GPP 5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

T110 Rugved Shetge

Practical No.5

Aim : Create 2D Target Shooting Game

Description :

pygame.init(): Initializes all Pygame modules, essential to start using Pygame


functions.
pygame.display.set_mode((width, height)): Sets up the game window with
specified dimensions.
pygame.image.load(file_path).convert_alpha(): Loads an image with
transparency support, crucial for rendering images with alpha channels.
pygame.transform.scale(image, (width, height)): Resizes images to fit the
required dimensions in the game.
pygame.Rect(x, y, width, height): Creates rectangular objects for positioning
and collision detection.
pygame.event.get(): Retrieves events from the event queue, necessary for
handling user inputs.
pygame.key.get_pressed(): Checks the state of all keyboard keys, used for
character movement.
Rect.colliderect(Rect): Detects collisions between rectangular objects, essential
for game mechanics.
screen.blit(image, (x, y)): Draws images on the screen at specified coordinates,
used to render all visual elements.
pygame.display.flip(): Updates the display to show the latest frame, critical for
rendering the game in real-time.
T110 Rugved Shetge

Game Elements :

Character.jpg Enemy.png Heart.png Bullet.png

Background.jpg
T110 Rugved Shetge

Image/Element Source :

Character : https://www.freepik.com/free-vector/jet-fighter-plane-flying-
illustration_11645877.htm#query=cartoon%20fighter
%20jet&position=1&from_view=keyword&track=ais_hybrid&uuid=bd90c032-
3eae-48cb-824b-da4cef97dae4#position=1&query=cartoon%20fighter%20jet

Enemy : https://www.vecteezy.com/vector-art/6369513-military-fighter-jet-flat-
icon-with-premium-download

Bullet : https://www.shutterstock.com/image-vector/cartoon-game-objects-2d-
art-object-656359261

Heart : https://www.pngwing.com/en/free-png-zrrvr/download

Background : https://www.pxfuel.com/en/desktop-wallpaper-edcjz
T110 Rugved Shetge

Code :
import pygame
import random

# Initialize Pygame
pygame.init()

# Screen setup
width, height = 600, 750
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("T110 Rugved Shetge")

# Load images with raw strings to handle backslashes in file paths


background_img = pygame.image.load(r"C:\Users\rugve\Downloads\
Background.jpg").convert()
character_img = pygame.image.load(r"C:\Users\rugve\Downloads\
Character.jpg").convert_alpha()
enemy_img = pygame.image.load(r"C:\Users\rugve\Downloads\
Enemy.png").convert_alpha()
bullet_img = pygame.image.load(r"C:\Users\rugve\Downloads\Bullet.png").convert_alpha()
heart_img = pygame.image.load(r"C:\Users\rugve\Downloads\Heart.png").convert_alpha()

# Resize background to fit screen


background_img = pygame.transform.scale(background_img, (width, height))

# Resize other images (2.5x original size)


character_size = int(50 * 2.5)
character_img = pygame.transform.scale(character_img, (character_size, character_size))

enemy_radius = int(20 * 2.5)


T110 Rugved Shetge

enemy_img = pygame.transform.scale(enemy_img, (enemy_radius * 2, enemy_radius * 2))

bullet_size = int(10 * 2.5)


bullet_img = pygame.transform.scale(bullet_img, (bullet_size, bullet_size))

heart_size = 30
heart_img = pygame.transform.scale(heart_img, (heart_size, heart_size))

# Character setup with adjusted hitbox


character_speed = 5
character = pygame.Rect(
width // 2 - character_size // 2,
height - character_size - 10,
character_size - 20, # Adjusted hitbox width
character_size - 20 # Adjusted hitbox height
)

# Initialize lists for bullets and enemies


bullets = []
enemies = []

# Initialize score and hearts


score = 0
hearts = 3

# Clock for controlling frame rate


clock = pygame.time.Clock()

def display_message(text, font_size, color, y_offset=0):


T110 Rugved Shetge

"""Display a message in the center of the screen."""


font = pygame.font.Font(None, font_size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect(center=(width // 2, height // 2 + y_offset))
screen.blit(text_surface, text_rect)

def game_over_screen(final_score):
"""Display game over screen with restart and quit buttons."""
screen.fill((0, 0, 0))
display_message("Game Over", 72, (255, 0, 0))
display_message(f"Your Score: {final_score}", 48, (255, 255, 255), 60)
display_message("Press R to Restart", 36, (255, 255, 255), 120)
display_message("Press Q to Quit", 36, (255, 255, 255), 180)
pygame.display.flip()

waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
waiting = False
return True
if event.key == pygame.K_q:
pygame.quit()
return False
clock.tick(60)
T110 Rugved Shetge

def reset_game():
"""Reset the game state."""
global character, bullets, enemies, score, hearts
character = pygame.Rect(
width // 2 - character_size // 2,
height - character_size - 10,
character_size - 20, # Adjusted hitbox width
character_size - 20 # Adjusted hitbox height
)
bullets = []
enemies = []
score = 0
hearts = 3

# Main game loop


running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet = pygame.Rect(character.centerx - bullet_size // 2, character.top, bullet_size,
bullet_size)
bullets.append(bullet)

# Move bullets
for bullet in bullets:
bullet.y -= 10
T110 Rugved Shetge

if bullet.top < 0:
bullets.remove(bullet)

# Spawn enemies
if random.randint(1, 100) <= 2:
enemy_x = random.randint(enemy_radius, width - enemy_radius)
enemy = pygame.Rect(enemy_x - enemy_radius, 0, enemy_radius * 2, enemy_radius *
2)
enemies.append(enemy)

# Move enemies
for enemy in enemies:
enemy.y += 5
if enemy.top > height:
enemies.remove(enemy)

# Move character with A and D keys


keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
character.x -= character_speed
if keys[pygame.K_d]:
character.x += character_speed

# Keep character within screen bounds


if character.left < 0:
character.left = 0
if character.right > width:
character.right = width

# Check for collisions between bullets and enemies


T110 Rugved Shetge

for bullet in bullets:


for enemy in enemies:
if bullet.colliderect(enemy):
score += 1
bullets.remove(bullet)
enemies.remove(enemy)
break

# Check for character collision with enemies (adjusted hit detection)


for enemy in enemies:
if character.colliderect(enemy.inflate(-20, -20)): # Inflate hitbox for more realistic
dodging
enemies.remove(enemy)
hearts -= 1
if hearts <= 0:
running = False

# Draw everything
screen.blit(background_img, (0, 0)) # Draw background

# Draw bullets
for bullet in bullets:
screen.blit(bullet_img, bullet.topleft)

# Draw character
screen.blit(character_img, character.topleft)

# Draw enemies
for enemy in enemies:
screen.blit(enemy_img, enemy.topleft)
T110 Rugved Shetge

# Display score
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score: {score}", True, (255, 0, 0))
screen.blit(score_text, (10, 10))

# Display hearts
for i in range(hearts):
screen.blit(heart_img, (width - (i + 1) * (heart_size + 10), 10))

# Update display
pygame.display.flip()

# Limit frame rate to 60 FPS


clock.tick(60)

# If game over, show restart/quit options


if not running:
if game_over_screen(score):
reset_game()
running = True

# Clean up
pygame.quit()
T110 Rugved Shetge

Output :

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