-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaze.go
136 lines (111 loc) · 2.35 KB
/
maze.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"bufio"
"os"
"sync"
"time"
)
type Maze struct {
Layout []string
Player *Player
Ghosts []*Ghost
GhostStatusMx sync.RWMutex
NumDots int
PillTimer *time.Timer
PillTimerEnd time.Time
pillMx sync.Mutex
}
func NewMaze(filename string) (*Maze, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
var layout []string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
layout = append(layout, line)
}
maze := &Maze{Layout: layout}
return maze.Populate(), nil
}
func (m *Maze) Populate() *Maze {
for row, line := range m.Layout {
for col, char := range line {
switch char {
case 'P':
m.Player = NewPlayer(row, col, cfg.PlayerLives)
case 'G':
m.Ghosts = append(m.Ghosts, NewGhost(row, col))
case '.':
m.NumDots++
}
}
}
return m
}
func (m *Maze) MovePlayer(direction string) {
m.Player.Move(direction)
removeDot := func(row, col int) {
m.Layout[row] = m.Layout[row][0:col] + " " + m.Layout[row][col+1:]
}
switch m.Layout[m.Player.Row][m.Player.Col] {
case '.':
m.NumDots--
m.Player.Score++
removeDot(m.Player.Row, m.Player.Col)
case 'X':
m.Player.Score += cfg.PillScore
removeDot(m.Player.Row, m.Player.Col)
go m.processPill()
}
}
func (m *Maze) MoveGhosts() {
for _, ghost := range m.Ghosts {
ghost.Move()
if m.Player.Row == ghost.Row && m.Player.Col == ghost.Col {
m.GhostStatusMx.Lock()
if ghost.IsThreat {
m.Player.LoseLife()
} else {
m.Player.Score += cfg.GhostDefeatScore
ghost.Defeat()
}
m.GhostStatusMx.Unlock()
}
}
}
func (m *Maze) swapGhosts(toStatus string) {
m.GhostStatusMx.Lock()
defer m.GhostStatusMx.Unlock()
for _, ghost := range m.Ghosts {
switch toStatus {
case "threat":
ghost.IsThreat = true
default:
ghost.IsThreat = false
}
}
}
func (m *Maze) processPill() {
m.pillMx.Lock()
defer m.pillMx.Unlock()
m.swapGhosts("safe")
m.setPillTimer()
m.pillMx.Unlock()
<-m.PillTimer.C
m.pillMx.Lock()
m.PillTimer.Stop()
m.swapGhosts("threat")
}
func (m *Maze) setPillTimer() {
pillTime := cfg.PillDuration
if m.PillTimer != nil {
m.PillTimer.Stop()
pillTime += time.Until(maze.PillTimerEnd)
maze.PillTimerEnd = time.Now()
}
m.PillTimer = time.NewTimer(pillTime)
m.PillTimerEnd = time.Now().Add(pillTime)
}