-
Notifications
You must be signed in to change notification settings - Fork 1
/
game.go
90 lines (74 loc) · 1.44 KB
/
game.go
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
79
80
81
82
83
84
85
86
87
88
89
90
// Samples used in a small go tutorial
//
// Copyright (C) 2017 framp at linux-tips-and-tricks dot de
//
// Samples for go templates
//
// See github.com/framps/golang_tutorial for latest code
package game
import (
"fmt"
"math/rand"
)
// States -
type States int
const (
// GameInitialized -
GameInitialized States = iota
// GameRunning -
GameRunning
// GameFinished -
GameFinished
)
// CurrentScore -
type CurrentScore struct {
Low int
High int
Guesses int
}
// HighLow -
type HighLow struct {
ActualValue int
State States
CurrentScore
}
const ( // upper and lower bounds
lowLimit = 1
highLimit = 99
)
// NewHighLow - Create new game
func NewHighLow() *HighLow {
return &HighLow{
rand.Intn(highLimit-lowLimit+1) + lowLimit,
GameInitialized,
CurrentScore{
Low: lowLimit - 1,
High: highLimit + 1,
Guesses: 0,
},
}
}
// GetState -
func (h *HighLow) GetState() (s States) {
return h.State
}
// Guess - execute a guess
func (h *HighLow) Guess(guess int) (hit bool, err error) {
if guess <= h.Low || guess >= h.High { // check guess
err := fmt.Errorf("Number %d is out of bounds\n", guess)
return false, err
}
h.Guesses++ // another round
if h.ActualValue == guess { // hit
h.State = GameFinished
return true, nil
}
switch h.ActualValue > guess { // set lower/upper value accordingly
case true:
h.Low = guess
case false:
h.High = guess
}
h.State = GameRunning
return false, nil
}