-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGAMEOBJECT.py
671 lines (611 loc) · 31.3 KB
/
GAMEOBJECT.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import pickle
import os
#
import itertools
from main import *
import neat, pygame
class GameObject:
"""Oyun objesi."""
# @auto_assign_arguments
def __init__(self, genomes, config, height=640, width=800, keepgoing=True, currentLevel=1, game_over=False,
fps=9999, screenshow=True, inputNum=20,
use_closest_rocket: bool = True,
use_closest_fuel: bool = False,
use_closest_stone: bool = False,
use_closest_enemy1s: bool = True,
use_missile_points: bool = False,
use_bullet_points: bool = True,
use_missile_interactions: bool = False,
use_top_interactions: bool = True,
use_bot_interactions: bool = True,
use_bullet_interactions: bool = True,
use_fuel: bool = True,
use_image_repr: bool = False):
if not screenshow:
os.environ["SDL_VIDEODRIVER"] = "dummy"
# Used NN Input Parameters
self.use_closest_rocket = use_closest_rocket
self.use_closest_fuel = use_closest_fuel
self.use_closest_stone = use_closest_stone
self.use_closest_enemy1s = use_closest_enemy1s
self.use_missile_points = use_missile_points
self.use_bullet_points = use_bullet_points
self.use_missile_interactions = use_missile_interactions
self.use_bullet_interactions = use_bullet_interactions
self.use_top_interactions = use_top_interactions
self.use_bot_interactions = use_bot_interactions
self.use_image_repr = use_image_repr
self.use_fuel = use_fuel
self.screenshow = screenshow
pygame.init()
self.white = (255, 255, 255)
pygame.mixer.init()
self.currentLevel = currentLevel
self.fps = fps
self.width = width
self.height = height
self.keepgoing = keepgoing
self.g = genomes
self.config = config
self.nets = []
self.ge = []
self.spaceships = []
self.game_over = game_over
if use_image_repr:
# for image representation input
self.RED = (255, 0, 0)
self.GREEN = (0, 255, 0)
self.BLUE = (0, 0, 255)
self.xnodePos = [[0 for x in range(inputNum)] for y in range(inputNum * 3)]
self.ynodePos = [[0 for x in range(inputNum)] for y in range(inputNum * 3)]
self.nodePos = list(zip(self.xnodePos, self.ynodePos))
self.inputNum = inputNum
self.inputImage = [[0 for i in range(self.inputNum)] for j in range(self.inputNum * 3)]
for x in range(0, inputNum):
for y in range(0, inputNum):
if (x % 2 == 0):
self.inputImage[x][y] = self.GREEN
else:
self.inputImage[x][y] = self.BLUE
# endfor
if self.screenshow:
self.initScreen()
self.fillBackground()
self.blit()
else:
self.clock = pygame.time.Clock()
self.lives = [Lives(1)]
self.initSprites()
self.load_data()
self.update()
def update(self):
"""Update fonksiyonu her frame de çağrılır."""
for genome_id, genome in self.g:
genome.fitness = 0 # start with fitness level of 0
net = neat.nn.FeedForwardNetwork.create(genome, self.config)
while self.spaceship.lives >= 0:
if self.spaceship.lives == 0:
# self.game_over = True
self.keepgoing = True
self.initSprites()
self.keepGoing(strt=False)
print("Species: " + str(genome_id))
break
else:
self.keepGoing()
self.colliders()
self.spriteUpdate()
# ********** INPUTS ************ #
params = [self.spaceship.rect.right, self.spaceship.rect.left,
self.spaceship.rect.bottom, self.spaceship.rect.top]
if self.use_closest_rocket:
closest_rocket = get_closest(self.spaceship, self.enemy3Sprites, self.width)
params.extend([[closest_rocket.rect.left if closest_rocket else 0][0],
[closest_rocket.rect.top if closest_rocket else 0][0],
[closest_rocket.rect.bottom if closest_rocket else 0][0],
[closest_rocket.rect.right if closest_rocket else 0][0], ])
if self.use_closest_fuel:
closest_fuel = get_closest(self.spaceship, self.fuelSprites, self.width)
params.extend([
[closest_fuel.rect.left if closest_fuel else 0][0],
[closest_fuel.rect.top if closest_fuel else 0][0],
])
if self.use_closest_stone:
closest_stone = get_closest(self.spaceship, self.stoneSprites, self.width)
params.extend([
[closest_stone.rect.left if closest_stone else 0][0],
[closest_stone.rect.top if closest_stone else 0][0],
])
if self.use_closest_enemy1s:
closest_enemy1s = get_closest_n(self.spaceship, self.enemy1Sprites, 3, self.width)
ces = [[ce.rect.left, ce.rect.right, ce.rect.top, ce.rect.bottom] if ce else [0, 0, 0, 0] for ce
in
closest_enemy1s]
params.extend([ces[0][0], ces[0][1], ces[0][2], ces[0][3],
ces[1][0], ces[1][1], ces[1][2], ces[1][3],
ces[2][0], ces[2][1], ces[2][2], ces[2][3]]
# ces[3][0], ces[3][1], ces[3][2], ces[3][3],
# ces[4][0], ces[4][1], ces[4][2], ces[4][3]]
)
if self.use_top_interactions:
top_points = calculate_top_points(self.spaceship)
top_intersections = check_linecol(self.spaceship, self.all_sp, top_points)
params.extend([
[top_intersections[0][0] if top_intersections else top_points[0]][0],
[top_intersections[0][1] if top_intersections else top_points[1]][0],
])
if self.use_top_interactions:
bottom_points = calculate_bottom_points(self.spaceship, self.height)
bot_intersections = check_linecol(self.spaceship, self.all_sp, bottom_points)
params.extend([
[bot_intersections[0][0] if bot_intersections else bottom_points[0]][0],
[bot_intersections[0][1] if bot_intersections else bottom_points[1]][0]
])
if self.use_bullet_points:
bullet_points = calculate_bullet_points(self.spaceship, self.width)
if self.use_bullet_interactions:
bullet_intersections = check_linecol(self.spaceship, self.all_sp, bullet_points)
params.extend([
[bullet_intersections[0][0] if bullet_intersections else bullet_points[0]][0],
[bullet_intersections[0][1] if bullet_intersections else bullet_points[1]][0],
])
if self.use_missile_points:
missile_points = calculate_missile_points(self.spaceship, self.height)
if self.use_missile_interactions:
missile_intersections = check_linecol(self.spaceship, self.all_sp, missile_points)
params.extend([
[missile_intersections[0][0] if missile_intersections else missile_points[0]][0],
[missile_intersections[0][1] if missile_intersections else missile_points[1]][0],
])
# enemy1_distanceX, enemy1_distanceY = map(list,
# zip(*get_distances(self.spaceship, self.enemy1Sprites)))
# fuel_distanceX, fuel_distanceY = map(list,
# zip(*get_distances(self.spaceship, self.fuelSprites)))
# rocket_distanceX, rocket_distanceY = map(list,
# zip(*get_distances(self.spaceship, self.enemy3Sprites)))
# enemy1_x, enemy1_y = map(list,
# zip(*get_positions(self.enemy1Sprites)))
# enemy3_x, enemy3_y = map(list,
# zip(*get_positions(self.enemy3Sprites)))
# stone_x, stone_y = map(list,
# zip(*get_positions(self.stoneSprites)))
# fuel_x, fuel_y = map(list, zip(*get_positions(self.fuelSprites)))
# inp = np.array(self.inputImage, dtype='object').flatten()
# inp = [1 if x == self.RED else 2 if x == self.GREEN else 0 for x in inp]
# inp = list(map(lambda x: 1 if x==self.RED else 2 if x==self.GREEN else 0, inp))
# inp = np.where(np.array(inp) == self.GREEN, 1,
# np.where(np.array(inp) == self.RED, 2, 0))
output = net.activate(params)
# print(self.clock.get_fps())
self.spaceship.play(output)
genome.fitness = self.spaceship.score
if self.screenshow:
self.clear()
self.draw(
draw_closest_rocket=self.use_closest_rocket,
draw_closest_fuel=self.use_closest_fuel,
draw_closest_stone=self.use_closest_stone,
draw_closest_enemy1s=self.use_closest_enemy1s,
draw_missile_points=self.use_missile_points,
draw_bullet_points=self.use_bullet_points,
draw_missile_interactions=self.use_missile_interactions,
draw_bullet_interactions=self.use_bullet_interactions,
draw_top_interactions=self.use_top_interactions,
draw_bot_interactions=self.use_bot_interactions,
draw_image_repr=self.use_image_repr,
draw_fuel=self.use_fuel,
)
# fill_image(inputNum=self.inputNum, inputImg=self.inputImage, HEIGHT=self.height, WIDTH=self.width,
# enemies=[*self.enemy1Sprites.sprites(), *self.enemy3Sprites.sprites()],
# spaceship=self.spaceship)
self.isThisTheEnd()
self.nets.append(net)
self.ge.append(genome)
if self.screenshow:
pygame.display.flip()
def isThisTheEnd(self):
"""Oyun sonu"""
if self.theEndGame.end():
try:
print("yeyy")
self.spaceship.score += 100
self.spaceship.lives -= 1
# self.level()
except Exception as ex:
pygame.quit()
def level(self):
"""her bir level için "-" karakteri mapteki taşları;
"x" karakteri mapteki fuel, yani yakıt objelerini;
"e" karakteri düşman füzeleri çağırır."""
self.isWave1 = True
self.wave_1()
y = 0
level1 = []
world = []
level = open('levels/level' + str(self.currentLevel) + 'a')
for i in level:
level1.append(i)
for row in level1:
x = 0
for col in row:
if col == "-":
self.stone = Stone()
world.append(self.stone)
self.stoneSprites.add(world)
self.stone.rect.x = x
self.stone.rect.y = y
if col == "x":
self.fuel = Fuels()
self.fuelSprites.add(self.fuel)
self.fuel.rect.x = x
self.fuel.rect.y = y
if col == "e":
self.enemy3 = Enemy3()
self.enemy3Sprites.add(self.enemy3)
self.enemy3.rect.x = x
self.enemy3.rect.y = y
if col == "]":
self.theEndGame = TheEndGame()
self.stoneSprites.add(self.theEndGame)
self.theEndGame.rect.x = x
self.theEndGame.rect.y = y
x += 32
y += +32
self.all_sp = pygame.sprite.Group(*self.enemy1Sprites.sprites(), *self.enemy3Sprites.sprites(),
*self.fuelSprites.sprites(), *self.stoneSprites.sprites())
def draw_player_fuel(self, surf, x, y, pct):
"""Oyuncu karakterin yakıt seviyesi için görselleştirme."""
if pct < 0:
pct = 0
BAR_LENGTH = 100
BAR_HEIGHT = 20
fill = pct * BAR_LENGTH
outline_rect = pygame.Rect(x, y, BAR_LENGTH * 2, BAR_HEIGHT)
fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
if pct > 0.6:
col = (0, 255, 0)
elif pct > 0.3:
col = (255, 255, 0)
else:
col = (255, 0, 0)
pygame.draw.rect(surf, col, fill_rect)
pygame.draw.rect(surf, self.white, outline_rect, 2)
def load_data(self, HS_FILE='HighScore'):
"""Oyuncu yüksek skor yaparsa bu skor kaydedilir."""
# load high score
self.dir = os.path.dirname(__file__)
with open(os.path.join(self.dir, HS_FILE), 'r') as f:
try:
self.highscore = int(f.read())
except:
self.highscore = 0
def colliders(self):
"""ana karakterin, mermilerin, füzelerin ve düşmanların çarpışma ve patlama efektleri."""
# bullet-fuel collider
fuel_hit_by_bullet = pygame.sprite.groupcollide(self.fuelSprites, self.shootSprites, True, True)
for hit in fuel_hit_by_bullet:
expl = Explosion(hit.rect.center, 'sm')
self.explosionSprites.add(expl)
if fuel_hit_by_bullet:
self.spaceship.fuel += 10
self.spaceship.score += 5
# bullet-enemy collider
bullethits = pygame.sprite.groupcollide(self.enemy1Sprites, self.shootSprites, True, True)
for hit in bullethits:
expl = Explosion(hit.rect.center, 'sm')
self.explosionSprites.add(expl)
if bullethits:
self.spaceship.score += 10
# bullet-enemy collider
bullethits = pygame.sprite.groupcollide(self.enemy3Sprites, self.shootSprites, True, True)
for hit in bullethits:
expl = Explosion(hit.rect.center, 'sm')
self.explosionSprites.add(expl)
if bullethits:
self.spaceship.score += 10
# player-enemy collider
spaceshiphits = pygame.sprite.spritecollide(self.spaceship, self.enemy1Sprites, True)
for hit in spaceshiphits:
expl = Explosion(hit.rect.center, 'sm')
self.explosionSprites.add(expl)
if spaceshiphits:
self.spaceship.score -= 50
self.spaceship.lives -= 1
self.lives[-1].kill()
del self.lives[-1]
# player-enemy collider
spaceshiphits = pygame.sprite.spritecollide(self.spaceship, self.enemy3Sprites, True)
for hit in spaceshiphits:
expl = Explosion(hit.rect.center, 'sm')
self.explosionSprites.add(expl)
if spaceshiphits:
self.spaceship.score -= 50
self.spaceship.lives -= 1
try:
self.lives[-1].kill()
del self.lives[-1]
except:
print(self.lives)
# player-enemy collider
spaceshiphits = pygame.sprite.spritecollide(self.spaceship, self.enemy2Sprites, True)
for hit in spaceshiphits:
expl = Explosion(hit.rect.center, 'sm')
self.explosionSprites.add(expl)
if spaceshiphits:
self.spaceship.score -= 50
self.spaceship.lives -= 1
try:
self.lives[-1].kill()
except:
print(self.lives)
del self.lives[-1]
# spaceship-ground collider
spaceshiphitsground = pygame.sprite.spritecollide(self.spaceship, self.stoneSprites, False)
if spaceshiphitsground:
self.spaceship.lives = 0
self.spaceship.score -= 50
# rocket-ground collider
rockethitsground = pygame.sprite.groupcollide(self.shootSprites, self.stoneSprites, True, False)
for hit in rockethitsground:
expl = Explosion(hit.rect.center, 'sm')
self.explosionSprites.add(expl)
def initSprites(self):
"""Bütün spriteları(düşman,oyuncu,yakıt,roket,taş,patlama,can) aktifleştirir"""
# Sprites
self.space = Background(0)
self.space1 = Background(1)
# sprite groups
self.explosionSprites = pygame.sprite.Group()
self.systemSprites = pygame.sprite.Group([self.space, self.space1])
self.liveSprites = pygame.sprite.Group()
for i in self.lives:
self.liveSprites.add(i)
self.enemy1Sprites = pygame.sprite.Group()
self.enemy2Sprites = pygame.sprite.Group()
self.enemy3Sprites = pygame.sprite.Group()
self.mobs = pygame.sprite.Group()
self.fuelSprites = pygame.sprite.Group()
self.shootSprites = pygame.sprite.Group()
self.stoneSprites = pygame.sprite.Group()
self.spaceship = SpaceShip(self.shootSprites, self.width, self.height)
self.userSprites = pygame.sprite.Group(self.spaceship)
self.rocket = Rockets(self.spaceship.rect.right, self.spaceship.rect.center[1], self.spaceship.rangey)
def keepGoing(self, isWave1=False, isWave2=False, strt=False):
"""1. ve 2. düşman dalgalarını ve oyun bitiş, açılış ekranını kontrol eder."""
self.isWave1 = isWave1
self.isWave2 = isWave2
if self.keepgoing:
if strt:
self.show_strt_screen()
self.keepgoing = False
self.lives = [Lives(i) for i in range(1, self.spaceship.lives + 1)]
self.initSprites()
self.level()
if self.game_over:
self.show_go_screen()
self.game_over = False
self.lives = [Lives(i) for i in range(1, self.spaceship.lives + 1)]
self.initSprites()
self.currentLevel = 1
self.level()
self.clock.tick(self.fps)
pygame.mouse.set_visible(False)
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
def show_go_screen(self, HS_FILE='HighScore'):
"""oyun bitiş ekranı"""
self.screen.blit(self.background, (0, 0))
draw_text(self.screen, "SCRAMBLE!", 64, self.width / 2, self.height / 4)
draw_text(self.screen, "Nice try, but not enough!", 22,
self.width / 2, self.height / 2)
draw_text(self.screen, "your score is:" + str(self.spaceship.score), 64, self.width / 2, self.height * 3 / 4)
draw_text(self.screen, "Press any key to play again", 18, self.width / 2, self.height * 8 / 9)
if self.spaceship.score > self.highscore:
self.highscore = self.spaceship.score
draw_text(self.screen, "NEW HIGH SCORE!!", 36, self.width / 2, self.height * 1 / 9)
with open(os.path.join(self.dir, HS_FILE), 'w') as f:
f.write(str(self.spaceship.score))
else:
draw_text(self.screen, "High Score: " + str(self.highscore), 18, self.width / 2, self.height * 1 / 9)
pygame.display.flip()
waiting = True
while waiting:
self.clock.tick(self.fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN and pygame.KEYUP:
waiting = False
def show_strt_screen(self):
"""oyun açılış ekranı"""
self.screen.blit(self.background, (0, 0))
draw_text(self.screen, "SCRAMBLE!", 64, self.width / 2, self.height / 4)
draw_text(self.screen, "Arrow keys move, Space to fire, R to fire rockets", 22,
self.width / 2, self.height / 2)
draw_text(self.screen, "Press a key to begin", 18, self.width / 2, self.height * 8 / 9)
draw_text(self.screen, "HighScore: " + str(self.highscore), 18, self.width / 2, self.height * 1 / 8)
pygame.display.flip()
waiting = True
while waiting:
self.clock.tick(self.fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYUP:
waiting = False
def initScreen(self):
"""ekranı, başlığı ve oyun saatini aktifleştirir."""
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption('Scramble Game')
self.clock = pygame.time.Clock()
def fillBackground(self):
"""arka fonu siyahla doldurur."""
self.background = pygame.Surface(self.screen.get_size())
self.background = self.background.convert()
self.background.fill((0, 0, 0))
def blit(self):
"""resimleri ekrana blitler."""
self.screen.blit(self.background, (0, 0))
pygame.display.flip()
def wave_1(self):
"""birinci düşman dalgası için yer ve level konfigurasyonu"""
# Event loop
if self.currentLevel == 1 or self.currentLevel == 3:
for i in range(80):
self.enemy = Enemy1()
self.enemy.rect.x = random.randrange(600, 8064, 10)
self.enemy.rect.y = random.randrange(10, self.height - 70, 10)
# self.enemySprites.add(self.enemy)
self.enemy1Sprites.add(self.enemy)
if self.currentLevel == 2 or self.currentLevel == 3:
for i in range(50):
self.enemy2 = Enemy2()
self.enemy2.rect.x = random.randrange(600, 8064)
self.enemy2.rect.y = random.randrange(0, self.height // 2 + 50)
self.enemy2Sprites.add(self.enemy2)
def clear(self):
"""ekranı temizler."""
self.systemSprites.clear(self.screen, self.background)
self.userSprites.clear(self.screen, self.background)
self.stoneSprites.clear(self.screen, self.background)
self.enemy2Sprites.clear(self.screen, self.background)
self.enemy1Sprites.clear(self.screen, self.background)
self.mobs.clear(self.screen, self.background)
self.enemy3Sprites.clear(self.screen, self.background)
self.fuelSprites.clear(self.screen, self.background)
self.shootSprites.clear(self.screen, self.background)
self.explosionSprites.clear(self.screen, self.background)
self.liveSprites.clear(self.screen, self.background)
def spriteUpdate(self):
"""bütün spriteların update fonksiyonlarını çalıştırır."""
self.systemSprites.update()
self.userSprites.update()
self.stoneSprites.update()
self.enemy2Sprites.update()
self.enemy1Sprites.update()
self.mobs.update()
self.enemy3Sprites.update()
self.fuelSprites.update()
self.shootSprites.update()
self.explosionSprites.update()
self.liveSprites.update()
def draw(self, draw_closest_rocket: bool = True, draw_closest_fuel: bool = True, draw_closest_stone: bool = True,
draw_closest_enemy1s: bool = True, draw_missile_points: bool = True, draw_bullet_points: bool = True,
draw_missile_interactions: bool = True, draw_bullet_interactions: bool = True, draw_fuel: bool = True,
draw_top_interactions: bool = True, draw_bot_interactions: bool = True, draw_image_repr: bool = False):
"""bütün spriteları ekrana çizer"""
self.systemSprites.draw(self.screen)
self.userSprites.draw(self.screen)
self.stoneSprites.draw(self.screen)
self.enemy2Sprites.draw(self.screen)
self.enemy1Sprites.draw(self.screen)
self.mobs.draw(self.screen)
self.enemy3Sprites.draw(self.screen)
self.fuelSprites.draw(self.screen)
self.shootSprites.draw(self.screen)
self.explosionSprites.draw(self.screen)
# self.liveSprites.draw(self.screen)
self.draw_player_fuel(self.screen, self.width / 2 - 100, self.height - 50, self.spaceship.fuel / 100)
if draw_closest_rocket:
closest_rocket = get_closest(self.spaceship, self.enemy3Sprites, self.width)
if closest_rocket:
pygame.draw.line(self.screen, "RED", (self.spaceship.rect.right, self.spaceship.rect.centery),
(closest_rocket.rect.centerx, closest_rocket.rect.top))
if draw_closest_fuel:
closest_fuel = get_closest(self.spaceship, self.fuelSprites, self.width)
if closest_fuel:
pygame.draw.line(self.screen, "GREEN", (self.spaceship.rect.right, self.spaceship.rect.centery),
(closest_fuel.rect.centerx, closest_fuel.rect.top))
if draw_closest_stone:
closest_stone = get_closest(self.spaceship, self.stoneSprites, self.width)
if closest_stone:
pygame.draw.line(self.screen, "BLUE", (self.spaceship.rect.right, self.spaceship.rect.centery),
(closest_stone.rect.centerx, closest_stone.rect.top))
if draw_missile_interactions:
missile_points = calculate_missile_points(self.spaceship, self.height)
missile_intersections = check_linecol(self.spaceship, self.enemy1Sprites, missile_points)
if missile_intersections:
pygame.draw.line(self.screen, "WHITE", (self.spaceship.rect.right, self.spaceship.rect.centery),
missile_intersections[0])
elif draw_missile_points:
pygame.draw.line(self.screen, "WHITE", (self.spaceship.rect.right, self.spaceship.rect.centery),
missile_points)
if draw_top_interactions:
top_points = calculate_top_points(self.spaceship)
top_intersections = check_linecol(self.spaceship, self.all_sp, top_points)
if top_intersections:
pygame.draw.line(self.screen, "PURPLE", (self.spaceship.rect.centerx, self.spaceship.rect.centery),
top_intersections[0])
else:
pygame.draw.line(self.screen, "WHITE", (self.spaceship.rect.centerx, self.spaceship.rect.centery),
top_points)
if draw_bot_interactions:
bottom_points = calculate_bottom_points(self.spaceship, self.height)
bot_intersections = check_linecol(self.spaceship, self.all_sp, bottom_points)
if bot_intersections:
pygame.draw.line(self.screen, "PURPLE", (self.spaceship.rect.centerx, self.spaceship.rect.centery),
bot_intersections[0])
else:
pygame.draw.line(self.screen, "WHITE", (self.spaceship.rect.centerx, self.spaceship.rect.centery),
bottom_points)
if draw_bullet_interactions:
bullet_points = calculate_bullet_points(self.spaceship, self.width)
bullet_intersections = check_linecol(
self.spaceship, pygame.sprite.Group([*self.enemy3Sprites, *self.enemy1Sprites]), bullet_points)
if bullet_intersections:
pygame.draw.line(self.screen, "PURPLE", (self.spaceship.rect.right, self.spaceship.rect.centery),
bullet_intersections[0])
elif draw_bullet_points:
pygame.draw.line(self.screen, "GREEN", (self.spaceship.rect.right, self.spaceship.rect.centery),
(800, self.spaceship.rect.centery))
if draw_closest_enemy1s:
closest_enemy1s = get_closest_n(self.spaceship, self.enemy1Sprites, 3, self.width)
[pygame.draw.line(
self.screen, "YELLOW",
(self.spaceship.rect.right, self.spaceship.rect.centery),
(e.rect.centerx, e.rect.centery)
) if e else None for e in closest_enemy1s]
# target_and_tri = line_of_sight(spaceship=self.spaceship, targets=self.all_sp)
# if target_and_tri[0]:
# pygame.draw.line(self.screen, "WHITE", (self.spaceship.rect.right, self.spaceship.rect.centery),
# target_and_tri[0])
# pygame.draw.line(self.screen, "WHITE", (self.spaceship.rect.right, self.spaceship.rect.centery),
# target_and_tri[1])
# pygame.draw.line(self.screen, "WHITE", (self.spaceship.rect.right, self.spaceship.rect.centery),
# target_and_tri[2])
if draw_image_repr:
fill_image(inputNum=self.inputNum, inputImg=self.inputImage, WIDTH=800, enemies=self.enemy1Sprites,
spaceship=self.spaceship)
size = 10
draw_neat(surf=self.screen, size=size, inputNum=self.inputNum, inputImg=self.inputImage,
xnodePos=self.xnodePos,
ynodePos=self.ynodePos, x=self.width / 2 - 500, y=(self.height) / 2 - 100)
if draw_fuel:
draw_text(self.screen, "FUEL ", 18, self.width / 2, self.height - 50)
draw_text(self.screen, str(self.spaceship.fuel), 24, self.width - 100, 24)
draw_text(self.screen, str(self.spaceship.score), 24, self.width - 24, 24)
def run(config_file):
config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation,
config_file)
# Create the population, which is the top-level object for a NEAT run.
p = neat.Population(config)
# Add a stdout reporter to show progress in the terminal.
p.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
p.add_reporter(stats)
# p.add_reporter(neat.Checkpointer(5))
winner = p.run(GameObject, 20)
stats.save_genome_fitness()
with open("winner.pkl", "wb") as f:
pickle.dump(winner, f)
f.close()
# show final stats
print('\nBest genome:\n{!s}'.format(winner))
if __name__ == '__main__':
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, 'network.txt')
run(config_path)
# GameObject(level=1, fps=60)