Advertisement
Maxinstellar

Space Invaders 03.06.2020_1

Jun 3rd, 2020
1,398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.08 KB | None | 0 0
  1. # Space Invaders
  2. import play
  3. from random import choice, randint
  4. import pygame
  5. from time import sleep
  6.  
  7.  
  8. explosion_sound = pygame.mixer.Sound('Explosion.wav')
  9. # 1) Health
  10. # 2) Score
  11. # 3) Boss
  12. # 4) Music #
  13. # 5) Explosions
  14. framerate = 42
  15. screen_heigh = play.screen.height
  16. screen_width = play.screen.width
  17. print(f'screen_heigh = {screen_heigh}, screen_width = {screen_width}')
  18.  
  19. background = play.new_image(image='Background.png',
  20.                            x=0,
  21.                            y=0,
  22.                            size=110,
  23.                            angle=180,
  24.                            transparency=100)
  25.  
  26.  
  27. explosion_image = play.new_image(image='explosion.png',
  28.                            x=0,
  29.                            y=0,
  30.                            size=8,
  31.                            angle=0,
  32.                            transparency=100)
  33.  
  34.  
  35. spaceship = play.new_image(image='Spaceship.png',
  36.                            x=0,
  37.                            y=-260,
  38.                            size=25,
  39.                            angle=180,
  40.                            transparency=100)
  41.  
  42. bullets = []
  43. ufos_bullets = []
  44. UFOs = []
  45. UFOs_names = ['UFO_1.png', 'UFO_2.png']
  46. direction = 30
  47. ufos_y_step = 10
  48. spaceship_health = 100
  49. ufo_damage = 20
  50. spaceship_health_text = play.text(words=f'HP: {spaceship_health}',
  51.                                   x=screen_width//2 - 45,  # screen_width = 700, 350
  52.                                   y=screen_heigh//2 - 20,
  53.                                   font=None,
  54.                                   font_size=30,
  55.                                   color='light blue',
  56.                                   angle=0,
  57.                                   transparency=50,
  58.                                   size=100)
  59.  
  60. score = 0
  61. ufo_score = 15
  62. score_text = play.text(words=f'Score: {score}',
  63.                                   x=-screen_width//2 + 45,  # screen_width = 700, 350
  64.                                   y=screen_heigh//2 - 20,
  65.                                   font=None,
  66.                                   font_size=30,
  67.                                   color='light blue',
  68.                                   angle=0,
  69.                                   transparency=50,
  70.                                   size=100)
  71.  
  72.  
  73. game_over = play.text(words=f'GAME OVER!',
  74.                         x=0,  # screen_width = 700, 350
  75.                         y=0,
  76.                         font=None,
  77.                         font_size=60,
  78.                         color='red',
  79.                         angle=0,
  80.                         transparency=100,
  81.                         size=100)
  82.  
  83.  
  84.  
  85. def create_ufos():
  86.     y = 250
  87.     for i in range(3):
  88.         x = -300
  89.         for j in range(8):
  90.             size = 2
  91.             image_name = choice(UFOs_names)
  92.             if image_name == 'UFO_1.png':
  93.                 size = 6
  94.             elif image_name == 'UFO_2.png':
  95.                 size = 2
  96.             ufo = play.new_image(image=image_name,
  97.                            x=x,
  98.                            y=y,
  99.                            size=size,
  100.                            angle=0,
  101.                            transparency=100)
  102.             ufo.show()
  103.             UFOs.append(ufo)
  104.             x += 75
  105.         y -= 40
  106.  
  107.  
  108. def check_ufos_border():
  109.     # движение вправо
  110.     global direction, UFOs, direction
  111.     # Проходимся в цикле по всем НЛОшкам
  112.     for ufo in UFOs:
  113.         # Если объект приблизился к правой границе + 385
  114.         # Проверка смены направления - НЛО дошли до края
  115.         if (ufo.x > screen_width / 2 - 30) or (ufo.x < - (screen_width / 2 - 30)):
  116.             direction = - direction
  117.             for ufo in UFOs:
  118.                 ufo.y -= ufos_y_step
  119.     # Смещаем каждого из НЛОшек на direction пикселей
  120.     for ufo in UFOs:
  121.         ufo.x += direction
  122.         # Создаём число от 0 до 100
  123.         number = randint(0, 100)
  124.         # С вероятностью 10% стреляем в корабль
  125.         if number < 10:
  126.             ufo_shoot(ufo)
  127.  
  128.  
  129. def ufo_shoot(ufo):
  130.     global ufos_bullets
  131.     bullet = play.new_box(color='purple',
  132.                         x=ufo.x,
  133.                         y=ufo.y - 15,
  134.                         width=7,
  135.                         height=17,
  136.                         border_color='black',
  137.                         border_width=1,
  138.                         angle=0,
  139.                         transparency=100,
  140.                         size=100)
  141.     bullet.show()
  142.     # Добавляем пулю в список летящих и видимых пуль корабля
  143.     ufos_bullets.append(bullet)
  144.  
  145.  
  146. def shoot():
  147.     global bullets
  148.     bullet = play.new_box(color='red',
  149.                         x=spaceship.x,
  150.                         y=spaceship.y + 37,
  151.                         width=7,
  152.                         height=17,
  153.                         border_color='black',
  154.                         border_width=2,
  155.                         angle=0,
  156.                         transparency=100,
  157.                         size=100)
  158.     bullet.show()
  159.     # Добавляем пулю в список летящих и видимых пуль корабля
  160.     bullets.append(bullet)
  161.  
  162. def move_bullets():
  163.     global bullets, UFOs, score, ufo_score, score_text, explosion_image
  164.     # Проходимся в цикле по всем пулям, выпущенным в нлошек
  165.     explosion_image.hide()
  166.     for bullet in bullets:
  167.         # Проходимся в цикле по всем НЛОшкам
  168.         # Перемещаем пулю вверх на 6 пикселей
  169.         bullet.y += 6
  170.         for ufo in UFOs: # [ufo1, ufo2, ufo3, ...] ufo -> ufo1, ufo -> ufo2 ...
  171.             # Если попали в НЛОшку
  172.             if bullet.is_touching(ufo):
  173.                 # for i in range()
  174.                 # list.pop([i])
  175.                 # Скрываем убитого НЛОшку
  176.                 explosion_sound.play()
  177.                 score += ufo_score
  178.                 score_text.words = f'Score: {score}'
  179.                 explosion_image.x = ufo.x
  180.                 explosion_image.y = ufo.y
  181.                 explosion_image.show()
  182.                 ufo.hide()
  183.                 # Убираем из списка всех НЛОшек убитого НЛОшку
  184.                 UFOs.remove(ufo)
  185.                 # Скрываем убитого НЛОшку
  186.                 # Скрываем убитого НЛОшку
  187.                 if bullet in bullets:
  188.                     bullets.remove(bullet)  
  189.                     bullet.hide()
  190.         # Или вышли за границы экрана сверху
  191.  
  192.  
  193. @play.when_program_starts
  194. def start():
  195.     explosion_image.hide()
  196.     pygame.mixer_music.set_volume(30)
  197.     pygame.mixer_music.load('main_theme.mp3')
  198.     pygame.mixer_music.play()
  199.     game_over.hide()
  200.     background.show()
  201.     spaceship.show()
  202.     create_ufos()
  203.     spaceship.start_physics(can_move=True,
  204.                             stable=False,
  205.                             x_speed=0,
  206.                             y_speed=0,
  207.                             obeys_gravity=False,
  208.                             bounciness=1.0,
  209.                             mass=10,
  210.                             friction=0.1)
  211.  
  212.  
  213. @play.repeat_forever
  214. async def game():
  215.  
  216.     await play.timer(seconds=1/framerate)
  217.  
  218.  
  219. @play.repeat_forever
  220. async def spaceship_control():    
  221.     if play.key_is_pressed('left', 'a', 'ф'):
  222.         spaceship.physics.x_speed = -10
  223.     elif play.key_is_pressed('right', 'd', 'в'):
  224.         spaceship.physics.x_speed = 10
  225.     else:
  226.         spaceship.physics.x_speed = 0
  227.     await play.timer(seconds=1/framerate)
  228.  
  229.  
  230. @play.repeat_forever
  231. async def shooting():
  232.     move_bullets()
  233.     if play.key_is_pressed('space'):
  234.         shoot()
  235.         await play.timer(seconds=0.15)
  236.     await play.timer(seconds=1/framerate)
  237.  
  238.  
  239. @play.repeat_forever
  240. async def bullets_control():  
  241.     global ufos_bullets, UFOs, spaceship_health, ufo_damage, game_over
  242.     move_bullets()
  243.     for bullet in ufos_bullets:
  244.         bullet.y -= 6
  245.         if bullet.is_touching(spaceship):
  246.             bullet.hide()
  247.             ufos_bullets.remove(bullet)
  248.             spaceship_health -= ufo_damage
  249.             spaceship_health_text.words = f'HP: {spaceship_health}'
  250.             if spaceship_health <= 0:
  251.                 game_over.show()
  252.     await play.timer(seconds=1/framerate)
  253.  
  254.  
  255. @play.repeat_forever
  256. async def ufos_control():    
  257.     global direction
  258.     # проверка что НЛО не дошли до края
  259.     # Движемся в зависимости от direction -30 влево +30 вправо
  260.     check_ufos_border()
  261.     await play.timer(seconds=1)
  262.  
  263.  
  264. play.start_program()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement