-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
215 lines (185 loc) · 6.79 KB
/
game.py
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import pygame
import random
from Vector import Vector
from NeuralNetwork import NeuralNetwork as NN
pygame.init()
class SnakeGame:
def __init__(self, window=False):
self.length = 0
self.history = []
self.lastMove = None
self.brain = NN([24, 20, 5, 4])
self.isDead = False
self.speed = 20
self.rows = 50
self.cols = 50
self.width = self.rows * self.speed
self.height = self.rows * self.speed
self.pos = Vector(self.speed * self.cols / 2, self.speed * self.rows / 2)
self.food = Vector(500, random.randrange(0, self.height, self.speed))
self.window = False
if window:
self.window = True
self.display_screen = pygame.display.set_mode(
(self.width, self.height))
pygame.display.set_caption("Snake game")
self.clock = pygame.time.Clock()
def updateHistory(self):
if self.length != 0:
if self.length == len(self.history):
newHis = []
for i in range(len(self.history) - 1):
newHis.append(self.history[i + 1].copy())
newHis.append(self.pos.copy())
else:
newHis = self.history
newHis.append(self.pos.copy())
self.history = newHis
def move(self, dir):
if dir == "Up":
if self.lastMove != "Down":
self.pos.y += self.speed
self.lastMove = "Up"
else:
self.pos.y -= self.speed
self.lastMove = "Down"
elif dir == "Down":
if self.lastMove != "Up":
self.pos.y -= self.speed
self.lastMove = "Down"
else:
self.pos.y += self.speed
self.lastMove = "Up"
elif dir == "Right":
if self.lastMove != "Left":
self.pos.x += self.speed
self.lastMove = "Right"
else:
self.pos.x -= self.speed
self.lastMove = "Left"
elif dir == "Left":
if self.lastMove != "Right":
self.pos.x -= self.speed
self.lastMove = "Left"
else:
self.pos.x += self.speed
self.lastMove = "Right"
else:
if self.lastMove == None:
self.pos.x += self.speed
self.lastMove = "Right"
else:
self.move(self.lastMove)
def eats(self):
return self.pos == self.food
def hitsWal(self):
return self.pos.x < 0 or self.pos.x >= self.width or self.pos.y < 0 or self.pos.y >= self.height
def hitsSnake(self):
hitting = False
for v in self.history:
if self.pos == v:
hitting = True
break
return hitting
def calculateVision(self):
vision = []
tempValues = self.lookInDirection(Vector(-self.speed, 0))
for num in tempValues:
vision.append(num)
tempValues = self.lookInDirection(Vector(-self.speed, -self.speed))
for num in tempValues:
vision.append(num)
tempValues = self.lookInDirection(Vector(0, -self.speed))
for num in tempValues:
vision.append(num)
tempValues = self.lookInDirection(Vector(self.speed, -self.speed))
for num in tempValues:
vision.append(num)
tempValues = self.lookInDirection(Vector(self.speed, 0))
for num in tempValues:
vision.append(num)
tempValues = self.lookInDirection(Vector(self.speed, self.speed))
for num in tempValues:
vision.append(num)
tempValues = self.lookInDirection(Vector(0, self.speed))
for num in tempValues:
vision.append(num)
tempValues = self.lookInDirection(Vector(-self.speed, self.speed))
for num in tempValues:
vision.append(num)
return vision
def lookInDirection(self, vector):
visionInDirection = [0, 0, 0]
position = self.pos.copy()
foodIsFound = False
tailIsFound = False
distance = 0
position += vector
distance += 1
while position.x > 0 and position.y > 0 and position.x <= self.width and position.y <= self.height:
if not foodIsFound and position == self.food:
visionInDirection[0] = 1
foodIsFound = True
if not tailIsFound:
for v in self.history:
if position == v:
tailIsFound = True
visionInDirection[1] = 1 / distance
position += vector
distance += 1
visionInDirection[2] = 1 / distance
return visionInDirection
def guess(self, vision):
output_matrix = self.brain.feedforward(vision)
outputs = output_matrix.toArray()
guessIndex = outputs.index(max(outputs))
return ["Up", "Down", "Left", "Right"][guessIndex]
def update(self):
self.updateHistory()
vision = self.calculateVision()
choice = self.guess(vision)
print(vision)
print(choice)
if choice != None:
self.move(choice)
else:
self.move(self.lastMove)
if self.hitsWal() or self.hitsSnake():
print("died ", self.length, " ", self.pos)
self.isDead = True
if self.eats():
self.length += 1
self.food = Vector(random.randrange(0, self.width, self.speed), random.randrange(0, self.height, self.speed))
def run(self):
self.update()
def getKeyInput(self):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
return "Left"
if event.key == pygame.K_RIGHT:
return "Right"
if event.key == pygame.K_UP:
return "Down"
if event.key == pygame.K_DOWN:
return "Up"
return None
def show(self):
self.display_screen.fill((0, 0, 0))
pygame.draw.rect(self.display_screen, (255, 255, 255), [self.pos.x, self.pos.y, self.speed, self.speed])
for v in self.history:
pygame.draw.rect(self.display_screen, (255, 255, 255), [v.x, v.y, self.speed, self.speed])
pygame.draw.rect(self.display_screen, (255, 0, 100), [self.food.x, self.food.y, self.speed, self.speed])
pygame.display.update()
self.clock.tick(5)
sg = SnakeGame(True)
while not sg.isDead:
sg.run()
if sg.window:
sg.show()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sg.isDead = True
break
pygame.quit()
quit()