-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
643 lines (527 loc) · 21.3 KB
/
main.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
import os
import random
import numpy as np
from math import atan2, degrees, dist
import pygame
from pynput.keyboard import Key, Controller
keyboard = Controller()
class SpaceShip(pygame.sprite.Sprite):
"""oyuncu karakteri uzay gemisi, skor,yakıt,can,ateşleme ve hareket fonksiyonları"""
def __init__(self, collide, rangex=500, rangey=500):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/spaceship.png')
self.score = 0
self.fuel = 200
self.lives = 1
self.rect.x = 0
self.rect.y = (rangey // 2) - 40
self.collide = collide
self.laser = None
self.rocket = None
self.rocketready = False
self.shootable = False
self.maxTick = 10
self.tick = self.maxTick
self.maxRocket = 30
self.rangex = rangex
self.rangey = rangey
self.rockettick = self.maxRocket
def update(self, *args):
self.speedx = 0
self.speedy = 0
if self.tick == 0 and self.fuel >= 1:
self.shootable = True
self.tick = self.maxTick
else:
self.tick -= 1
if self.rockettick == 0 and self.fuel >= 2:
self.rocketready = True
self.rockettick = self.maxRocket
else:
self.rockettick -= 1
keystate = pygame.key.get_pressed()
if keystate[pygame.K_SPACE]:
self.shoot()
if keystate[pygame.K_r]:
self.missile()
if keystate[pygame.K_LEFT]:
self.left()
if keystate[pygame.K_RIGHT]:
self.right()
if self.rect.right > self.rangex - 10:
self.rect.right = self.rangex - 10
if self.rect.left < 0:
self.rect.left = 0
if keystate[pygame.K_UP]:
self.up()
if keystate[pygame.K_DOWN]:
self.down()
# self.rect.y += self.speedy
if self.rect.bottom > self.rangey - 50:
self.rect.bottom = self.rangey - 50
if self.rect.top < 20:
self.rect.top = 20
def up(self):
self.speedy = -8
self.rect.y += self.speedy
def down(self):
self.speedy = 8
self.rect.y += self.speedy
def right(self):
self.speedx = 8
self.rect.x += self.speedx
def left(self):
self.speedx = -8
self.rect.x += self.speedx
def shoot(self):
"""mermi ateşleme fonksiyonu"""
if self.shootable:
laser = Shoot(self.rect.right, self.rect.centery, self.rangex)
self.collide.add(laser)
self.fuel -= 1
self.score -= 1
self.shootable = False
def missile(self):
"""roket ateşleme fonksiyonu"""
if self.rocketready:
rocket = Rockets(self.rect.right, self.rect.center[1], self.rangey)
self.collide.add(rocket)
# self.fuel -= 2
self.score -= 2
self.rocketready = False
def play(self, predictions):
# print(predictions)
# print(self.rect)
if predictions[0] > 0.5:
# print("tried to shoot")
self.shoot()
# if predictions[1] > 0.5:
# # print("tried to missile")
# self.missile()
if predictions[1] > 0.5:
# print("tried to go up")
self.up()
if predictions[2] > 0.5:
# print("tried to go down")
self.down()
if predictions[3] > 0.5:
# print("tried to go right")
self.right()
if predictions[4] > 0.5:
# print("tried to go left")
self.left()
class Lives(pygame.sprite.Sprite):
"""karakterin canları"""
def __init__(self, lives=3):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/spaceship.png')
self.rect.x = (lives - 1) * 64
self.rect.y = 10
class Fuels(pygame.sprite.Sprite):
"""yakıt sınıfı"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/fuel.png')
def update(self, *args):
self.rect.x += -1
class Shoot(pygame.sprite.Sprite):
"""mermi sınıfı ve hareket fonksiyonu"""
def __init__(self, x, y, width):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/shot.gif')
self.rect.x = x
self.rect.y = y
self.width = width
# self.sndHit1 = pygame.mixer.Sound('data/laser.wav')
# hit
def update(self):
self.rect.x += 25
if self.rect.x > self.width:
self.kill()
class Rockets(pygame.sprite.Sprite):
"""karakterin ateşleyebildiği roket sınıfı ve hareket fonksiyonu"""
def __init__(self, x, y, width):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/rocket.png')
self.rect.x = x
self.rect.y = y
self.width = width
# self.rcktHit1 = pygame.mixer.Sound('data/boom.wav')
def update(self):
# self.count = 0
# self.rect.x = 20
self.rect.x += 2
self.rect.y += 10
if self.rect.y > self.width:
self.kill()
# if self.count > 8:
# self.rect.x +=0
class TheEndGame(pygame.sprite.Sprite):
"""oyun sonu için bitiş bayrağı olan taş."""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/stone.png')
def update(self, *args):
self.rect.x += -1
def end(self):
if self.rect.x < 200:
return True
return False
class Stone(pygame.sprite.Sprite):
"""mapi oluşturan taş sınıfı"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/stone.png')
def update(self, *args):
self.rect.x += -1
# defines the enemies
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/enemy1.png')
self.rect.y = random.randrange(0, 640 - self.rect.width)
self.rect.x = random.randrange(900, 1050)
self.speedx = random.randrange(1, 3) ## for randomizing the speed of the Mob
## randomize the movements a little more
self.speedy = random.randrange(-3, 3)
def update(self):
self.rect.x -= self.speedx
self.rect.y += self.speedy
## now what if the mob element goes out of the screen
# or (self.rect.right > 800 + 20)
if (self.rect.top > 640 + 10) or (self.rect.left < -25):
self.rect.y = random.randrange(0, 640 - self.rect.width)
self.rect.x = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8) ## for randomizing the speed of the Mob
class Enemy1(pygame.sprite.Sprite):
"""1.düşman, 1.25 ve 2.5 arasında rastgele bir hızla ilerler"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/enemy1.png')
# print(self.rect)
self.speedx = random.randrange(2, 4)
# self.speedy = random.randrange(-2, 2)
def update(self, *args):
self.rect.x -= self.speedx
class Enemy2(pygame.sprite.Sprite):
"""ateş topu, 2.düşman"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/fireball.png')
def update(self, *args):
self.rect.x += -5
class Enemy3(pygame.sprite.Sprite):
"""3.düşman (roket) sınıfı, ve karakter rokete yaklaşınca ateşleme fonksiyonu"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/enemy3.png')
def update(self):
self.rect.x -= 1
if self.rect.x < random.randrange(0, 300):
self.rect.y -= 5
class Space(pygame.sprite.Sprite):
"""arka plandaki uzay fonu ve hareket etme fonksiyonu"""
def __init__(self, width=960):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('images/space.png')
self.x = 0
self.y = 250
self.dx = 5
self.width = width
self.reset()
def update(self):
self.rect.center = (self.x, self.y)
self.x -= self.dx
if self.x == 0:
self.reset()
def reset(self):
self.x = self.width
class Background(pygame.sprite.Sprite):
def __init__(self, number, *args):
self.image, self.rect = load_png('images/space.png')
self._layer = -10
pygame.sprite.Sprite.__init__(self, *args)
self.moved = 0
self.number = number
self.rect.x = self.rect.width * self.number
def update(self):
self.rect.move_ip(-5, 0)
self.moved += 5
if self.moved >= self.rect.width:
self.rect.x = self.rect.width * self.number
self.moved = 0
class Explosion(pygame.sprite.Sprite):
"""Patlama sınıfı."""
def __init__(self, center, size):
pygame.sprite.Sprite.__init__(self)
self.size = size
self.explosion_anim = self.explosionAnim()
self.image = self.explosion_anim[self.size][0]
self.rect = self.image.get_rect()
self.rect.center = center
self.frame = 0
self.last_update = pygame.time.get_ticks()
self.frame_rate = 50
def update(self):
now = pygame.time.get_ticks()
if now - self.last_update > self.frame_rate:
self.last_update = now
self.frame += 1
if self.frame == len(self.explosion_anim[self.size]):
self.kill()
else:
center = self.rect.center
self.image = self.explosion_anim[self.size][self.frame]
self.rect = self.image.get_rect()
self.rect.center = center
def explosionAnim(self):
"""Patlama efektlerini gif haline getirir."""
explosion_anim = {}
explosion_anim['sm'] = []
WHITE = (255, 255, 255)
for i in range(9):
filename = 'regularExplosion0{}.png'.format(i)
img_dir = os.path.join(os.path.dirname(__file__), 'data/images')
img = pygame.image.load(os.path.join(img_dir, filename))
img.set_colorkey(WHITE)
img_sm = pygame.transform.scale(img, (32, 32))
explosion_anim['sm'].append(img_sm)
return explosion_anim
def load_png(name):
""" Image dosyalarini okumat"""
fullname = os.path.join('data', name)
try:
image = pygame.image.load(fullname)
if image.get_alpha is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error as error:
# print('Cannot load image:', fullname)
# raise (SystemExit, error)
return image, image.get_rect()
return image, image.get_rect()
def draw_text(surf, text, size, x, y):
"""Ekrana Yazi yazdirma"""
font_name = pygame.font.match_font('arial')
WHITE = (255, 255, 255)
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
def get_angle(pointA, pointB):
changeInX = pointB[0] - pointA[0]
changeInY = pointB[1] - pointA[1]
return degrees(atan2(changeInY, changeInX))
def get_distance(pointA, pointB):
return dist(pointA, pointB)
def get_coinformation(spaceship: pygame.sprite.Sprite, targets: pygame.sprite.Group):
infos = []
for target in targets:
# angle = get_angle(spaceship.rect.right, target.rect.left)
distance = dist(spaceship.rect.right, target.rect.left)
infos.append(distance)
# infos.append((distance, angle))
# infos.sort(key=lambda x: x[0])
infos.sort()
return infos
def get_distances(spaceship: pygame.sprite.Sprite, targets: pygame.sprite.Group):
infos = []
for target in targets:
distance_x = spaceship.rect.right - target.rect.left
distance_y = spaceship.rect.centery - target.rect.centery
infos.append((distance_x, distance_y))
infos.sort(key=lambda x: x[0])
return infos
def get_closest(spaceship: pygame.sprite.Sprite, targets: pygame.sprite.Group, width):
infos = []
closest_dist = 999999
closest_obj = None
for target in targets:
dist = get_distance(spaceship.rect, target.rect)
if dist < closest_dist \
and spaceship.rect.centery - target.rect.centery < 0 \
and spaceship.rect.left - target.rect.left < 0 \
and target.rect.left < width:
closest_obj = target
closest_dist = dist
return closest_obj
def get_closest_n(spaceship: pygame.sprite.Sprite, targets: pygame.sprite.Group, n, width):
infos = []
closest_dists = [999 for n in range(n)]
closest_objs = [None for n in range(n)]
for target in targets:
dist = get_distance(spaceship.rect, target.rect)
max_ind = np.argmax(closest_dists)
if dist < closest_dists[int(max_ind)] \
and spaceship.rect.left - target.rect.right < 0 \
and target.rect.left < width:
# and spaceship.rect.centery - target.rect.centery < 0 \
# and spaceship.rect.top - target.rect.bottom < 5 \
# and spaceship.rect.centery - target.rect.centery < 0 \
closest_objs.pop(int(max_ind))
closest_objs.insert(int(max_ind), target)
closest_dists.pop(int(max_ind))
closest_dists.insert(int(max_ind), dist)
return closest_objs
def get_positions(targets: pygame.sprite.Group):
infos = [target.rect.center for target in targets]
# for target in targets:
# infos.append(target.rect.center)
return infos
# def point_in_sight(target, t0, t1, t2):
# a = 1 / 2 * (-t1[1] * t2[0] + t0[1] * (-t1[0] + t2[0]) + t0[0] * (t1[1] - t2[1]) + t1[0] * t2[1])
# print(a, target, t0, t1, t2)
# sign = -1 if a < 0 else 1
# s = (t0[1] * t2[0] - t0[0] * t2[1] + (t2[1] - t0[1]) * target[0] + (t0[0] - t2[0]) * target[1]) * sign
# t = (t0[0] * t1[1] - t0[1] * t1[0] + (t0[1] - t1[1]) * target[0] + (t1[0] - t0[0]) * target[1]) * sign
# return s > 0 & t > 0 & (s + t) < 2 * a * sign
#
#
# def line_of_sight(spaceship: pygame.sprite.Sprite, targets: pygame.sprite.Group):
# top_point = spaceship.rect.midright[0] + 500, spaceship.rect.midright[1] - 100
# bottom_point = spaceship.rect.midright[0] + 500, spaceship.rect.midright[1] + 100
# for target in targets:
# if point_in_sight(target.rect.center, spaceship.rect.midright, top_point, bottom_point):
# return [target, top_point, bottom_point]
# else:
# print([None, top_point, bottom_point])
# return [None, top_point, bottom_point]
# taken from https://stackoverflow.com/questions/1585525/how-to-find-the-intersection-point-between-a-line-and-a-rectangle
def lineRectIntersectionPoints(line, rect):
""" Get the list of points where the line and rect
intersect, The result may be zero, one or two points.
BUG: This function fails when the line and the side
of the rectangle overlap """
def linesAreParallel(x1, y1, x2, y2, x3, y3, x4, y4):
""" Return True if the given lines (x1,y1)-(x2,y2) and
(x3,y3)-(x4,y4) are parallel """
return (((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)) == 0)
def intersectionPoint(x1, y1, x2, y2, x3, y3, x4, y4):
""" Return the point where the lines through (x1,y1)-(x2,y2)
and (x3,y3)-(x4,y4) cross. This may not be on-screen """
# Use determinant method, as per
# Ref: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
Px = ((((x1 * y2) - (y1 * x2)) * (x3 - x4)) - ((x1 - x2) * ((x3 * y4) - (y3 * x4)))) / (
((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)))
Py = ((((x1 * y2) - (y1 * x2)) * (y3 - y4)) - ((y1 - y2) * ((x3 * y4) - (y3 * x4)))) / (
((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)))
return Px, Py
### Begin the intersection tests
result = []
line_x1, line_y1, line_x2, line_y2 = line # split into components
pos_x, pos_y, width, height = rect
### Convert the rectangle into 4 lines
rect_lines = [(pos_x, pos_y, pos_x + width, pos_y), (pos_x, pos_y + height, pos_x + width, pos_y + height),
# top & bottom
(pos_x, pos_y, pos_x, pos_y + height),
(pos_x + width, pos_y, pos_x + width, pos_y + height)] # left & right
### intersect each rect-side with the line
for r in rect_lines:
rx1, ry1, rx2, ry2 = r
if (not linesAreParallel(line_x1, line_y1, line_x2, line_y2, rx1, ry1, rx2, ry2)): # not parallel
pX, pY = intersectionPoint(line_x1, line_y1, line_x2, line_y2, rx1, ry1, rx2,
ry2) # so intersecting somewhere
pX = round(pX)
pY = round(pY)
# Lines intersect, but is on the rectangle, and between the line end-points?
if (rect.collidepoint(pX, pY) and
pX >= min(line_x1, line_x2) and pX <= max(line_x1, line_x2) and
pY >= min(line_y1, line_y2) and pY <= max(line_y1, line_y2)):
# pygame.draw.circle( surface, "WHITE", ( pX, pY ), 4 )
result.append((pX, pY)) # keep it
if (len(result) == 2):
break # Once we've found 2 intersection points, that's it
return result
def check_linecol(spaceship: pygame.sprite.Sprite, targets: pygame.sprite.Group, line):
# Does the line <spaceship> to <the path of bullet> intersect any obstacles?
line_of_sight = [spaceship.rect.right, spaceship.rect.centery, *line]
found = True
coords = []
for target in targets:
# is anyting blocking the line-of-sight?
intersection_points = lineRectIntersectionPoints(line_of_sight, target.rect)
if (len(intersection_points) > 0):
found = False
coords = intersection_points
return coords
# break # seen already
# if (found):
# # pygame.draw.line(window, WHITE, spaceship_centre, npc_centre)
# return coords
# else:
# # pygame.draw.line(window, GREY, spaceship_centre, npc_centre)
# return "WHITE"
def calculate_missile_points(spaceship: pygame.sprite.Sprite, height):
xpos = spaceship.rect.right
ypos = spaceship.rect.centery
Py = height - ypos
Px = xpos
k = Py // 10
Sx = Px + (k * 2)
Sy = height
return Sx, Sy
def calculate_bullet_points(spaceship: pygame.sprite.Sprite, width):
# xpos = spaceship.rect.right
ypos = spaceship.rect.centery
# Py = 640 - ypos
# Px = xpos
# k = Py // 10
# Sx = Px + (k * 2)
# Sy = 640
return width, ypos
def calculate_top_points(spaceship: pygame.sprite.Sprite):
xpos = spaceship.rect.centerx
# ypos = spaceship.rect.centery
# Py = 640 - ypos
# Px = xpos
# k = Py // 10
# Sx = Px + (k * 2)
# Sy = 640
return xpos, 0
def calculate_bottom_points(spaceship: pygame.sprite.Sprite, height):
xpos = spaceship.rect.centerx
# ypos = spaceship.rect.centery
# Py = 640 - ypos
# Px = xpos
# k = Py // 10
# Sx = Px + (k * 2)
# Sy = 640
return xpos, height
# taken from https://github.com/WilliamAmbrozic/spaceShooter/tree/master/spaceshooter
def fill_image(inputNum, inputImg, HEIGHT, WIDTH, spaceship, enemies):
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
for x in range(inputNum, inputNum * 2):
for y in range(inputNum):
if (spaceship.rect.center[0] > WIDTH / inputNum * (x - inputNum) and
spaceship.rect.center[0] < WIDTH / inputNum * ((x - inputNum) + 1) and
spaceship.rect.center[1] > WIDTH / inputNum * (y - 1) and
spaceship.rect.center[1] < WIDTH / inputNum * y):
# if spaceship collides with a hitbox
inputImg[x][y] = RED
datOffSet = x - inputNum * 2
else:
inputImg[x][y] = BLUE
# print(type(enemies))
for z in range(len(enemies)):
if (enemies[z].rect.center[0] > HEIGHT / inputNum * (x - inputNum) and
enemies[z].rect.center[0] < HEIGHT / inputNum * ((x - inputNum) + 1) and
enemies[z].rect.center[1] > HEIGHT / inputNum * (y - 1) and
enemies[z].rect.center[1] < HEIGHT / inputNum * y):
inputImg[x][y] = GREEN
# print(enemies[z].rect.center[1], WIDTH, inputNum, y)
elif (inputImg[x][y] != RED):
inputImg[x][y] = BLUE
if (inputImg[x][y] == GREEN):
break
# taken from https://github.com/WilliamAmbrozic/spaceShooter/tree/master/spaceshooter
def draw_neat(surf, inputNum, inputImg, xnodePos, ynodePos, size, x, y):
for z in range(inputNum, inputNum * 2):
for c in range(0, inputNum):
pygame.draw.rect(surf, inputImg[z][c], pygame.Rect(x + z * size, y + c * size, size, size))
xnodePos[z][c] = x + z * size
ynodePos[z][c] = y + c * size
nodePos = list(zip(xnodePos, ynodePos))