-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake_game_ga.py
258 lines (224 loc) · 7.2 KB
/
snake_game_ga.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import pygame as game
import random, copy
from ga import *
from neuralNetwork_API import *
height = 800
width = 800
rezolution = 10
fps = 60
#populationSize = random.randint(1,10000)
populationSize = 100
savedSnakes = []
snakes = []
bestSnakesOfEachGen = []
xy = 1
def nextGeneration(RestSnakes):
for i in range (100):
snakes.append(Snake(5))
global savedSnakes,snakes,xy
xy = 1
print("New Generation")
calcFitness()
for i in range(populationSize-1):
snakes.append(pickOne(RestSnakes,xy))
savedSnakes = []
return snakes
def pickOne(RestSnakes,x):
global savedSnakes, currentGen,highscore, xy
index = 0
r = random.uniform(0.0,1.0)
while (r > 0 and index <99):
r = r - savedSnakes[index-RestSnakes].fitness
index += 1
parent = savedSnakes[index-5]
bestSnakesOfEachGen.append(parent)
if currentGen > 350 or highscore > 300:
filename = "genData/best_of_all.npy"
parent.brain.saveNetwork(filename)
if xy != 0:
filename = "genData/best_of_gen_"+str(currentGen) +".npy"
parent.brain.saveNetwork(filename)
child = Snake(parent.brain)
child.brain.mutate(0.1)
xy = 0
return child
def calcFitness():
global savedSnakes
sum = 0
for snake in savedSnakes:
sum += snake.score
for snake in savedSnakes:
snake.fitness = snake.score / sum
class Snake:
def __init__(self,brain):
self.score = 1
self.body = []
x = random.randint(0,width/rezolution)
y = random.randint(0,height/rezolution)
x *= rezolution
y *= rezolution
if x == width:
x-=rezolution
if y == height:
y -= rezolution
if y == height:
y -= rezolution
if x == 0:
x+= rezolution
if y == 0:
y += rezolution
self.body.append([x,y])
self.xdir = 1
self.ydir = 0
self.food = [width/2+rezolution/2,height/2+rezolution/2+60]
self.newFood()
if type(brain)!= int:
self.brain = copy.copy(brain)
else:
self.brain = neuralNetwork(12,20,5,0.2)
self.lastDecisions = []
self.fitness = 0
def grow(self):
self.score += 1
global fps
head = copy.copy(self.body[len(self.body) -1 ])
self.body.append(head)
fps *= 1.1
def eat(self):
x = self.body[len(self.body) -1][0]
y = self.body[len(self.body) -1][1]
if (x == self.food[0] and y == self.food[1]):
self.grow()
return True
return False
def think(self):
inputs = getInputArray(self,width,height)
outputs = self.brain.query(inputs)
decision = np.argmax(outputs)
self.lastDecisions.append(decision)
if (len(self.lastDecisions)>4 and decision == self.lastDecisions[-5]):
if decision != 4:
decision += 1
else:
decision = 0
if decision == 0:
self.setDir(-1,0) #go left
elif decision == 1:
self.setDir(1,0) #go right
elif decision == 2:
self.setDir(0,-1) #go up
elif decision == 3:
self.setDir(0,1) #go down
elif decision == 4:
nothing = 1 #stay in direction
else:
print("Error with outputs: ",outputs)
def endGame(self):
x = self.body[len(self.body) -1 ][0]
y = self.body[len(self.body) -1 ][1]
if (x > width-rezolution/2 or x < 0 or y > height-rezolution/2 or y < 0):
return True
for i in range(0,len(self.body)-15):
part = self.body[i]
if (part[0]==x and part[1] == y):
return True
return False
def draw(self):
for i in range(len(self.body)):
game.draw.rect(window, game.Color(255,255,255),(self.body[i][0],self.body[i][1],rezolution,rezolution))
def setDir(self,x,y):
self.xdir = x
self.ydir = y
def update(self):
head = copy.copy(self.body[len(self.body)-1])
self.body.remove(self.body[0])
head[0] += self.xdir * rezolution
head[1] += self.ydir * rezolution
self.body.append(head);
def newFood(self):
x = random.randint(0,width/rezolution)
y = random.randint(0,height/rezolution)
x *= rezolution
y *= rezolution
if x == width:
x-=rezolution
if y == height:
y -= rezolution
self.food = [x,y]
if (self.food in self.body):
self.newFood()
def showFood(self):
game.draw.rect(window, (255,0,0),(self.food[0],self.food[1],rezolution,rezolution))
game.init()
for i in range(populationSize):
snakes.append(Snake(5))
window = game.display.set_mode((height,width))
clock = game.time.Clock()
game.display.set_caption("Snake Game")
myfont = game.font.SysFont("Comic Sans MS", 30)
currentGen = 1
cols = int(width/rezolution)
rows = int(height/rezolution)
highscore = 0
i = 0
run = True
while run:
if currentGen > 355:
run = False
clock.tick(fps)
if currentGen == 15:
fps = 10
textsurface = myfont.render("highest Score: "+str(highscore), False, (255,255,255))
window.fill((50,50,50))
for snake in snakes:
snake.think()
if (snake.eat()):
snake.newFood()
snake.draw()
if i %2 == 0 :
snake.update()
snake.update()
snake.showFood()
if snake.score> highscore:
i = 0
highscore = snake.score
if snake.endGame() :
savedSnakes.append(snake)
snakes.remove(snake)
for y in range(rows):
y *= rezolution
for x in range(cols):
x *= rezolution
game.draw.line(window,(0,0,0),(x,y),(x+rezolution,y),rezolution/10)
game.draw.line(window,(0,0,0),(x+rezolution,y),(x+rezolution,y+rezolution),rezolution/10)
game.draw.line(window,(0,0,0),(x+rezolution,y+rezolution),(x,y+rezolution),rezolution/10)
game.draw.line(window,(0,0,0),(x,y+rezolution),(x,y),rezolution/10)
for y in range(rows):
y *= rezolution
for x in range(cols):
x *= rezolution
game.draw.line(window,(0,0,255),(x,y),(x+rezolution,y),rezolution/10)
game.draw.line(window,(0,0,255),(x+rezolution,y),(x+rezolution,y+rezolution),rezolution/10)
game.draw.line(window,(0,0,255),(x+rezolution,y+rezolution),(x,y+rezolution),rezolution/10)
game.draw.line(window,(0,0,255),(x,y+rezolution),(x,y),rezolution/10)
if (currentGen < 350 and len(snakes) < 2):
snakes = []
snakes = nextGeneration(1)
currentGen += 1
i= 0
highscore = 0
if (i>1000):
highscore = 0
i = 0
left = len(snakes)
print(left)
snakes = []
snakes = nextGeneration(left+populationSize/20)
currentGen += 1
textsurface2 = myfont.render("Gen: "+str(currentGen),False, (255,255,255))
window.blit(textsurface,(width-rezolution*50,height/20))
window.blit(textsurface2,(0+rezolution*3,height/20))
game.display.update()
i += 1
print(i)
game.quit()