-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguessnumber.go
More file actions
78 lines (70 loc) · 1.37 KB
/
guessnumber.go
File metadata and controls
78 lines (70 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"math/rand"
"time"
)
const maxTries = 3
const min = 1;
const max = 9;
var answers = map[int]string{
-1: "Your number is less",
0: "Your number is the same, you WON !",
1: "Your number is more",
maxTries: "You Lose !",
}
func main() {
rand.Seed(time.Now().UnixNano())
for again := true; again; again = askAgain() {
playOnce()
}
}
func playOnce() {
guess := min - 1
tries := 0
number := rand.Intn(max + 1 - min) + min
fmt.Print("Guess number (", min, "..", max, "): ")
for tries < maxTries && guess != number {
if _, err := fmt.Scan(&guess); err != nil {
fmt.Print("No! Type a number (", min, "..", max, "): ")
continue
}
tries++
triesLeft := maxTries - tries;
won := guess == number
lost := !won && triesLeft == 0
nexttry := !won && !lost
switch {
case won:
printAnswer(0)
case lost:
fmt.Println("Number was ", number)
printAnswer(maxTries)
case nexttry:
printAnswer(Sign(guess - number))
fmt.Print("Try ", triesLeft, " more time(s): ")
}
}
}
func printAnswer(key int) {
if val, ok := answers[key]; ok {
fmt.Println(val)
} else {
fmt.Println("bug! no key!")
}
}
func Sign(a int) int {
switch {
case a < 0:
return -1
case a > 0:
return +1
}
return 0
}
func askAgain() bool {
fmt.Print("Again(y/n)? ")
confirm := "";
fmt.Scan(&confirm)
return confirm == "y"
}