-
Notifications
You must be signed in to change notification settings - Fork 0
/
fleet.go
73 lines (66 loc) · 1.41 KB
/
fleet.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
package main
import (
"sync"
"time"
"github.com/nsf/termbox-go"
)
// Fleet is a type to handle multiple ships
type Fleet struct {
ships map[*Ship]bool
direction int
stopCh chan bool
dirCh chan int
lock sync.Mutex
}
func (fleet *Fleet) run() {
direction := fleet.direction
for {
if len(fleet.ships) == 0 {
cleanExit()
}
select {
case direction = <-fleet.dirCh:
case <-time.After(500000 * time.Microsecond):
// Move all ships in the fleet and let them fire
for ship, _ := range fleet.ships {
ship.moveCh <- direction
ship.fireFromFleet()
}
case <-fleet.stopCh:
fleet.lock.Lock()
for ship, _ := range fleet.ships {
ship.stopCh <- true
}
return
}
}
}
// Initialize a fleet of enemy ships
func initFleet(size sizes, matrix [][]*Ship) {
fleet := Fleet{
ships: make(map[*Ship]bool),
direction: -1,
stopCh: make(chan bool),
dirCh: make(chan int),
}
midX := size.width / 2
for j := 0; j < 3; j++ {
for i := 0; i < 10; i++ {
ship := &Ship{
view: [][]rune{{'(', '=', ')'}, {'\\', ' ', '/'}},
positionX: midX - (-5+i)*5 - 5,
positionY: 2 + 3*j,
stopCh: make(chan bool),
moveCh: make(chan int),
fleet: &fleet,
size: &size,
matrix: matrix,
fg: termbox.ColorYellow,
bg: termbox.ColorDefault,
}
go ship.run()
fleet.ships[ship] = true
}
}
go fleet.run()
}