import pygame from pygame import mixer import os import csv import Button mixer.init() pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = int(SCREEN_WIDTH * 0.8) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Shooter') #set framerate clock = pygame.time.Clock() FPS = 60 #define game variables GRAVITY = 0.75 SCROLL_THRESH = 100 ROWS = 16 COLS = 150 TILE_SIZE = SCREEN_HEIGHT // ROWS TILE_TYPES = 21 MAX_LEVELS = 3 screen_scroll = 0 bg_scroll = 0 level = 1 start_game = False start_intro = False #define player action variables moving_left = False moving_right = False shoot = False grenade = False grenade_thrown = False #load music and sounds #pygame.mixer.music.load('audio/music2.mp3') #pygame.mixer.music.set_volume(0.3) #pygame.mixer.music.play(-1, 0.0, 5000) jump_fx = pygame.mixer.Sound('Shooter-main/audio/jump.wav') jump_fx.set_volume(0.05) #load images #Button images start_img = pygame.image.load('Shooter-main/img/start_btn.png').convert_alpha() exit_img = pygame.image.load('Shooter-main/img/exit_btn.png').convert_alpha() restart_img = pygame.image.load('Shooter-main/img/restart_btn.png').convert_alpha() #background pine1_img = pygame.image.load('Shooter-main/img/Background/pine1.png').convert_alpha() pine2_img = pygame.image.load('Shooter-main/img/Background/pine2.png').convert_alpha() mountain_img = pygame.image.load('Shooter-main/img/Background/mountain.png').convert_alpha() sky_img = pygame.image.load('Shooter-main/img/Background/sky_cloud.png').convert_alpha() #store tiles in a list img_list = [] for x in range(TILE_TYPES): img = pygame.image.load(f'Shooter-main/img/Tile/{x}.png') img = pygame.transform.scale(img, (TILE_SIZE, TILE_SIZE)) img_list.append(img) #define colours BG = (144, 201, 120) RED = (255, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) BLACK = (0, 0, 0) PINK = (235, 65, 54) #define font font = pygame.font.SysFont('Futura', 30) def draw_text(text, font, text_col, x, y): img = font.render(text, True, text_col) screen.blit(img, (x, y)) def draw_bg(): screen.fill(BG) width = sky_img.get_width() for x in range(5): screen.blit(sky_img, ((x * width) - bg_scroll * 0.5, 0)) screen.blit(mountain_img, ((x * width) - bg_scroll * 0.6, SCREEN_HEIGHT - mountain_img.get_height() - 300)) screen.blit(pine1_img, ((x * width) - bg_scroll * 0.7, SCREEN_HEIGHT - pine1_img.get_height() - 150)) screen.blit(pine2_img, ((x * width) - bg_scroll * 0.8, SCREEN_HEIGHT - pine2_img.get_height())) #function to reset level def reset_level(): decoration_group.empty() water_group.empty() exit_group.empty() #create empty tile list data = [] for row in range(ROWS): r = [-1] * COLS data.append(r) return data #world class Soldier(pygame.sprite.Sprite): def __init__(self, char_type, x, y, scale, speed, ammo, grenades): pygame.sprite.Sprite.__init__(self) self.alive = True self.char_type = char_type self.speed = speed self.health = 100 self.max_health = self.health self.extra_jump = 1 self.direction = 1 self.vel_y = 0 self.jump = False self.in_air = True self.flip = False self.animation_list = [] self.frame_index = 0 self.action = 0 self.update_time = pygame.time.get_ticks() self.move_counter = 0 self.vision = pygame.Rect(0, 0, 150, 20) self.idling = False self.idling_counter = 0 animation_types = ['Idle', 'Run', 'Jump', 'Death'] for animation in animation_types: temp_list = [] num_of_frames = len(os.listdir(f'Shooter-main/img/{self.char_type}/{animation}')) for i in range(num_of_frames): img = pygame.image.load(f'Shooter-main/img/{self.char_type}/{animation}/{i}.png').convert_alpha() img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) temp_list.append(img) self.animation_list.append(temp_list) self.image = self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y) self.width = self.image.get_width() self.height = self.image.get_height() def update(self): self.update_animation() # Ensure animation is updated every frame self.check_alive() # Cooldown for shooting, if applicable def move(self, moving_left, moving_right): screen_scroll = 0 dx = 0 dy = 0 level_complete = False # Moving left if moving_left: dx = -self.speed self.flip = True self.direction = -1 # Moving right if moving_right: dx = self.speed self.flip = False self.direction = 1 # Handle scrolling if self.rect.centerx >= SCREEN_WIDTH // 2 and moving_right: screen_scroll = -dx if self.rect.centerx <= SCREEN_WIDTH // 2 and moving_left: screen_scroll = -dx #jump if self.jump == True and self.in_air == False: self.vel_y = -11 self.jump = False self.in_air = True elif self.jump == True and self.in_air == True: if self.extra_jump == 1: self.vel_y = -11 self.jump = False self.in_air = True self.extra_jump = 0 # Apply gravity self.vel_y += GRAVITY if self.vel_y > 10: self.vel_y dy += self.vel_y # Check for collisions with tiles for tile in world.obstacle_list: if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height): dx = 0 if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height): if self.vel_y < 0: self.vel_y = 0 dy = tile[1].bottom - self.rect.top elif self.vel_y >= 0: self.vel_y = 0 self.in_air = False self.extra_jump = 1 dy = tile[1].top - self.rect.bottom # Ensure the player is still in bounds if self.rect.bottom > SCREEN_HEIGHT: self.health = 0 # Check if the player reaches the exit for exit_tile in world.exit_group: if self.rect.colliderect(exit_tile.rect): level_complete = True # Update the player’s position self.rect.x += dx self.rect.y += dy # Apply screen scrolling adjustments self.rect.x += screen_scroll return screen_scroll, level_complete def update_animation(self): ANIMATION_COOLDOWN = 100 # Cooldown time for updating the animation (in milliseconds) # Check the current action and update the animation self.image = self.animation_list[self.action][self.frame_index] # Update the frame only if the cooldown has passed if pygame.time.get_ticks() - self.update_time > ANIMATION_COOLDOWN: self.frame_index += 1 self.update_time = pygame.time.get_ticks() # If the frame index exceeds the animation frames, reset or loop if self.frame_index >= len(self.animation_list[self.action]): if self.action == 3: # Death animation, should freeze at the last frame self.frame_index = len(self.animation_list[self.action]) - 1 else: self.frame_index = 0 # Loop the animation for idle, run, or jump def update_action(self, new_action): if new_action != self.action: self.action = new_action self.frame_index = 0 self.update_time = pygame.time.get_ticks() def check_alive(self): if self.health <= 0: self.health = 0 self.speed = 0 self.alive = False self.update_action(3) def draw(self): screen.blit(pygame.transform.flip(self.image, self.flip, False), self.rect) class World: def __init__(self): self.obstacle_list = [] self.water_group = pygame.sprite.Group() self.enemy_group = pygame.sprite.Group() self.item_box_group = pygame.sprite.Group() self.decoration_group = pygame.sprite.Group() self.exit_group = pygame.sprite.Group() def process_data(self, data): self.level_length = len(data[0]) player = None health_bar = None for y, row in enumerate(data): for x, tile in enumerate(row): if tile >= 0: img = img_list[tile] img_rect = img.get_rect() img_rect.x = x * TILE_SIZE img_rect.y = y * TILE_SIZE tile_data = (img, img_rect) if tile >= 0 and tile <= 8: self.obstacle_list.append(tile_data) elif tile >= 9 and tile <= 10: water = Water(img, x * TILE_SIZE, y * TILE_SIZE) self.water_group.add(water) elif tile >= 11 and tile <= 14: decoration = Decoration(img, x * TILE_SIZE, y * TILE_SIZE) self.decoration_group.add(decoration) elif tile == 15: player = Soldier('player', x * TILE_SIZE, y * TILE_SIZE, 1.65, 5, 20, 5) health_bar = HealthBar(10, 10, player.health, player.health) return player, health_bar def draw(self): # Scroll and draw obstacles for tile in self.obstacle_list: tile[1].x += screen_scroll screen.blit(tile[0], tile[1]) # Scroll and draw each group for group in [self.water_group, self.enemy_group, self.item_box_group, self.decoration_group, self.exit_group]: for sprite in group: sprite.rect.x += screen_scroll group.draw(screen) def update(self): for tile in self.obstacle_list: tile[1].x += screen_scroll self.water_group.update() self.enemy_group.update() self.item_box_group.update() self.decoration_group.update() self.exit_group.update() def reset_level(self): self.obstacle_list.clear() self.water_group.empty() self.enemy_group.empty() self.item_box_group.empty() self.decoration_group.empty() self.exit_group.empty() class Decoration(pygame.sprite.Sprite): def __init__(self, img, x, y): pygame.sprite.Sprite.__init__(self) self.image = img self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): self.rect.x += screen_scroll class Water(pygame.sprite.Sprite): def __init__(self, img, x, y): pygame.sprite.Sprite.__init__(self) self.image = img self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): self.rect.x += screen_scroll class Exit(pygame.sprite.Sprite): def __init__(self, img, x, y): pygame.sprite.Sprite.__init__(self) self.image = img self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): self.rect.x += screen_scroll def update(self): #scroll self.rect.x += screen_scroll #check if the player has picked up the box if pygame.sprite.collide_rect(self, player): #check what kind of box it was if self.item_type == 'Health': player.health += 25 if player.health > player.max_health: player.health = player.max_health elif self.item_type == 'Ammo': player.ammo += 15 elif self.item_type == 'Grenade': player.grenades += 3 #delete the item box self.kill() class HealthBar(): def __init__(self, x, y, health, max_health): self.x = x self.y = y self.health = health self.max_health = max_health def draw(self, health): #update with new health self.health = health #calculate health ratio ratio = self.health / self.max_health pygame.draw.rect(screen, BLACK, (self.x - 2, self.y - 2, 154, 24)) pygame.draw.rect(screen, RED, (self.x, self.y, 150, 20)) pygame.draw.rect(screen, GREEN, (self.x, self.y, 150 * ratio, 20)) class Bullet(pygame.sprite.Sprite): def __init__(self, x, y, direction, image): pygame.sprite.Sprite.__init__(self) self.speed = 6 self.image = image if direction == -1: self.image = pygame.transform.flip(self.image, True, False) self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = direction self.invulnerable_time = 0 # Time in frames that the bullet is invulnerable def update(self): # Decrease the invulnerability time (0.3 seconds roughly at 60 FPS = 18 frames) if self.invulnerable_time > 0: self.invulnerable_time -= 1 # Move the bullet self.rect.x += (self.direction * self.speed) + screen_scroll # Check if bullet has gone off-screen if self.rect.right < 0 or self.rect.left > SCREEN_WIDTH: self.kill() # Check for collision with the world (obstacles) for tile in world.obstacle_list: if tile[1].colliderect(self.rect) and self.invulnerable_time <= 0: self.kill() # Check for collision with the player or enemies only if invulnerable time has passed if self.invulnerable_time <= 0: if pygame.sprite.spritecollide(player, bullet_group, False): if player.alive: player.health -= 5 self.kill() for enemy in enemy_group: if pygame.sprite.spritecollide(enemy, bullet_group, False): if enemy.alive: enemy.health -= 25 self.kill() def make_invulnerable(self): # Set invulnerable time (18 frames, roughly 0.3 seconds at 60 FPS) self.invulnerable_time = 18 def update(self): self.vel_y += GRAVITY dx = self.direction * self.speed dy = self.vel_y #check for collision with level for tile in world.obstacle_list: #check collision with walls if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height): self.direction *= -1 dx = self.direction * self.speed #check for collision in the y direction if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height): self.speed = 0 #check if below the ground, i.e. thrown up if self.vel_y < 0: self.vel_y = 0 dy = tile[1].bottom - self.rect.top #check if above the ground, i.e. falling elif self.vel_y >= 0: self.vel_y = 0 dy = tile[1].top - self.rect.bottom class Explosion(pygame.sprite.Sprite): def __init__(self, x, y, scale): pygame.sprite.Sprite.__init__(self) self.images = [] for num in range(1, 6): img = pygame.image.load(f'Shooter-main/img/explosion/exp{num}.png').convert_alpha() img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) self.images.append(img) self.frame_index = 0 self.image = self.images[self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y) self.counter = 0 def update(self): #scroll self.rect.x += screen_scroll EXPLOSION_SPEED = 4 #update explosion amimation self.counter += 1 if self.counter >= EXPLOSION_SPEED: self.counter = 0 self.frame_index += 1 #if the animation is complete then delete the explosion if self.frame_index >= len(self.images): self.kill() else: self.image = self.images[self.frame_index] class ScreenFade(): def __init__(self, direction, colour, speed): self.direction = direction self.colour = colour self.speed = speed self.fade_counter = 0 def fade(self): fade_complete = False self.fade_counter += self.speed if self.direction == 1:#whole screen fade pygame.draw.rect(screen, self.colour, (0 - self.fade_counter, 0, SCREEN_WIDTH // 2, SCREEN_HEIGHT)) pygame.draw.rect(screen, self.colour, (SCREEN_WIDTH // 2 + self.fade_counter, 0, SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.draw.rect(screen, self.colour, (0, 0 - self.fade_counter, SCREEN_WIDTH, SCREEN_HEIGHT // 2)) pygame.draw.rect(screen, self.colour, (0, SCREEN_HEIGHT // 2 +self.fade_counter, SCREEN_WIDTH, SCREEN_HEIGHT)) if self.direction == 2:#vertical screen fade down pygame.draw.rect(screen, self.colour, (0, 0, SCREEN_WIDTH, 0 + self.fade_counter)) if self.fade_counter >= SCREEN_WIDTH: fade_complete = True return fade_complete #create screen fades intro_fade = ScreenFade(1, BLACK, 4) death_fade = ScreenFade(2, PINK, 4) #create Buttons start_Button = Button.Button(SCREEN_WIDTH // 2 - 130, SCREEN_HEIGHT // 2 - 150, start_img, 1) exit_Button = Button.Button(SCREEN_WIDTH // 2 - 110, SCREEN_HEIGHT // 2 + 50, exit_img, 1) restart_Button = Button.Button(SCREEN_WIDTH // 2 - 100, SCREEN_HEIGHT // 2 - 50, restart_img, 2) #create sprite groups enemy_group = pygame.sprite.Group() bullet_group = pygame.sprite.Group() grenade_group = pygame.sprite.Group() explosion_group = pygame.sprite.Group() item_box_group = pygame.sprite.Group() decoration_group = pygame.sprite.Group() water_group = pygame.sprite.Group() exit_group = pygame.sprite.Group() #create empty tile list world_data = [] for row in range(ROWS): r = [-1] * COLS world_data.append(r) #load in level data and create world with open(f'Images/level{level}_data.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for x, row in enumerate(reader): for y, tile in enumerate(row): world_data[x][y] = int(tile) world = World() player, health_bar = world.process_data(world_data) run = True while run: clock.tick(FPS) if start_game == False: #draw menu screen.fill(BG) #add Buttons if start_Button.draw(screen): start_game = True start_intro = True if exit_Button.draw(screen): run = False else: #update background draw_bg() #draw world map world.draw() #show player health health_bar.draw(player.health) player.update() player.draw() for enemy in enemy_group: enemy.ai() enemy.update() enemy.draw() #update and draw groups bullet_group.update() grenade_group.update() explosion_group.update() item_box_group.update() decoration_group.update() water_group.update() exit_group.update() bullet_group.draw(screen) grenade_group.draw(screen) explosion_group.draw(screen) item_box_group.draw(screen) decoration_group.draw(screen) water_group.draw(screen) exit_group.draw(screen) #show intro if start_intro == True: if intro_fade.fade(): start_intro = False intro_fade.fade_counter = 0 #update player actions if player.alive: #shoot bullets if player.in_air: player.update_action(2)#2: jump elif moving_left or moving_right: player.update_action(1)#1: run else: player.update_action(0)#0: idle screen_scroll, level_complete = player.move(moving_left, moving_right) bg_scroll -= screen_scroll #check if player has completed the level if level_complete: start_intro = True level += 1 bg_scroll = 0 world_data = reset_level() if level <= MAX_LEVELS: #load in level data and create world with open(f'level{level}_data.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for x, row in enumerate(reader): for y, tile in enumerate(row): world_data[x][y] = int(tile) world = World() player, health_bar = world.process_data(world_data) else: screen_scroll = 0 if death_fade.fade(): if restart_Button.draw(screen): death_fade.fade_counter = 0 start_intro = True bg_scroll = 0 world_data = reset_level() #load in level data and create world with open(f'level{level}_data.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for x, row in enumerate(reader): for y, tile in enumerate(row): world_data[x][y] = int(tile) world = World() player, health_bar = world.process_data(world_data) for event in pygame.event.get(): #quit game if event.type == pygame.QUIT: run = False #keyboard presses if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: moving_left = True if event.key == pygame.K_d: moving_right = True if event.key == pygame.K_SPACE: shoot = True if event.key == pygame.K_q: grenade = True if event.key == pygame.K_w and player.alive: player.jump = True jump_fx.play() if event.key == pygame.K_ESCAPE: run = False #keyboard Button released if event.type == pygame.KEYUP: if event.key == pygame.K_a: moving_left = False if event.key == pygame.K_d: moving_right = False if event.key == pygame.K_SPACE: shoot = False if event.key == pygame.K_q: grenade = False grenade_thrown = False pygame.display.update() pygame.quit()