Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Space Invaders
- import play
- from random import choice, randint
- import pygame
- from time import sleep
- explosion_sound = pygame.mixer.Sound('Explosion.wav')
- # 1) Health
- # 2) Score
- # 3) Boss
- # 4) Music #
- # 5) Explosions
- framerate = 42
- screen_heigh = play.screen.height
- screen_width = play.screen.width
- print(f'screen_heigh = {screen_heigh}, screen_width = {screen_width}')
- background = play.new_image(image='Background.png',
- x=0,
- y=0,
- size=110,
- angle=180,
- transparency=100)
- explosion_image = play.new_image(image='explosion.png',
- x=0,
- y=0,
- size=8,
- angle=0,
- transparency=100)
- spaceship = play.new_image(image='Spaceship.png',
- x=0,
- y=-260,
- size=25,
- angle=180,
- transparency=100)
- bullets = []
- ufos_bullets = []
- UFOs = []
- UFOs_names = ['UFO_1.png', 'UFO_2.png']
- direction = 30
- ufos_y_step = 10
- spaceship_health = 100
- ufo_damage = 20
- spaceship_health_text = play.text(words=f'HP: {spaceship_health}',
- x=screen_width//2 - 45, # screen_width = 700, 350
- y=screen_heigh//2 - 20,
- font=None,
- font_size=30,
- color='light blue',
- angle=0,
- transparency=50,
- size=100)
- score = 0
- ufo_score = 15
- score_text = play.text(words=f'Score: {score}',
- x=-screen_width//2 + 45, # screen_width = 700, 350
- y=screen_heigh//2 - 20,
- font=None,
- font_size=30,
- color='light blue',
- angle=0,
- transparency=50,
- size=100)
- game_over = play.text(words=f'GAME OVER!',
- x=0, # screen_width = 700, 350
- y=0,
- font=None,
- font_size=60,
- color='red',
- angle=0,
- transparency=100,
- size=100)
- def create_ufos():
- y = 250
- for i in range(3):
- x = -300
- for j in range(8):
- size = 2
- image_name = choice(UFOs_names)
- if image_name == 'UFO_1.png':
- size = 6
- elif image_name == 'UFO_2.png':
- size = 2
- ufo = play.new_image(image=image_name,
- x=x,
- y=y,
- size=size,
- angle=0,
- transparency=100)
- ufo.show()
- UFOs.append(ufo)
- x += 75
- y -= 40
- def check_ufos_border():
- # движение вправо
- global direction, UFOs, direction
- # Проходимся в цикле по всем НЛОшкам
- for ufo in UFOs:
- # Если объект приблизился к правой границе + 385
- # Проверка смены направления - НЛО дошли до края
- if (ufo.x > screen_width / 2 - 30) or (ufo.x < - (screen_width / 2 - 30)):
- direction = - direction
- for ufo in UFOs:
- ufo.y -= ufos_y_step
- # Смещаем каждого из НЛОшек на direction пикселей
- for ufo in UFOs:
- ufo.x += direction
- # Создаём число от 0 до 100
- number = randint(0, 100)
- # С вероятностью 10% стреляем в корабль
- if number < 10:
- ufo_shoot(ufo)
- def ufo_shoot(ufo):
- global ufos_bullets
- bullet = play.new_box(color='purple',
- x=ufo.x,
- y=ufo.y - 15,
- width=7,
- height=17,
- border_color='black',
- border_width=1,
- angle=0,
- transparency=100,
- size=100)
- bullet.show()
- # Добавляем пулю в список летящих и видимых пуль корабля
- ufos_bullets.append(bullet)
- def shoot():
- global bullets
- bullet = play.new_box(color='red',
- x=spaceship.x,
- y=spaceship.y + 37,
- width=7,
- height=17,
- border_color='black',
- border_width=2,
- angle=0,
- transparency=100,
- size=100)
- bullet.show()
- # Добавляем пулю в список летящих и видимых пуль корабля
- bullets.append(bullet)
- def move_bullets():
- global bullets, UFOs, score, ufo_score, score_text, explosion_image
- # Проходимся в цикле по всем пулям, выпущенным в нлошек
- explosion_image.hide()
- for bullet in bullets:
- # Проходимся в цикле по всем НЛОшкам
- # Перемещаем пулю вверх на 6 пикселей
- bullet.y += 6
- for ufo in UFOs: # [ufo1, ufo2, ufo3, ...] ufo -> ufo1, ufo -> ufo2 ...
- # Если попали в НЛОшку
- if bullet.is_touching(ufo):
- # for i in range()
- # list.pop([i])
- # Скрываем убитого НЛОшку
- explosion_sound.play()
- score += ufo_score
- score_text.words = f'Score: {score}'
- explosion_image.x = ufo.x
- explosion_image.y = ufo.y
- explosion_image.show()
- ufo.hide()
- # Убираем из списка всех НЛОшек убитого НЛОшку
- UFOs.remove(ufo)
- # Скрываем убитого НЛОшку
- # Скрываем убитого НЛОшку
- if bullet in bullets:
- bullets.remove(bullet)
- bullet.hide()
- # Или вышли за границы экрана сверху
- @play.when_program_starts
- def start():
- explosion_image.hide()
- pygame.mixer_music.set_volume(30)
- pygame.mixer_music.load('main_theme.mp3')
- pygame.mixer_music.play()
- game_over.hide()
- background.show()
- spaceship.show()
- create_ufos()
- spaceship.start_physics(can_move=True,
- stable=False,
- x_speed=0,
- y_speed=0,
- obeys_gravity=False,
- bounciness=1.0,
- mass=10,
- friction=0.1)
- @play.repeat_forever
- async def game():
- await play.timer(seconds=1/framerate)
- @play.repeat_forever
- async def spaceship_control():
- if play.key_is_pressed('left', 'a', 'ф'):
- spaceship.physics.x_speed = -10
- elif play.key_is_pressed('right', 'd', 'в'):
- spaceship.physics.x_speed = 10
- else:
- spaceship.physics.x_speed = 0
- await play.timer(seconds=1/framerate)
- @play.repeat_forever
- async def shooting():
- move_bullets()
- if play.key_is_pressed('space'):
- shoot()
- await play.timer(seconds=0.15)
- await play.timer(seconds=1/framerate)
- @play.repeat_forever
- async def bullets_control():
- global ufos_bullets, UFOs, spaceship_health, ufo_damage, game_over
- move_bullets()
- for bullet in ufos_bullets:
- bullet.y -= 6
- if bullet.is_touching(spaceship):
- bullet.hide()
- ufos_bullets.remove(bullet)
- spaceship_health -= ufo_damage
- spaceship_health_text.words = f'HP: {spaceship_health}'
- if spaceship_health <= 0:
- game_over.show()
- await play.timer(seconds=1/framerate)
- @play.repeat_forever
- async def ufos_control():
- global direction
- # проверка что НЛО не дошли до края
- # Движемся в зависимости от direction -30 влево +30 вправо
- check_ufos_border()
- await play.timer(seconds=1)
- play.start_program()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement