diff --git a/Space Invaders/alien.png b/Space Invaders/alien.png new file mode 100644 index 0000000..9fe4ce4 Binary files /dev/null and b/Space Invaders/alien.png differ diff --git a/Space Invaders/background.jpg b/Space Invaders/background.jpg new file mode 100644 index 0000000..374d6f1 Binary files /dev/null and b/Space Invaders/background.jpg differ diff --git a/Space Invaders/beam.png b/Space Invaders/beam.png new file mode 100644 index 0000000..8e4a0ad Binary files /dev/null and b/Space Invaders/beam.png differ diff --git a/Space Invaders/bullet.png b/Space Invaders/bullet.png new file mode 100644 index 0000000..01ea954 Binary files /dev/null and b/Space Invaders/bullet.png differ diff --git a/Space Invaders/enemy.png b/Space Invaders/enemy.png new file mode 100644 index 0000000..cee73b8 Binary files /dev/null and b/Space Invaders/enemy.png differ diff --git a/Space Invaders/jenya.py b/Space Invaders/jenya.py new file mode 100644 index 0000000..530473f --- /dev/null +++ b/Space Invaders/jenya.py @@ -0,0 +1,288 @@ +import pygame +import sys +import random + + +pygame.init() +res = (720, 720) + +c1 = random.randint(125, 125) +c2 = random.randint(0, 255) +c3 = random.randint(0, 255) + +screen = pygame.display.set_mode(res) +clock = pygame.time.Clock() +red = (255, 0, 0) +green = (0, 255, 0) +blue = (0, 0, 255) +color_list = [red, green, blue] +colox_c1 = 0 +colox_c2 = 0 +colox_c3 = 254 +colox_c4 = 254 + +player_c = random.choice(color_list) + +startl = (169, 169, 169) + + +startd = (100, 100, 100) +white = (255, 255, 255) +start = (255, 255, 255) +width = screen.get_width() +height = screen.get_height() + +lead_x = 40 + +lead_y = height / 2 +x = 300 +y = 290 +width1 = 100 +height1 = 40 +enemy_size = 50 + +smallfont = pygame.font.SysFont('Corbel', 35) + +text = smallfont.render('Start', True, white) +text1 = smallfont.render('Options', True, white) +exit1 = smallfont.render('Exit', True, white) + +colox = smallfont.render('Colox', True, (c3, c2, c1)) +x1 = random.randint(width // 2, width) +y1 = random.randint(100, height // 2) +x2 = 40 +y2 = 40 +speed = 15 + +count = 0 +rgb = random.choice(color_list) + +e_p = [width, random.randint(50, height - 50)] +e1_p = [random.randint(width, width + 100), random.randint(50, height + - 100)] + + +def game_over(): + + while True: + + for ev in pygame.event.get(): + if ev.type == pygame.QUIT: + pygame.quit() + + if ev.type == pygame.MOUSEBUTTONDOWN: + if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] \ + < height - 80: + pygame.quit() + + if ev.type == pygame.MOUSEBUTTONDOWN: + if width - 180 < mouse1[0] < width - 100 and height \ + - 100 < mouse1[1] < height - 80: + + game(lead_x, lead_y, speed, count) + + screen.fill((65, 25, 64)) + smallfont = pygame.font.SysFont('Corbel', 60) + smallfont1 = pygame.font.SysFont('Corbel', 25) + game_over = smallfont.render('GAME OVER', True, white) + game_exit = smallfont1.render('exit', True, white) + restart = smallfont1.render('restart', True, white) + mouse1 = pygame.mouse.get_pos() + + if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80: + pygame.draw.rect(screen, startl, [100, height - 100, 40,20]) + else: + pygame.draw.rect(screen, startd, [100, height - 100, 40,20]) + + if width - 180 < mouse1[0] < width - 100 and height - 100 < mouse1[1] < height - 80: + pygame.draw.rect(screen, startl, [width - 180, height- 100, 80, 20]) + else: + pygame.draw.rect(screen, startd, [width - 180, height- 100, 80, 20]) + + screen.blit(game_exit, (100, height - 100)) + + screen.blit(restart, (width - 180, height - 100)) + screen.blit(game_over, (width / 2 - 150, 295)) + + pygame.display.update() + + +pygame.draw.rect(screen, startd, [100, height - 100, 40, 20]) +pygame.draw.rect(screen, startd, [width - 180, height - 100, 40, 50]) + + + +def game( + lead_y, + lead_X, + speed, + count, + ): + + while True: + for ev in pygame.event.get(): + if ev.type == pygame.QUIT: + pygame.quit() + + + keys = pygame.key.get_pressed() + if keys[pygame.K_UP]: + + lead_y -= 10 + if keys[pygame.K_DOWN]: + + lead_y += 10 + screen.fill((65, 25, 64)) + clock.tick(speed) + + rect = pygame.draw.rect(screen, player_c, [lead_x, lead_y, 40,40]) + pygame.draw.rect(screen, (c1, c2, c3), [0, 0, width, 40]) + pygame.draw.rect(screen, (c3, c2, c1), [0, 680, width, 40]) + pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) + smallfont = pygame.font.SysFont('Corbel', 35) + exit2 = smallfont.render('Exit', True, white) + + mouse = pygame.mouse.get_pos() + if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: + pygame.draw.rect(screen, startl, [width - 100, 0, 100, 40]) + else: + pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) + if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: + if ev.type == pygame.MOUSEBUTTONDOWN: + pygame.quit() + + if e_p[0] > 0 and e_p[0] <= width: + + e_p[0] -= 10 + else: + if e_p[1] <= 40 or e_p[1] >= height - 40: + e_p[1] = height / 2 + if e1_p[1] <= 40 or e1_p[1] >= height - 40: + e1_p[1] = height / 2 + e_p[1] = random.randint(enemy_size, height - enemy_size) + e_p[0] = width + + + if lead_x <= e_p[0] <= lead_x + 40 and lead_y >= e_p[1] >= lead_y - 40: + game_over() + + if lead_y <= e_p[1] + enemy_size <= lead_y + 40 and lead_x <= e_p[0] <= lead_x + 40: + game_over() + + pygame.draw.rect(screen, red, [e_p[0], eапмапрааааааак_p[1], enemy_size,enemy_size]) + if e1_p[0] > 0 and e1_p[0] <= width + 100: + e1_p[0] -= 10 + else: + if e1_p[1] <= 40 or e1_p[1] >= height - 40: + e1_p[1] = height / 2 + e1_p[1] = random.randint(enemy_size, height - 40) + e1_p[0] = width + 100 + + if lead_x <= e1_p[0] <= lead_x + 40 and lead_y >= e1_p[1] >= lead_y - 40: + e1_p[0] = width + 100 + e1_p[1] = random.randint(40, height - 40) + count += 1 + speed += 1 + if lead_y <= e1_p[1] + enemy_size <= lead_y + 40 and lead_x <= e1_p[0] <= lead_x + 40: + + e1_p[0] = width + 100 + e1_p[1] = random.randint(40, height - 40) + + count += 1 + + speed += 1 + + if count >= 45: + + speed = 60 + + if lead_y <= 38 or lead_y >= height - 38: + game_over() + if e1_p[0] <= 0: + game_over() + + pygame.draw.rect(screen, blue, [e1_p[0], e1_p[1], enemy_size, + enemy_size]) + score1 = smallfont.render('Score:', True, white) + screen.blit(score1, (width - 120, height - 40)) + screen.blit(exit2, (width - 80, 0)) + pygame.display.update() + + +def intro( + colox_c1, + colox_c2, + colox, + exit1, + text1, + text, + ): + intro = True + while intro: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + screen.fill((65, 25, 64)) + mouse = pygame.mouse.get_pos() + + if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: + + pygame.draw.rect(screen, startl, [x, y, width1, height1]) + else: + if x < mouse[0] < x + width1 + 40 and y + 70 < mouse[1] < y \ + + 70 + height1: + pygame.draw.rect(screen, startl, [x, y + 70, width1+40,height]) + else: + + if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: + pygame.draw.rect(screen, startl, [x, y + 140,width1,height1]) + else: + pygame.draw.rect(screen, startd, [x, y, width1,height1]) + pygame.draw.rect(screen, startd, [x, y + 70, width1 + + 40, height1]) + pygame.draw.rect(screen, startd, [x, y + 140,width1, height1]) + + if event.type == pygame.MOUSEBUTTONDOWN: + if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: + #music() + game(lead_y, lead_x, speed, count) + + if event.type == pygame.MOUSEBUTTONDOWN: + if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: + pygame.quit() + + if 0 <= colox_c1 <= 254 or 0 <= colox_c2 <= 254: + colox_c1 += 1 + colox_c2 += 1 + if colox_c1 >= 254 or colox_c2 >= 254: + colox_c1 = c3 + colox_c2 = c3 + + pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [0, 0, 40, + height]) + pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [width - 40, + 0, 40, height]) + smallfont = pygame.font.SysFont('Corbel', 35) + sig = smallfont.render('Deisgned by := Antriksh', True, white) + text = smallfont.render('Start', True, white) + text1 = smallfont.render('Options', True, white) + exit1 = smallfont.render('Exit', True, white) + colox = smallfont.render('Colox', True, (c1, colox_c1, + colox_c2)) + screen.blit(colox, (312, 50)) + screen.blit(text, (312, 295)) + screen.blit(text1, (312, 365)) + screen.blit(exit1, (312, 435)) + screen.blit(sig, (320, height - 50)) + clock.tick(60) + pygame.display.update() + + +intro( + colox_c1, + colox_c2, + colox, + exit1, + text1, + text, + ) \ No newline at end of file diff --git a/Space Invaders/main.py b/Space Invaders/main.py index d0a9c3c..fa31563 100644 --- a/Space Invaders/main.py +++ b/Space Invaders/main.py @@ -1,21 +1,13 @@ -# Author: Atanu Sarkar -# Space Invaders (my version) -# v1.1.4 -# 11-April-2020, 03:04 AM (IST) - import pygame import random import math from pygame import mixer import time -# import sched -# game constants WIDTH = 800 HEIGHT = 600 -# global variables running = True pause_state = 0 score = 0 @@ -34,16 +26,13 @@ frame_count = 0 fps = 0 -# game objects player = type('Player', (), {})() bullet = type('Bullet', (), {})() enemies = [] lasers = [] -# initialize pygame pygame.init() -# Input key states (keyboard) LEFT_ARROW_KEY_PRESSED = 0 RIGHT_ARROW_KEY_PRESSED = 0 UP_ARROW_KEY_PRESSED = 0 @@ -51,20 +40,17 @@ ENTER_KEY_PRESSED = 0 ESC_KEY_PRESSED = 0 -# create display window window = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Space Invaders") -window_icon = pygame.image.load("res/images/alien.png") +window_icon = pygame.image.load("Space Invaders/res/images/alien.png") pygame.display.set_icon(window_icon) -# game sounds pause_sound = None level_up_sound = None weapon_annihilation_sound = None game_over_sound = None -# create background -background_img = pygame.image.load("res/images/background.jpg") # 800 x 600 px image +background_img = pygame.image.load("Space Invaders/res/images/background.jpg") background_music_paths = ["res/sounds/Space_Invaders_Music.ogg", "res/sounds/Space_Invaders_Music_x2.ogg", "res/sounds/Space_Invaders_Music_x4.ogg", @@ -84,7 +70,6 @@ def init_background_music(): mixer.music.play(-1) -# create player class class Player: def __init__(self, img_path, width, height, x, y, dx, dy, kill_sound_path): self.img_path = img_path @@ -102,7 +87,6 @@ def draw(self): window.blit(self.img, (self.x, self.y)) -# create enemy class class Enemy: def __init__(self, img_path, width, height, x, y, dx, dy, kill_sound_path): self.img_path = img_path @@ -120,7 +104,6 @@ def draw(self): window.blit(self.img, (self.x, self.y)) -# create bullet class class Bullet: def __init__(self, img_path, width, height, x, y, dx, dy, fire_sound_path): self.img_path = img_path @@ -140,7 +123,6 @@ def draw(self): window.blit(self.img, (self.x, self.y)) -# create laser class class Laser: def __init__(self, img_path, width, height, x, y, dx, dy, shoot_probability, relaxation_time, beam_sound_path): self.img_path = img_path @@ -166,26 +148,22 @@ def draw(self): def scoreboard(): x_offset = 10 y_offset = 10 - # set font type and size font = pygame.font.SysFont("calibre", 16) - # render font and text sprites score_sprint = font.render("SCORE : " + str(score), True, (255, 255, 255)) - highest_score_sprint = font.render("HI-SCORE : " + str(highest_score), True, (255, 255, 255)) + hightst_score_sprint = font.render("HI-SCORE : " + str(highest_score), True, (255, 255, 255)) level_sprint = font.render("LEVEL : " + str(level), True, (255, 255, 255)) difficulty_sprint = font.render("DIFFICULTY : " + str(difficulty), True, (255, 255, 255)) life_sprint = font.render("LIFE LEFT : " + str(life) + " | " + ("@ " * life), True, (255, 255, 255)) - # performance info fps_sprint = font.render("FPS : " + str(fps), True, (255, 255, 255)) frame_time_in_ms = round(single_frame_rendering_time * 1000, 2) frame_time_sprint = font.render("FT : " + str(frame_time_in_ms) + " ms", True, (255, 255, 255)) - # place the font sprites on the screen window.blit(score_sprint, (x_offset, y_offset)) - window.blit(highest_score_sprint, (x_offset, y_offset + 20)) - window.blit(level_sprint, (x_offset, y_offset + 40)) - window.blit(difficulty_sprint, (x_offset, y_offset + 60)) + window.blit(hightst_score_sprint, (x_offset, y_offset + 20)) + window.blit(level_sprint, (x_offset, y_offset, + 40)) + window.blit(difficulty.sprint, (x_offset, y_offset + 60)) window.blit(life_sprint, (x_offset, y_offset + 80)) window.blit(fps_sprint, (WIDTH - 80, y_offset)) window.blit(frame_time_sprint, (WIDTH - 80, y_offset + 20)) @@ -200,15 +178,6 @@ def collision_check(object1, object2): return distance < ((object1.width + object2.width) / 2) -# def collision_check(object1_x, object1_y, object1_diameter, object2_x, object2_y, object2_diameter): -# x1_cm = object1_x + object1_diameter / 2 -# y1_cm = object1_y + object1_diameter / 2 -# x2_cm = object2_x + object2_diameter / 2 -# y2_cm = object2_y + object2_diameter / 2 -# distance = math.sqrt(math.pow((x2_cm - x1_cm), 2) + math.pow((y2_cm - y1_cm), 2)) -# return distance < ((object1_diameter + object2_diameter) / 2) - - def level_up(): global life global level @@ -216,20 +185,8 @@ def level_up(): global max_difficulty_to_level_up level_up_sound.play() level += 1 - life += 1 # grant a life - difficulty = 1 # reset difficulty - # TODO: change player and bullet speeds, enemy laser speed and firing probability wrt level - # come up with interesting gameplay ideas. - # variables in hand: - # 1. speed of weapons - # 2. enemy (up to 6) & player velocity - # 3. laser firing probability - # future ideas: - # 1. add new type of enemies - # 2. add new player spaceship and bullets! - # future features: - # 1. create player profile ad store highest score to DB - # 2. multiplayer + life += 1 + difficulty = 1 if level % 3 == 0: player.dx += 1 bullet.dy += 1 @@ -240,7 +197,6 @@ def level_up(): each_laser.shoot_probability = 1.0 if max_difficulty_to_level_up > 7: max_difficulty_to_level_up = 7 - font = pygame.font.SysFont("freesansbold", 64) gameover_sprint = font.render("LEVEL UP", True, (255, 255, 255)) window.blit(gameover_sprint, (WIDTH / 2 - 120, HEIGHT / 2 - 32)) @@ -248,7 +204,6 @@ def level_up(): init_game() time.sleep(1.0) - def respawn(enemy_obj): enemy_obj.x = random.randint(0, (WIDTH - enemy_obj.width)) enemy_obj.y = random.randint(((HEIGHT / 10) * 1 - (enemy_obj.height / 2)), @@ -267,7 +222,7 @@ def kill_enemy(player_obj, bullet_obj, enemy_obj): kills += 1 if kills % max_kills_to_difficulty_up == 0: difficulty += 1 - if (difficulty == max_difficulty_to_level_up) and (life != 0): + if (difficulty == max_difficulty_to_level_up) and ( life != 0): level_up() init_background_music() print("Score:", score) @@ -283,7 +238,7 @@ def rebirth(player_obj): def gameover_screen(): scoreboard() - font = pygame.font.SysFont("freesansbold", 64) + font= pygame.font.SysFont("freesansbold", 64) gameover_sprint = font.render("GAME OVER", True, (255, 255, 255)) window.blit(gameover_sprint, (WIDTH / 2 - 140, HEIGHT / 2 - 32)) pygame.display.update() @@ -302,16 +257,18 @@ def gameover(): if score > highest_score: highest_score = score - # console display + if score > highest_score: + highest_score = score + print("----------------") - print("GAME OVER !!") + print("GAME OVER ! !") print("----------------") print("you died at") print("Level:", level) print("difficulty:", difficulty) print("Your Score:", score) print("----------------") - print("Try Again !!") + print("Try Again ! !") print("----------------") running = False gameover_screen() @@ -341,21 +298,6 @@ def destroy_weapons(player_obj, bullet_obj, enemy_obj, laser_obj): laser_obj.y = enemy_obj.y + laser_obj.height / 2 -# timer = sched.scheduler(time.time, time.sleep) -# -# -# def calculate_fps(sc): -# global frame_count -# fps = frame_count -# print("FPS =", fps) -# frame_count = 0 -# timer.enter(60, 1, calculate_fps, (sc,)) -# -# -# timer.enter(60, 1, calculate_fps, (timer, )) -# timer.run() - - def pause_game(): pause_sound.play() scoreboard() @@ -372,56 +314,53 @@ def init_game(): global game_over_sound global weapon_annihilation_sound - pause_sound = mixer.Sound("res/sounds/pause.wav") - level_up_sound = mixer.Sound("res/sounds/1up.wav") - game_over_sound = mixer.Sound("res/sounds/gameover.wav") - weapon_annihilation_sound = mixer.Sound("res/sounds/annihilation.wav") + pause_sound = mixer.Sound("Space Invaders/res/sounds/pause.wav") + level_up_sound = mixer.Sound("Space Invaders/res/sounds/1up.wav") + game_over_sound = mixer.Sound("Space Invaders/res/sounds/gameover.wav") + weapon_annihilation_sound = mixer.Sound("Space Invaders/res/sounds/annihilation.wav") - # player - player_img_path = "res/images/spaceship.png" # 64 x 64 px image + player_img_path = "Space Invaders/res/images/spaceship.png" player_width = 64 player_height = 64 player_x = (WIDTH / 2) - (player_width / 2) player_y = (HEIGHT / 10) * 9 - (player_height / 2) player_dx = initial_player_velocity player_dy = 0 - player_kill_sound_path = "res/sounds/explosion.wav" + player_kill_sound_path = "Space Invaders/res/sounds/explosion.wav" global player player = Player(player_img_path, player_width, player_height, player_x, player_y, player_dx, player_dy, player_kill_sound_path) - - # bullet - bullet_img_path = "res/images/bullet.png" # 32 x 32 px image + + bullet_img_path = "Space Invaders/res/images/bullet.png" bullet_width = 32 bullet_height = 32 - bullet_x = player_x + player_width / 2 - bullet_width / 2 + bullet_x = player_x + player_width / 2 - bullet_width / 2 bullet_y = player_y + bullet_height / 2 bullet_dx = 0 bullet_dy = weapon_shot_velocity - bullet_fire_sound_path = "res/sounds/gunshot.wav" + bullet_fire_sound_path = "Space Invaders/res/sounds/gunshot.wav" global bullet bullet = Bullet(bullet_img_path, bullet_width, bullet_height, bullet_x, bullet_y, bullet_dx, bullet_dy, bullet_fire_sound_path) + - # enemy (number of enemy = level number) - enemy_img_path = "res/images/enemy.png" # 64 x 64 px image + enemy_img_path = "Space Invaders/res/images/enemy.png" enemy_width = 64 enemy_height = 64 enemy_dx = initial_enemy_velocity enemy_dy = (HEIGHT / 10) / 2 - enemy_kill_sound_path = "res/sounds/enemykill.wav" + enemy_kill_sound_path = "Space Invaders/res/sounds/enemykill.wav" - # laser beam (equals number of enemies and retains corresponding enemy position) - laser_img_path = "res/images/beam.png" # 24 x 24 px image + laser_img_path = "Space Invaders/res/images/beam.png" laser_width = 24 laser_height = 24 laser_dx = 0 laser_dy = weapon_shot_velocity shoot_probability = 0.3 - relaxation_time = 100 - laser_beam_sound_path = "res/sounds/laser.wav" + relaxition_time = 100 + laser_beam_sound_path = "Space Invaders/res/sounds/laser.wav" global enemies global lasers @@ -431,7 +370,7 @@ def init_game(): for lev in range(level): enemy_x = random.randint(0, (WIDTH - enemy_width)) - enemy_y = random.randint(((HEIGHT / 10) * 1 - (enemy_height / 2)), ((HEIGHT / 10) * 4 - (enemy_height / 2))) + enemy_y = random.randint(((HEIGHT // 10) * 1 - (enemy_height // 2)), ((HEIGHT // 10) * 4 - (enemy_height // 2))) laser_x = enemy_x + enemy_width / 2 - laser_width / 2 laser_y = enemy_y + laser_height / 2 @@ -440,87 +379,65 @@ def init_game(): enemies.append(enemy_obj) laser_obj = Laser(laser_img_path, laser_width, laser_height, laser_x, laser_y, laser_dx, laser_dy, - shoot_probability, relaxation_time, laser_beam_sound_path) + shoot_probability, relaxition_time, laser_beam_sound_path) lasers.append(laser_obj) -# init game init_game() init_background_music() -runned_once = False +rinned_once = False -# main game loop begins while running: - # start of frame timing start_time = time.time() - # background window.fill((0, 0, 0)) window.blit(background_img, (0, 0)) - # register events for event in pygame.event.get(): - # Quit Event if event.type == pygame.QUIT: running = False - # Keypress Down Event if event.type == pygame.KEYDOWN: - # Left Arrow Key down if event.key == pygame.K_LEFT: print("LOG: Left Arrow Key Pressed Down") LEFT_ARROW_KEY_PRESSED = 1 - # Right Arrow Key down if event.key == pygame.K_RIGHT: print("LOG: Right Arrow Key Pressed Down") RIGHT_ARROW_KEY_PRESSED = 1 - # Up Arrow Key down if event.key == pygame.K_UP: print("LOG: Up Arrow Key Pressed Down") UP_ARROW_KEY_PRESSED = 1 - # Space Bar down if event.key == pygame.K_SPACE: print("LOG: Space Bar Pressed Down") SPACE_BAR_PRESSED = 1 - # Enter Key down ("Carriage RETURN key" from old typewriter lingo) if event.key == pygame.K_RETURN: print("LOG: Enter Key Pressed Down") ENTER_KEY_PRESSED = 1 pause_state += 1 - # Esc Key down if event.key == pygame.K_ESCAPE: print("LOG: Escape Key Pressed Down") ESC_KEY_PRESSED = 1 pause_state += 1 - # Keypress Up Event if event.type == pygame.KEYUP: - # Right Arrow Key up if event.key == pygame.K_RIGHT: print("LOG: Right Arrow Key Released") RIGHT_ARROW_KEY_PRESSED = 0 - # Left Arrow Key up if event.key == pygame.K_LEFT: print("LOG: Left Arrow Key Released") LEFT_ARROW_KEY_PRESSED = 0 - # Up Arrow Key up if event.key == pygame.K_UP: print("LOG: Up Arrow Key Released") - UP_ARROW_KEY_PRESSED = 0 - # Space Bar up if event.key == pygame.K_SPACE: print("LOG: Space Bar Released") SPACE_BAR_PRESSED = 0 - # Enter Key up ("Carriage RETURN key" from old typewriter lingo) if event.key == pygame.K_RETURN: print("LOG: Enter Key Released") ENTER_KEY_PRESSED = 0 - # Esc Key up if event.key == pygame.K_ESCAPE: print("LOG: Escape Key Released") ESC_KEY_PRESSED = 0 - # check for pause game event if pause_state == 2: pause_state = 0 runned_once = False @@ -530,25 +447,19 @@ def init_game(): runned_once = True pause_game() continue - # manipulate game objects based on events and player actions - # player spaceship movement if RIGHT_ARROW_KEY_PRESSED: player.x += player.dx if LEFT_ARROW_KEY_PRESSED: player.x -= player.dx - # bullet firing if (SPACE_BAR_PRESSED or UP_ARROW_KEY_PRESSED) and not bullet.fired: bullet.fired = True bullet.fire_sound.play() bullet.x = player.x + player.width / 2 - bullet.width / 2 bullet.y = player.y + bullet.height / 2 - # bullet movement if bullet.fired: bullet.y -= bullet.dy - # iter through every enemies and lasers for i in range(len(enemies)): - # laser beaming if not lasers[i].beamed: lasers[i].shoot_timer += 1 if lasers[i].shoot_timer == lasers[i].relaxation_time: @@ -559,13 +470,10 @@ def init_game(): lasers[i].beam_sound.play() lasers[i].x = enemies[i].x + enemies[i].width / 2 - lasers[i].width / 2 lasers[i].y = enemies[i].y + lasers[i].height / 2 - # enemy movement enemies[i].x += enemies[i].dx * float(2 ** (difficulty - 1)) - # laser movement if lasers[i].beamed: lasers[i].y += lasers[i].dy - # collision check for i in range(len(enemies)): bullet_enemy_collision = collision_check(bullet, enemies[i]) if bullet_enemy_collision: @@ -579,7 +487,7 @@ def init_game(): for i in range(len(enemies)): enemy_player_collision = collision_check(enemies[i], player) if enemy_player_collision: - kill_enemy(player, bullet, enemies[i]) + kill_enemy(player, bullet, enemies[1]) kill_player(player, enemies[i], lasers[i]) for i in range(len(lasers)): @@ -587,13 +495,10 @@ def init_game(): if bullet_laser_collision: destroy_weapons(player, bullet, enemies[i], lasers[i]) - # boundary check: 0 <= x <= WIDTH, 0 <= y <= HEIGHT - # player spaceship if player.x < 0: player.x = 0 if player.x > WIDTH - player.width: player.x = WIDTH - player.width - # enemy for enemy in enemies: if enemy.x <= 0: enemy.dx = abs(enemy.dx) * 1 @@ -601,19 +506,16 @@ def init_game(): if enemy.x >= WIDTH - enemy.width: enemy.dx = abs(enemy.dx) * -1 enemy.y += enemy.dy - # bullet if bullet.y < 0: bullet.fired = False bullet.x = player.x + player.width / 2 - bullet.width / 2 bullet.y = player.y + bullet.height / 2 - # laser for i in range(len(lasers)): if lasers[i].y > HEIGHT: lasers[i].beamed = False lasers[i].x = enemies[i].x + enemies[i].width / 2 - lasers[i].width / 2 lasers[i].y = enemies[i].y + lasers[i].height / 2 - # create frame by placing objects on the surface scoreboard() for laser in lasers: laser.draw() @@ -622,19 +524,14 @@ def init_game(): bullet.draw() player.draw() - # render the display pygame.display.update() - # end of rendering, end on a frame frame_count += 1 end_time = time.time() single_frame_rendering_time = end_time - start_time - # fps = 1 / render_time total_time = total_time + single_frame_rendering_time if total_time >= 1.0: fps = frame_count frame_count = 0 total_time = 0 - # print("rendering time:", single_frame_rendering_time) - # print("FPS:", fps) diff --git a/Space Invaders/maintoretype.py b/Space Invaders/maintoretype.py new file mode 100644 index 0000000..a33fff8 --- /dev/null +++ b/Space Invaders/maintoretype.py @@ -0,0 +1,640 @@ +# Author: Atanu Sarkar +# Space Invaders (my version) +# v1.1.4 +# 11-April-2020, 03:04 AM (IST) + +import pygame +import random +import math +from pygame import mixer +import time + +# import sched + +# game constants +WIDTH = 800 +HEIGHT = 600 + +# global variables +running = True +pause_state = 0 +score = 0 +highest_score = 0 +life = 3 +kills = 0 +difficulty = 1 +level = 1 +max_kills_to_difficulty_up = 5 +max_difficulty_to_level_up = 5 +initial_player_velocity = 3.0 +initial_enemy_velocity = 1.0 +weapon_shot_velocity = 5.0 +single_frame_rendering_time = 0 +total_time = 0 +frame_count = 0 +fps = 0 + +# game objects +player = type('Player', (), {})() +bullet = type('Bullet', (), {})() +enemies = [] +lasers = [] + +# initialize pygame +pygame.init() + +# Input key states (keyboard) +LEFT_ARROW_KEY_PRESSED = 0 +RIGHT_ARROW_KEY_PRESSED = 0 +UP_ARROW_KEY_PRESSED = 0 +SPACE_BAR_PRESSED = 0 +ENTER_KEY_PRESSED = 0 +ESC_KEY_PRESSED = 0 + +# create display window +window = pygame.display.set_mode((WIDTH, HEIGHT)) +pygame.display.set_caption("Space Invaders") +window_icon = pygame.image.load("Space Invaders/res/images/alien.png") +pygame.display.set_icon(window_icon) + +# game sounds +pause_sound = None +level_up_sound = None +weapon_annihilation_sound = None +game_over_sound = None + +# create background +background_img = pygame.image.load("Space Invaders/res/images/background.jpg") # 800 x 600 px image +background_music_paths = ["res/sounds/Space_Invaders_Music.ogg", + "res/sounds/Space_Invaders_Music_x2.ogg", + "res/sounds/Space_Invaders_Music_x4.ogg", + "res/sounds/Space_Invaders_Music_x8.ogg", + "res/sounds/Space_Invaders_Music_x16.ogg", + "res/sounds/Space_Invaders_Music_x32.ogg"] + + +def init_background_music(): + if difficulty == 1: + mixer.quit() + mixer.init() + if difficulty <= 6: + mixer.music.load(background_music_paths[difficulty - 1]) + else: + mixer.music.load(background_music_paths[5]) + mixer.music.play(-1) + + +# create player class +class Player: + def __init__(self, img_path, width, height, x, y, dx, dy, kill_sound_path): + self.img_path = img_path + self.img = pygame.image.load(self.img_path) + self.width = width + self.height = height + self.x = x + self.y = y + self.dx = dx + self.dy = dy + self.kill_sound_path = kill_sound_path + self.kill_sound = mixer.Sound(self.kill_sound_path) + + def draw(self): + window.blit(self.img, (self.x, self.y)) + + +# create enemy class +class Enemy: + def __init__(self, img_path, width, height, x, y, dx, dy, kill_sound_path): + self.img_path = img_path + self.img = pygame.image.load(self.img_path) + self.width = width + self.height = height + self.x = x + self.y = y + self.dx = dx + self.dy = dy + self.kill_sound_path = kill_sound_path + self.kill_sound = mixer.Sound(self.kill_sound_path) + + def draw(self): + window.blit(self.img, (self.x, self.y)) + + +# create bullet class +class Bullet: + def __init__(self, img_path, width, height, x, y, dx, dy, fire_sound_path): + self.img_path = img_path + self.img = pygame.image.load(self.img_path) + self.width = width + self.height = height + self.x = x + self.y = y + self.dx = dx + self.dy = dy + self.fired = False + self.fire_sound_path = fire_sound_path + self.fire_sound = mixer.Sound(self.fire_sound_path) + + def draw(self): + if self.fired: + window.blit(self.img, (self.x, self.y)) + + +# create laser class +class Laser: + def __init__(self, img_path, width, height, x, y, dx, dy, shoot_probability, relaxation_time, beam_sound_path): + self.img_path = img_path + self.img = pygame.image.load(self.img_path) + self.width = width + self.height = height + self.x = x + self.y = y + self.dx = dx + self.dy = dy + self.beamed = False + self.shoot_probability = shoot_probability + self.shoot_timer = 0 + self.relaxation_time = relaxation_time + self.beam_sound_path = beam_sound_path + self.beam_sound = mixer.Sound(self.beam_sound_path) + + def draw(self): + if self.beamed: + window.blit(self.img, (self.x, self.y)) + + +def scoreboard(): + x_offset = 10 + y_offset = 10 + # set font type and size + font = pygame.font.SysFont("calibre", 16) + + # render font and text sprites + score_sprint = font.render("SCORE : " + str(score), True, (255, 255, 255)) + highest_score_sprint = font.render("HI-SCORE : " + str(highest_score), True, (255, 255, 255)) + level_sprint = font.render("LEVEL : " + str(level), True, (255, 255, 255)) + difficulty_sprint = font.render("DIFFICULTY : " + str(difficulty), True, (255, 255, 255)) + life_sprint = font.render("LIFE LEFT : " + str(life) + " | " + ("@ " * life), True, (255, 255, 255)) + + # performance info + fps_sprint = font.render("FPS : " + str(fps), True, (255, 255, 255)) + frame_time_in_ms = round(single_frame_rendering_time * 1000, 2) + frame_time_sprint = font.render("FT : " + str(frame_time_in_ms) + " ms", True, (255, 255, 255)) + + # place the font sprites on the screen + window.blit(score_sprint, (x_offset, y_offset)) + window.blit(highest_score_sprint, (x_offset, y_offset + 20)) + window.blit(level_sprint, (x_offset, y_offset + 40)) + window.blit(difficulty_sprint, (x_offset, y_offset + 60)) + window.blit(life_sprint, (x_offset, y_offset + 80)) + window.blit(fps_sprint, (WIDTH - 80, y_offset)) + window.blit(frame_time_sprint, (WIDTH - 80, y_offset + 20)) + + +def collision_check(object1, object2): + x1_cm = object1.x + object1.width / 2 + y1_cm = object1.y + object1.width / 2 + x2_cm = object2.x + object2.width / 2 + y2_cm = object2.y + object2.width / 2 + distance = math.sqrt(math.pow((x2_cm - x1_cm), 2) + math.pow((y2_cm - y1_cm), 2)) + return distance < ((object1.width + object2.width) / 2) + + +# def collision_check(object1_x, object1_y, object1_diameter, object2_x, object2_y, object2_diameter): +# x1_cm = object1_x + object1_diameter / 2 +# y1_cm = object1_y + object1_diameter / 2 +# x2_cm = object2_x + object2_diameter / 2 +# y2_cm = object2_y + object2_diameter / 2 +# distance = math.sqrt(math.pow((x2_cm - x1_cm), 2) + math.pow((y2_cm - y1_cm), 2)) +# return distance < ((object1_diameter + object2_diameter) / 2) + + +def level_up(): + global life + global level + global difficulty + global max_difficulty_to_level_up + level_up_sound.play() + level += 1 + life += 1 # grant a life + difficulty = 1 # reset difficulty + # TODO: change player and bullet speeds, enemy laser speed and firing probability wrt level + # come up with interesting gameplay ideas. + # variables in hand: + # 1. speed of weapons + # 2. enemy (up to 6) & player velocity + # 3. laser firing probability + # future ideas: + # 1. add new type of enemies + # 2. add new player spaceship and bullets! + # future features: + # 1. create player profile ad store highest score to DB + # 2. multiplayer + if level % 3 == 0: + player.dx += 1 + bullet.dy += 1 + max_difficulty_to_level_up += 1 + for each_laser in lasers: + each_laser.shoot_probability += 0.1 + if each_laser.shoot_probability > 1.0: + each_laser.shoot_probability = 1.0 + if max_difficulty_to_level_up > 7: + max_difficulty_to_level_up = 7 + + font = pygame.font.SysFont("freesansbold", 64) + gameover_sprint = font.render("LEVEL UP", True, (255, 255, 255)) + window.blit(gameover_sprint, (WIDTH / 2 - 120, HEIGHT / 2 - 32)) + pygame.display.update() + init_game() + time.sleep(1.0) + + +def respawn(enemy_obj): + enemy_obj.x = random.randint(0, (WIDTH - enemy_obj.width)) + enemy_obj.y = random.randint(((HEIGHT / 10) * 1 - (enemy_obj.height / 2)), + ((HEIGHT / 10) * 4 - (enemy_obj.height / 2))) + + +def kill_enemy(player_obj, bullet_obj, enemy_obj): + global score + global kills + global difficulty + bullet_obj.fired = False + enemy_obj.kill_sound.play() + bullet_obj.x = player_obj.x + player_obj.width / 2 - bullet_obj.width / 2 + bullet_obj.y = player_obj.y + bullet_obj.height / 2 + score = score + 10 * difficulty * level + kills += 1 + if kills % max_kills_to_difficulty_up == 0: + difficulty += 1 + if (difficulty == max_difficulty_to_level_up) and (life != 0): + level_up() + init_background_music() + print("Score:", score) + print("level:", level) + print("difficulty:", difficulty) + respawn(enemy_obj) + + +def rebirth(player_obj): + player_obj.x = (WIDTH / 2) - (player_obj.width / 2) + player_obj.y = (HEIGHT / 10) * 9 - (player_obj.height / 2) + + +def gameover_screen(): + scoreboard() + font = pygame.font.SysFont("freesansbold", 64) + gameover_sprint = font.render("GAME OVER", True, (255, 255, 255)) + window.blit(gameover_sprint, (WIDTH / 2 - 140, HEIGHT / 2 - 32)) + pygame.display.update() + + mixer.music.stop() + game_over_sound.play() + time.sleep(13.0) + mixer.quit() + + +def gameover(): + global running + global score + global highest_score + + if score > highest_score: + highest_score = score + + # console display + print("----------------") + print("GAME OVER !!") + print("----------------") + print("you died at") + print("Level:", level) + print("difficulty:", difficulty) + print("Your Score:", score) + print("----------------") + print("Try Again !!") + print("----------------") + running = False + gameover_screen() + + +def kill_player(player_obj, enemy_obj, laser_obj): + global life + laser_obj.beamed = False + player_obj.kill_sound.play() + laser_obj.x = enemy_obj.x + enemy_obj.width / 2 - laser_obj.width / 2 + laser_obj.y = enemy_obj.y + laser_obj.height / 2 + life -= 1 + print("Life Left:", life) + if life > 0: + rebirth(player_obj) + else: + gameover() + + +def destroy_weapons(player_obj, bullet_obj, enemy_obj, laser_obj): + bullet_obj.fired = False + laser_obj.beamed = False + weapon_annihilation_sound.play() + bullet_obj.x = player_obj.x + player_obj.width / 2 - bullet_obj.width / 2 + bullet_obj.y = player_obj.y + bullet_obj.height / 2 + laser_obj.x = enemy_obj.x + enemy_obj.width / 2 - laser_obj.width / 2 + laser_obj.y = enemy_obj.y + laser_obj.height / 2 + + +# timer = sched.scheduler(time.time, time.sleep) +# +# +# def calculate_fps(sc): +# global frame_count +# fps = frame_count +# print("FPS =", fps) +# frame_count = 0 +# timer.enter(60, 1, calculate_fps, (sc,)) +# +# +# timer.enter(60, 1, calculate_fps, (timer, )) +# timer.run() + + +def pause_game(): + pause_sound.play() + scoreboard() + font = pygame.font.SysFont("freesansbold", 64) + gameover_sprint = font.render("PAUSED", True, (255, 255, 255)) + window.blit(gameover_sprint, (WIDTH / 2 - 80, HEIGHT / 2 - 32)) + pygame.display.update() + mixer.music.pause() + + +def init_game(): + global pause_sound + global level_up_sound + global game_over_sound + global weapon_annihilation_sound + + pause_sound = mixer.Sound("Space Invaders/res/sounds/pause.wav") + level_up_sound = mixer.Sound("Space Invaders/res/sounds/1up.wav") + game_over_sound = mixer.Sound("Space Invaders/res/sounds/gameover.wav") + weapon_annihilation_sound = mixer.Sound("Space Invaders/res/sounds/annihilation.wav") + + # player + player_img_path = "Space Invaders/res/images/spaceship.png" # 64 x 64 px image + player_width = 64 + player_height = 64 + player_x = (WIDTH / 2) - (player_width / 2) + player_y = (HEIGHT / 10) * 9 - (player_height / 2) + player_dx = initial_player_velocity + player_dy = 0 + player_kill_sound_path = "Space Invaders/res/sounds/explosion.wav" + + global player + player = Player(player_img_path, player_width, player_height, player_x, player_y, player_dx, player_dy, + player_kill_sound_path) + + # bullet + bullet_img_path = "Space Invaders/res/images/bullet.png" # 32 x 32 px image + bullet_width = 32 + bullet_height = 32 + bullet_x = player_x + player_width / 2 - bullet_width / 2 + bullet_y = player_y + bullet_height / 2 + bullet_dx = 0 + bullet_dy = weapon_shot_velocity + bullet_fire_sound_path = "Space Invaders/res/sounds/gunshot.wav" + + global bullet + bullet = Bullet(bullet_img_path, bullet_width, bullet_height, bullet_x, bullet_y, bullet_dx, bullet_dy, + bullet_fire_sound_path) + + # enemy (number of enemy = level number) + enemy_img_path = "Space Invaders/res/images/enemy.png" # 64 x 64 px image + enemy_width = 64 + enemy_height = 64 + enemy_dx = initial_enemy_velocity + enemy_dy = (HEIGHT / 10) / 2 + enemy_kill_sound_path = "Space Invaders/res/sounds/enemykill.wav" + + # laser beam (equals number of enemies and retains corresponding enemy position) + laser_img_path = "Space Invaders/res/images/beam.png" # 24 x 24 px image + laser_width = 24 + laser_height = 24 + laser_dx = 0 + laser_dy = weapon_shot_velocity + shoot_probability = 0.3 + relaxation_time = 100 + laser_beam_sound_path = "Space Invaders/res/sounds/laser.wav" + + global enemies + global lasers + + enemies.clear() + lasers.clear() + + for lev in range(level): + enemy_x = random.randint(0, (WIDTH - enemy_width)) + enemy_y = random.randint(((HEIGHT // 10) * 1 - (enemy_height // 2)), ((HEIGHT // 10) * 4 - (enemy_height // 2))) + laser_x = enemy_x + enemy_width / 2 - laser_width / 2 + laser_y = enemy_y + laser_height / 2 + + enemy_obj = Enemy(enemy_img_path, enemy_width, enemy_height, enemy_x, enemy_y, enemy_dx, enemy_dy, + enemy_kill_sound_path) + enemies.append(enemy_obj) + + laser_obj = Laser(laser_img_path, laser_width, laser_height, laser_x, laser_y, laser_dx, laser_dy, + shoot_probability, relaxation_time, laser_beam_sound_path) + lasers.append(laser_obj) + + +# init game +init_game() +init_background_music() +runned_once = False + +# main game loop begins +while running: + # start of frame timing + start_time = time.time() + + # background + window.fill((0, 0, 0)) + window.blit(background_img, (0, 0)) + + # register events + for event in pygame.event.get(): + # Quit Event + if event.type == pygame.QUIT: + running = False + + # Keypress Down Event + if event.type == pygame.KEYDOWN: + # Left Arrow Key down + if event.key == pygame.K_LEFT: + print("LOG: Left Arrow Key Pressed Down") + LEFT_ARROW_KEY_PRESSED = 1 + # Right Arrow Key down + if event.key == pygame.K_RIGHT: + print("LOG: Right Arrow Key Pressed Down") + RIGHT_ARROW_KEY_PRESSED = 1 + # Up Arrow Key down + if event.key == pygame.K_UP: + print("LOG: Up Arrow Key Pressed Down") + UP_ARROW_KEY_PRESSED = 1 + # Space Bar down + if event.key == pygame.K_SPACE: + print("LOG: Space Bar Pressed Down") + SPACE_BAR_PRESSED = 1 + # Enter Key down ("Carriage RETURN key" from old typewriter lingo) + if event.key == pygame.K_RETURN: + print("LOG: Enter Key Pressed Down") + ENTER_KEY_PRESSED = 1 + pause_state += 1 + # Esc Key down + if event.key == pygame.K_ESCAPE: + print("LOG: Escape Key Pressed Down") + ESC_KEY_PRESSED = 1 + pause_state += 1 + + # Keypress Up Event + if event.type == pygame.KEYUP: + # Right Arrow Key up + if event.key == pygame.K_RIGHT: + print("LOG: Right Arrow Key Released") + RIGHT_ARROW_KEY_PRESSED = 0 + # Left Arrow Key up + if event.key == pygame.K_LEFT: + print("LOG: Left Arrow Key Released") + LEFT_ARROW_KEY_PRESSED = 0 + # Up Arrow Key up + if event.key == pygame.K_UP: + print("LOG: Up Arrow Key Released") + UP_ARROW_KEY_PRESSED = 0 + # Space Bar up + if event.key == pygame.K_SPACE: + print("LOG: Space Bar Released") + SPACE_BAR_PRESSED = 0 + # Enter Key up ("Carriage RETURN key" from old typewriter lingo) + if event.key == pygame.K_RETURN: + print("LOG: Enter Key Released") + ENTER_KEY_PRESSED = 0 + # Esc Key up + if event.key == pygame.K_ESCAPE: + print("LOG: Escape Key Released") + ESC_KEY_PRESSED = 0 + + # check for pause game event + if pause_state == 2: + pause_state = 0 + runned_once = False + mixer.music.unpause() + if pause_state == 1: + if not runned_once: + runned_once = True + pause_game() + continue + # manipulate game objects based on events and player actions + # player spaceship movement + if RIGHT_ARROW_KEY_PRESSED: + player.x += player.dx + if LEFT_ARROW_KEY_PRESSED: + player.x -= player.dx + # bullet firing + if (SPACE_BAR_PRESSED or UP_ARROW_KEY_PRESSED) and not bullet.fired: + bullet.fired = True + bullet.fire_sound.play() + bullet.x = player.x + player.width / 2 - bullet.width / 2 + bullet.y = player.y + bullet.height / 2 + # bullet movement + if bullet.fired: + bullet.y -= bullet.dy + + # iter through every enemies and lasers + for i in range(len(enemies)): + # laser beaming + if not lasers[i].beamed: + lasers[i].shoot_timer += 1 + if lasers[i].shoot_timer == lasers[i].relaxation_time: + lasers[i].shoot_timer = 0 + random_chance = random.randint(0, 100) + if random_chance <= (lasers[i].shoot_probability * 100): + lasers[i].beamed = True + lasers[i].beam_sound.play() + lasers[i].x = enemies[i].x + enemies[i].width / 2 - lasers[i].width / 2 + lasers[i].y = enemies[i].y + lasers[i].height / 2 + # enemy movement + enemies[i].x += enemies[i].dx * float(2 ** (difficulty - 1)) + # laser movement + if lasers[i].beamed: + lasers[i].y += lasers[i].dy + + # collision check + for i in range(len(enemies)): + bullet_enemy_collision = collision_check(bullet, enemies[i]) + if bullet_enemy_collision: + kill_enemy(player, bullet, enemies[i]) + + for i in range(len(lasers)): + laser_player_collision = collision_check(lasers[i], player) + if laser_player_collision: + kill_player(player, enemies[i], lasers[i]) + + for i in range(len(enemies)): + enemy_player_collision = collision_check(enemies[i], player) + if enemy_player_collision: + kill_enemy(player, bullet, enemies[i]) + kill_player(player, enemies[i], lasers[i]) + + for i in range(len(lasers)): + bullet_laser_collision = collision_check(bullet, lasers[i]) + if bullet_laser_collision: + destroy_weapons(player, bullet, enemies[i], lasers[i]) + + # boundary check: 0 <= x <= WIDTH, 0 <= y <= HEIGHT + # player spaceship + if player.x < 0: + player.x = 0 + if player.x > WIDTH - player.width: + player.x = WIDTH - player.width + # enemy + for enemy in enemies: + if enemy.x <= 0: + enemy.dx = abs(enemy.dx) * 1 + enemy.y += enemy.dy + if enemy.x >= WIDTH - enemy.width: + enemy.dx = abs(enemy.dx) * -1 + enemy.y += enemy.dy + # bullet + if bullet.y < 0: + bullet.fired = False + bullet.x = player.x + player.width / 2 - bullet.width / 2 + bullet.y = player.y + bullet.height / 2 + # laser + for i in range(len(lasers)): + if lasers[i].y > HEIGHT: + lasers[i].beamed = False + lasers[i].x = enemies[i].x + enemies[i].width / 2 - lasers[i].width / 2 + lasers[i].y = enemies[i].y + lasers[i].height / 2 + + # create frame by placing objects on the surface + scoreboard() + for laser in lasers: + laser.draw() + for enemy in enemies: + enemy.draw() + bullet.draw() + player.draw() + + # render the display + pygame.display.update() + + # end of rendering, end on a frame + frame_count += 1 + end_time = time.time() + single_frame_rendering_time = end_time - start_time + # fps = 1 / render_time + + total_time = total_time + single_frame_rendering_time + if total_time >= 1.0: + fps = frame_count + frame_count = 0 + total_time = 0 + # print("rendering time:", single_frame_rendering_time) + # print("FPS:", fps) diff --git a/Space Invaders/rocket.png b/Space Invaders/rocket.png new file mode 100644 index 0000000..724ed92 Binary files /dev/null and b/Space Invaders/rocket.png differ diff --git a/Space Invaders/simpletryout.py b/Space Invaders/simpletryout.py new file mode 100644 index 0000000..86c56cd --- /dev/null +++ b/Space Invaders/simpletryout.py @@ -0,0 +1,338 @@ +# Базовая игра, которую написал сам: 8-бит, классика, два блока +# Одним мы управляем, два других - враг и союзник. +# Уворачиваемся от одного и собираем другого, увеличиваем очки. +# Обрати внимание на рандомные переменные и какие именно числа я использую + + +import pygame +import sys +import random + + +# инициализация конструктора +pygame.init() +res = (720, 720) + +# рандомно назначаем значения переменных +# начиная с нижнего и до самого верхнего значения +c1 = random.randint(125, 255) +c2 = random.randint(0, 255) +c3 = random.randint(0, 255) + +screen = pygame.display.set_mode(res) +clock = pygame.time.Clock() +red = (255, 0, 0) +green = (0, 255, 0) +blue = (0, 0, 255) +color_list = [red, green, blue] +colox_c1 = 0 +colox_c2 = 0 +colox_c3 = 254 +colox_c4 = 254 + +# рандомно назначаем игроку цвет из списка color_list +player_c = random.choice(color_list) + +# слегка оттеняем кнопки +startl = (169, 169, 169) + +# затемняем кнопки в стартовом меню +startd = (100, 100, 100) +white = (255, 255, 255) +start = (255, 255, 255) +width = screen.get_width() +height = screen.get_height() + +# начальная Х позиция игрока +lead_x = 40 + +# начальная У позиция игрока +lead_y = height / 2 +x = 300 +y = 290 +width1 = 100 +height1 = 40 +enemy_size = 50 + +# определяем шрифт для игры +smallfont = pygame.font.SysFont('Corbel', 35) + +# какие текста будут существовать и рендериться на экране +text = smallfont.render('Start', True, white) +text1 = smallfont.render('Options', True, white) +exit1 = smallfont.render('Exit', True, white) + +# название игры +colox = smallfont.render('Colox', True, (c3, c2, c1)) +x1 = random.randint(width // 2, width) +y1 = random.randint(100, height // 2) +x2 = 40 +y2 = 40 +speed = 15 + +# очки игрока +count = 0 +rgb = random.choice(color_list) + +# позиция противника +e_p = [width, random.randint(50, height - 50)] +e1_p = [random.randint(width, width + 100), random.randint(50, height + - 100)] + + +# функция для геймовера +def game_over(): + + while True: + + # проверка на случай если игрок нажмет кнопку cross + for ev in pygame.event.get(): + if ev.type == pygame.QUIT: + pygame.quit() + + if ev.type == pygame.MOUSEBUTTONDOWN: + if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] \ + < height - 80: + pygame.quit() + + if ev.type == pygame.MOUSEBUTTONDOWN: + if width - 180 < mouse1[0] < width - 100 and height \ + - 100 < mouse1[1] < height - 80: + + # зовём игровую функцию + game(lead_x, lead_y, speed, count) + + # заполняем экран определённым цветом + screen.fill((65, 25, 64)) + smallfont = pygame.font.SysFont('Corbel', 60) + smallfont1 = pygame.font.SysFont('Corbel', 25) + game_over = smallfont.render('GAME OVER', True, white) + game_exit = smallfont1.render('exit', True, white) + restart = smallfont1.render('restart', True, white) + mouse1 = pygame.mouse.get_pos() + + # выход + if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80: + pygame.draw.rect(screen, startl, [100, height - 100, 40,20]) + else: + pygame.draw.rect(screen, startd, [100, height - 100, 40,20]) + + # рестарт + if width - 180 < mouse1[0] < width - 100 and height - 100 < mouse1[1] < height - 80: + pygame.draw.rect(screen, startl, [width - 180, height- 100, 80, 20]) + else: + pygame.draw.rect(screen, startd, [width - 180, height- 100, 80, 20]) + + screen.blit(game_exit, (100, height - 100)) + + # расположение объектов + screen.blit(restart, (width - 180, height - 100)) + screen.blit(game_over, (width / 2 - 150, 295)) + + # обновление экрана + pygame.display.update() + + +pygame.draw.rect(screen, startd, [100, height - 100, 40, 20]) +pygame.draw.rect(screen, startd, [width - 180, height - 100, 40, 50]) + + + +# игровая функция или тело +def game( + lead_y, + lead_X, + speed, + count, + ): + + while True: + for ev in pygame.event.get(): + if ev.type == pygame.QUIT: + pygame.quit() + + + # управление + # слкедит за нажатыми клавишами + keys = pygame.key.get_pressed() + if keys[pygame.K_UP]: + + # если стрелочка вверх нажата то + # у будет уменьшаться на -10 + lead_y -= 10 + if keys[pygame.K_DOWN]: + + # если стрелка вниз будет нажата + # то позиция у будет увеличиваться на 10 + lead_y += 10 + screen.fill((65, 25, 64)) + clock.tick(speed) + + # отрисовка квадратов + rect = pygame.draw.rect(screen, player_c, [lead_x, lead_y, 40,40]) + pygame.draw.rect(screen, (c1, c2, c3), [0, 0, width, 40]) + pygame.draw.rect(screen, (c3, c2, c1), [0, 680, width, 40]) + pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) + smallfont = pygame.font.SysFont('Corbel', 35) + exit2 = smallfont.render('Exit', True, white) + + # выход + # получает позицию мыши, Х и У координаты + # сохраняет их в качестве tuple + mouse = pygame.mouse.get_pos() + if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: + pygame.draw.rect(screen, startl, [width - 100, 0, 100, 40]) + else: + pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40]) + if width - 100 < mouse[0] < width and 0 < mouse[1] < 40: + if ev.type == pygame.MOUSEBUTTONDOWN: + pygame.quit() + + # позиция врага + if e_p[0] > 0 and e_p[0] <= width: + + e_p[0] -= 10 + else: + if e_p[1] <= 40 or e_p[1] >= height - 40: + e_p[1] = height / 2 + if e1_p[1] <= 40 or e1_p[1] >= height - 40: + e1_p[1] = random.randint(40, height - 40) + e_p[1] = random.randint(enemy_size, height - enemy_size) + e_p[0] = width + + + # гей овер + # проверка столкновений + if lead_x <= e_p[0] <= lead_x + 40 and lead_y >= e_p[1] >= lead_y - 40: + game_over() + + # провреяем столкнулся ли игрок с кубом-противником + if lead_y <= e_p[1] + enemy_size <= lead_y + 40 and lead_x <= e_p[0] <= lead_x + 40: + game_over() + + pygame.draw.rect(screen, red, [e_p[0], e_p[1], enemy_size,enemy_size]) + if e1_p[0] > 0 and e1_p[0] <= width + 100: + e1_p[0] -= 10 + else: + if e1_p[1] <= 40 or e1_p[1] >= height - 40: + e1_p[1] = height / 2 + e1_p[1] = random.randint(enemy_size, height - 40) + e1_p[0] = width + 100 + + if lead_x <= e1_p[0] <= lead_x + 40 and lead_y >= e1_p[1] >= lead_y - 40: + e1_p[0] = width + 100 + e1_p[1] = random.randint(40, height - 40) + count += 1 + speed += 1 + if lead_y <= e1_p[1] + enemy_size <= lead_y + 40 and lead_x <= e1_p[0] <= lead_x + 40: + + e1_p[0] = width + 100 + e1_p[1] = random.randint(40, height - 40) + + # увеличивает очки если синий куб задет + count += 1 + + # увеличиваем скорость по мере увеличения очков + speed += 1 + + if count >= 45: + + # фиксация на 60 фпс + speed = 60 + + if lead_y <= 38 or lead_y >= height - 38: + game_over() + if e1_p[0] <= 0: + game_over() + + pygame.draw.rect(screen, blue, [e1_p[0], e1_p[1], enemy_size, + enemy_size]) + score1 = smallfont.render('Score:', True, white) + screen.blit(score1, (width - 120, height - 40)) + screen.blit(exit2, (width - 80, 0)) + pygame.display.update() + + +# интро +def intro( + colox_c1, + colox_c2, + colox, + exit1, + text1, + text, + ): + intro = True + while intro: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + screen.fill((65, 25, 64)) + mouse = pygame.mouse.get_pos() + + # начальный экран + if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: + + # если мышь над кнопкой + # то цвет тени становится слегка светлее + pygame.draw.rect(screen, startl, [x, y, width1, height1]) + else: + if x < mouse[0] < x + width1 + 40 and y + 70 < mouse[1] < y \ + + 70 + height1: + pygame.draw.rect(screen, startl, [x, y + 70, width1+40,height1]) + else: + + if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: + pygame.draw.rect(screen, startl, [x, y + 140,width1,height1]) + else: + pygame.draw.rect(screen, startd, [x, y, width1,height1]) + pygame.draw.rect(screen, startd, [x, y + 70, width1 + + 40, height1]) + pygame.draw.rect(screen, startd, [x, y + 140,width1, height1]) + + # кнопка старт + if event.type == pygame.MOUSEBUTTONDOWN: + if x < mouse[0] < x + width1 and y < mouse[1] < y + height1: + #music() + game(lead_y, lead_x, speed, count) + + if event.type == pygame.MOUSEBUTTONDOWN: + if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1: + pygame.quit() + + # это для лёгкого градиента в цветах + if 0 <= colox_c1 <= 254 or 0 <= colox_c2 <= 254: + colox_c1 += 1 + colox_c2 += 1 + if colox_c1 >= 254 or colox_c2 >= 254: + colox_c1 = c3 + colox_c2 = c3 + + pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [0, 0, 40, + height]) + pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [width - 40, + 0, 40, height]) + smallfont = pygame.font.SysFont('Corbel', 35) + sig = smallfont.render('Designed by :- Antriksh', True, white) + text = smallfont.render('Start', True, white) + text1 = smallfont.render('Options', True, white) + exit1 = smallfont.render('Exit', True, white) + colox = smallfont.render('Colox', True, (c1, colox_c1, + colox_c2)) + screen.blit(colox, (312, 50)) + screen.blit(text, (312, 295)) + screen.blit(text1, (312, 365)) + screen.blit(exit1, (312, 435)) + screen.blit(sig, (320, height - 50)) + clock.tick(60) + pygame.display.update() + + +intro( + colox_c1, + colox_c2, + colox, + exit1, + text1, + text, + ) \ No newline at end of file diff --git a/Space Invaders/spaceship.png b/Space Invaders/spaceship.png new file mode 100644 index 0000000..40fce68 Binary files /dev/null and b/Space Invaders/spaceship.png differ