0% found this document useful (0 votes)
35 views11 pages

The Bull and The Bear

This document is a Python script for a 2D space-themed game using Pygame. It includes classes for the player spaceship, lasers, obstacles, and health packs, along with game mechanics such as scoring, speed adjustments, and health management. The game features a main menu, game loop, and screens for game over and winning scenarios.

Uploaded by

nivesad05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views11 pages

The Bull and The Bear

This document is a Python script for a 2D space-themed game using Pygame. It includes classes for the player spaceship, lasers, obstacles, and health packs, along with game mechanics such as scoring, speed adjustments, and health management. The game features a main menu, game loop, and screens for game over and winning scenarios.

Uploaded by

nivesad05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

import pygame

import random
import sys
import os

# Initialize Pygame
pygame.init()

# Constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
MAX_HP = 100 # Maximum HP
INITIAL_PLAYER_SPEED = 4 # Initial speed for the spaceship
SPEED_INCREMENT = 0.1 # Speed increment per score point
MAX_PLAYER_SPEED = 6 # Maximum speed for the spaceship

INITIAL_OBSTACLE_SPEED = 4 # Initial speed for obstacles


OBSTACLE_SPEED_INCREMENT = 0.03 # Reduced speed increment for obstacles
per score point
MAX_OBSTACLE_SPEED = 10 # Maximum speed for obstacles

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Load images and sounds


def load_image(filename):
if os.path.exists(filename):
return pygame.image.load(filename)
else:
print(f"Warning: {filename} not found.")
return pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT)) # Placeholder

def load_sound(filename):
if os.path.exists(filename):
return pygame.mixer.Sound(filename)
else:
print(f"Warning: {filename} not found.")
return None

# Load background image


background = load_image('Background.jpg')

# Load sounds
collision_sound = load_sound('collision.mp3') # Load collision sound
gun_sound = load_sound('gun_sound.mp3') # Load gun sound for firing
pygame.mixer.music.load('Background_Music.mp3') # Load background music

# Player Class (Spaceship)


class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = load_image('spaceship.png')
self.image = pygame.transform.scale(self.image, (80, 80)) # Increased size
self.rect = self.image.get_rect()
self.rect.center = (100, SCREEN_HEIGHT // 2)
self.hp = MAX_HP # Initialize HP to 100
self.speed = INITIAL_PLAYER_SPEED # Set initial player speed

def update(self):
keys = pygame.key.get_pressed()
if (keys[pygame.K_UP] or keys[pygame.K_w]) and self.rect.top > 0:
self.rect.y -= self.speed
if (keys[pygame.K_DOWN] or keys[pygame.K_s]) and self.rect.bottom <
SCREEN_HEIGHT:
self.rect.y += self.speed

def take_damage(self, damage):


self.hp -= damage
if self.hp <= 0:
self.hp = 0 # Ensure HP doesn't drop below zero

def adjust_speed(self, score):


self.speed = min(INITIAL_PLAYER_SPEED + score * SPEED_INCREMENT,
MAX_PLAYER_SPEED)

def restore_health(self, amount):


self.hp += amount
if self.hp > MAX_HP: # Ensure HP doesn't exceed maximum
self.hp = MAX_HP

# Laser Class
class Laser(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((10, 5))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.center = (x, y)

def update(self):
self.rect.x += 10 # Move laser to the right
if self.rect.x > SCREEN_WIDTH:
self.kill()
# Obstacle Class (Debris)
class Obstacle(pygame.sprite.Sprite):
def __init__(self, speed):
super().__init__()
self.image = load_image('debris.png')
self.image = pygame.transform.scale(self.image, (60, 60)) # Increased size
self.rect = self.image.get_rect()
self.rect.x = SCREEN_WIDTH
self.rect.y = random.randint(0, SCREEN_HEIGHT - self.rect.height)
self.speed = speed

def update(self):
self.rect.x -= self.speed
if self.rect.x < 0:
self.kill()

@classmethod
def get_speed(cls, score):
return min(INITIAL_OBSTACLE_SPEED + score *
OBSTACLE_SPEED_INCREMENT, MAX_OBSTACLE_SPEED)

# Health Pack Class


class HealthPack(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = load_image('health_pack.png')
self.image = pygame.transform.scale(self.image, (40, 40)) # Size of the health
pack
self.rect = self.image.get_rect()
self.rect.x = SCREEN_WIDTH
self.rect.y = random.randint(0, SCREEN_HEIGHT - self.rect.height)
def update(self):
self.rect.x -= 5 # Move health pack to the left
if self.rect.x < 0:
self.kill()

# Game Loop
def game_loop():
global INITIAL_OBSTACLE_SPEED, MAX_OBSTACLE_SPEED
player = Player()
player_group = pygame.sprite.GroupSingle(player)
obstacle_group = pygame.sprite.Group()
laser_group = pygame.sprite.Group()
health_pack_group = pygame.sprite.Group()

spawn_rate = 500 # Spawn every 500 milliseconds


pygame.time.set_timer(pygame.USEREVENT, spawn_rate)
pygame.time.set_timer(pygame.USEREVENT + 1, 10000) # Spawn health pack
every 10 seconds

clock = pygame.time.Clock()
score = 0

damaged = False
shooting_delay = 0 # Track delay for shooting
running = True

pygame.mixer.music.play(-1) # Play background music in a loop

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE: # End game on Esc key press
pygame.quit()
sys.exit()
elif event.type == pygame.USEREVENT:
obstacle_speed = Obstacle.get_speed(score)
obstacle = Obstacle(obstacle_speed)
obstacle_group.add(obstacle)
elif event.type == pygame.USEREVENT + 1: # Spawn health pack
health_pack = HealthPack()
health_pack_group.add(health_pack)

keys = pygame.key.get_pressed()
player_group.update()
obstacle_group.update()
laser_group.update()
health_pack_group.update()

player.adjust_speed(score)

# Laser shooting
if keys[pygame.K_SPACE] and shooting_delay == 0: # If the spacebar is pressed
and no delay
laser = Laser(player.rect.right, player.rect.centery) # Create a laser at the
player's position
laser_group.add(laser)
gun_sound.play() # Play gun sound
shooting_delay = 10 # Set delay (e.g., 10 frames)

if shooting_delay > 0:
shooting_delay -= 1 # Decrease the delay counter

if pygame.sprite.spritecollide(player, obstacle_group, False):


if not damaged:
collision_sound.play() # Play collision sound
player.take_damage(20)
damaged = True
shake_screen()
if player.hp <= 0:
show_final_score_on_white_screen(score) # Show final score when
losing
game_over_screen() # Show the game over screen
return
else:
damaged = False

for laser in laser_group:


hit_obstacles = pygame.sprite.spritecollide(laser, obstacle_group, True)
for hit in hit_obstacles:
laser.kill()
score += 10

if pygame.sprite.spritecollide(player, health_pack_group, True):


player.restore_health(20)

if score >= 500:


show_final_score_on_white_screen(score) # Show final score when winning
win_screen() # Show the win screen
return

draw_game(player_group, obstacle_group, laser_group, health_pack_group,


score)

pygame.display.flip()
clock.tick(FPS)
# Flash screen on game over
def flash_screen():
for _ in range(5):
screen.fill(RED)
pygame.display.flip()
pygame.time.delay(100)
screen.fill(WHITE)
pygame.display.flip()
pygame.time.delay(100)

# Shake the screen on damage


def shake_screen():
for _ in range(5):
screen.fill(RED)
pygame.display.flip()
pygame.time.delay(50)
screen.fill(WHITE)
pygame.display.flip()
pygame.time.delay(50)

# Show final score on a white screen before transitioning


def show_final_score_on_white_screen(score):
screen.fill(WHITE)
font = pygame.font.Font(None, 72)
score_text = f"Final Score: {score}"
text_surface = font.render(score_text, True, BLACK)
text_rect = text_surface.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT //
2))

screen.blit(text_surface, text_rect)
pygame.display.flip()
pygame.time.delay(3000) # Show score for 3 seconds
# Game over screen
def game_over_screen():
game_over_image = load_image('game end.jpg')

while True:
screen.blit(game_over_image, (0, 0))
pygame.display.flip()

for event in pygame.event.get():


if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # Restart the game on spacebar press
return

# Win screen
def win_screen():
win_image = load_image('win.jpg')

while True:
screen.blit(win_image, (0, 0))
pygame.display.flip()

for event in pygame.event.get():


if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # Restart the game on spacebar press
return
# Draw game elements
def draw_game(player_group, obstacle_group, laser_group, health_pack_group,
score):
screen.blit(background, (0, 0))
player_group.draw(screen)
obstacle_group.draw(screen)
laser_group.draw(screen)
health_pack_group.draw(screen)

font = pygame.font.Font(None, 36)


score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (SCREEN_WIDTH - score_text.get_width() - 10, 10))

pygame.draw.rect(screen, RED, (10, 50, MAX_HP, 20)) # Full HP background


pygame.draw.rect(screen, GREEN, (10, 50, player_group.sprite.hp, 20)) # Current
HP
hp_text = font.render(f"HP: {player_group.sprite.hp}", True, WHITE)
screen.blit(hp_text, (10, 20)) # Draw HP label

# Reset speeds
def reset_speeds():
global INITIAL_OBSTACLE_SPEED, MAX_OBSTACLE_SPEED
INITIAL_OBSTACLE_SPEED = 4
MAX_OBSTACLE_SPEED = 10

# Main Menu
def main_menu():
reset_speeds()

start_background = load_image('Front background.jpg')

start_font_size = 40
while True:
screen.blit(start_background, (0, 0))

font_title = pygame.font.Font(None, start_font_size)


title_text = "Cosmic Path to Celestria"
title_surface = font_title.render(title_text, True, WHITE)
screen.blit(title_surface, (SCREEN_WIDTH // 2 - title_surface.get_width() // 2,
SCREEN_HEIGHT // 3))

font_start = pygame.font.Font(None, start_font_size)


start_text = font_start.render("Press ENTER to Start", True, WHITE)
screen.blit(start_text, (SCREEN_WIDTH // 2 - start_text.get_width() // 2,
SCREEN_HEIGHT // 2))

exit_text = font_start.render("Press ESC key to exit", True, WHITE)


screen.blit(exit_text, (SCREEN_WIDTH // 2 - exit_text.get_width() // 2,
SCREEN_HEIGHT // 2 + 60)) # Increased spacing

pygame.display.flip()

for event in pygame.event.get():


if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN: # Start the game on Enter key press
game_loop()

# Main Program
if __name__ == "__main__":
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Cosmic Path to Celestria")
main_menu()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy