Cannon Game In Python

Cannon Game In Python

Introduction

 

In this game, you control a cannon that must be aimed and fired to hit targets scattered across the screen. Utilizing the Pygame library, you’ll adjust the cannon’s angle and power to achieve the perfect shot. 

The game challenges your accuracy and timing as you navigate through varying levels, each with unique obstacles and target placements. With straightforward mechanics and engaging gameplay, this Python cannon game provides both a fun and educational experience, perfect for honing your programming skills while enjoying a dynamic shooting challenge.

Coding a Cannon Program in Python

Coding a cannon program in Python involves creating a simple simulation where you control a cannon to aim and shoot at targets. Using the Pygame library, you set up a graphical window where the cannon is displayed along with targets at various positions. 

The program allows you to adjust the cannon’s angle and power, typically controlled by user inputs such as mouse movements or keyboard presses. By calculating projectile trajectories based on physics principles, you can simulate realistic shooting mechanics.
The core tasks include handling user input, updating the cannon’s aim, and drawing the projectile path, all while providing visual feedback on hits and misses. This project offers a hands-on way to practice game development and physics simulation in Python.

How To Recover your Instagram Password
Learn Python

What You Need To Know

To create a cannon program in Python, you need to understand several key concepts:

  1. Python Basics: Proficiency in Python programming, including variables, control flow, and functions.

  2. Graphics Programming: Familiarity with graphical libraries like Pygame, which is essential for creating the visual elements of the game and handling user input.

  3. Physics Simulation: Understanding the basic principles of projectile motion, including how to calculate trajectories, angles, and velocities to simulate realistic cannon shots.

  4. Event Handling: Knowledge of how to manage user inputs, such as keyboard and mouse actions, to control the cannon’s angle and firing power.

  5. Drawing and Animation: Skills in rendering graphics on the screen, updating positions, and creating animations for the cannon and projectiles.

  6. Game Logic: Ability to implement game mechanics, such as scoring, collision detection, and level progression.

These fundamentals will help you design and build a functional and engaging cannon program, allowing you to effectively manage gameplay, user interaction, and visual representation.

How To Recover your Instagram Password
Cannon Game In Python

Canon Game With Python (Full Code)

import pygame  # Import the pygame module
import sys # Import the sys module for system-specific parameters and functions
import math # Import the math module for mathematical functions
import random # Import the random module for generating random numbers

# Initialize Pygame
pygame.init() # Initialize all imported Pygame modules

# Set up the screen
SCREEN_WIDTH = 800 # Define the width of the screen
SCREEN_HEIGHT = 600 # Define the height of the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Create the game window with the specified dimensions
pygame.display.set_caption("Cannon Game") # Set the title of the game window

# Load images
background_img = pygame.image.load("background.png").convert() # Load the background image
cannon_img = pygame.image.load("cannon.png").convert_alpha() # Load the cannon image with transparency
enemy_img = pygame.image.load("enemy.png").convert_alpha() # Load the enemy image with transparency

# Resize images to fit screen
background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH, SCREEN_HEIGHT)) # Resize the background image
cannon_img = pygame.transform.scale(cannon_img, (50, 30)) # Resize the cannon image
enemy_img = pygame.transform.scale(enemy_img, (20, 20)) # Resize the enemy image

# Cannon attributes
cannon_width = 50 # Define the width of the cannon
cannon_height = 30 # Define the height of the cannon
cannon_x = SCREEN_WIDTH // 2 - cannon_width // 2 # Set the initial x-coordinate of the cannon to center it horizontally
cannon_y = SCREEN_HEIGHT - cannon_height # Set the initial y-coordinate of the cannon to the bottom of the screen
cannon_move_speed = 7 # Set the speed at which the cannon moves horizontally

# Missile attributes
missile_radius = 5 # Define the radius of the missile
missile_speed = 10 # Define the speed of the missile
missiles = [] # Initialize the list to store missile positions

# Enemy attributes
initial_enemy_speed = 2 # Define the initial speed of the enemies
enemy_speed = initial_enemy_speed # Set the current speed of the enemies
enemy_spawn_delay = 1500 # Define the delay between enemy spawns (milliseconds)
base_spawn_delay = enemy_spawn_delay # Store the base spawn delay
last_enemy_spawn = 0 # Store the time when the last enemy was spawned
enemies = [] # Initialize the list to store enemy positions

# Target cannon attributes
target_cannon_width = 50 # Define the width of the target cannon
target_cannon_height = 30 # Define the height of the target cannon
target_cannon_x = SCREEN_WIDTH - 100 # Set the x-coordinate of the target cannon
target_cannon_y = SCREEN_HEIGHT - target_cannon_height # Set the y-coordinate of the target cannon

# Score
score = 0 # Initialize the score variable

# Variables to keep track of pressed keys
pressed_keys = set() # Initialize an empty set to store pressed keys

# Function to draw cannon
def draw_cannon():
screen.blit(cannon_img, (cannon_x, cannon_y)) # Draw the cannon image at its current position

# Function to draw missiles
def draw_missiles():
for missile in missiles: # Iterate over the list of missile positions
pygame.draw.circle(screen, (255, 0, 0), (int(missile[0]), int(missile[1])), missile_radius) # Draw a red circle representing the missile

# Function to draw enemies
def draw_enemies():
for enemy in enemies: # Iterate over the list of enemy positions
screen.blit(enemy_img, (enemy[0], enemy[1])) # Draw the enemy image at its current position

# Function to move cannon
def move_cannon():
global cannon_x # Access the global variable for the cannon's x-coordinate
if pygame.K_LEFT in pressed_keys: # Check if the left arrow key is pressed
cannon_x -= cannon_move_speed # Move the cannon to the left
if cannon_x < 0: # Check if the cannon has reached the left edge of the screen
cannon_x = 0 # Keep the cannon within the left edge
elif pygame.K_RIGHT in pressed_keys: # Check if the right arrow key is pressed
cannon_x += cannon_move_speed # Move the cannon to the right
if cannon_x > SCREEN_WIDTH - cannon_width: # Check if the cannon has reached the right edge of the screen
cannon_x = SCREEN_WIDTH - cannon_width # Keep the cannon within the right edge

# Function to shoot missile
def shoot_missile():
global missiles # Access the global variable for missiles
missile_x = cannon_x + cannon_width // 2 # Calculate the x-coordinate of the missile to shoot from the center of the cannon
missile_y = cannon_y # Set the y-coordinate of the missile to the top of the cannon
missiles.append([missile_x, missile_y]) # Add the new missile position to the list of missiles

# Function to create enemies
def create_enemy():
enemy_x = random.randint(0, SCREEN_WIDTH - enemy_img.get_width()) # Generate a random x-coordinate for the enemy
enemy_y = -enemy_img.get_height() # Set the y-coordinate of the enemy above the top edge of the screen
enemies.append([enemy_x, enemy_y]) # Add the new enemy position to the list of enemies

# Function to draw target cannon
def draw_target_cannon():
pygame.draw.rect(screen, (0, 0, 255), (target_cannon_x, target_cannon_y, target_cannon_width, target_cannon_height)) # Draw a blue rectangle representing the target cannon

# Function to detect missile-target collision
def detect_collision():
global score, enemy_speed, enemy_spawn_delay # Access global variables for score and enemy attributes
for missile in missiles[:]: # Iterate over a copy of the list of missiles
for enemy in enemies[:]: # Iterate over a copy of the list of enemies
if enemy[0] <= missile[0] <= enemy[0] + enemy_img.get_width() and \
enemy[1] <= missile[1] <= enemy[1] + enemy_img.get_height(): # Check if the missile hits an enemy
score += 1 # Increase the score
enemy_speed += 0.1 # Increase the enemy speed
enemy_spawn_delay = int(base_spawn_delay / (1 + score * 0.1)) # Adjust the enemy spawn delay based on the score
enemies.remove(enemy) # Remove the enemy from the list
missiles.remove(missile) # Remove the missile from the list
break # Exit the inner loop

# Main game loop
clock = pygame.time.Clock() # Create a Clock object to control the frame rate

running = True # Set the flag to indicate if the game is running
while running: # Main loop for the game
current_time = pygame.time.get_ticks() # Get the current time in milliseconds

for event in pygame.event.get(): # Iterate over the list of events
if event.type == pygame.QUIT: # Check if the user wants to quit the game
running = False # Set the flag to stop the game
pygame.quit() # Uninitialize all Pygame modules
sys.exit() # Exit the program
elif event.type == pygame.KEYDOWN: # Check if a key is pressed
if event.key == pygame.K_SPACE: # Check if the space key is pressed
shoot_missile() # Call the function to shoot a missile
else: # If any other key is pressed
pressed_keys.add(event.key) # Add the pressed key to the set of pressed keys
elif event.type == pygame.KEYUP: # Check if a key is released
if event.key in pressed_keys: # Check if the released key is in the set of pressed keys
pressed_keys.remove(event.key) # Remove the released key from the set of pressed keys

# Move cannon
move_cannon() # Call the function to move the cannon

# Move missiles
for missile in missiles[:]: # Iterate over a copy of the list of missiles
missile[1] -= missile_speed # Move the missile upward
if missile[1] < 0: # Check if the missile goes off-screen
missiles.remove(missile) # Remove the missile from the list of missiles

# Spawn enemies
if current_time - last_enemy_spawn > enemy_spawn_delay: # Check if it's time to spawn a new enemy
create_enemy() # Call the function to create a new enemy
last_enemy_spawn = current_time # Update the time of the last enemy spawn

# Move enemies
for enemy in enemies[:]: # Iterate over a copy of the list of enemies
enemy[1] += enemy_speed # Move the enemy downward
if enemy[1] > SCREEN_HEIGHT: # Check if the enemy goes off-screen
enemies.remove(enemy) # Remove the enemy from the list of enemies

# Clear the screen
screen.blit(background_img, (0, 0)) # Draw the background image

# Draw cannon
draw_cannon() # Call the function to draw the cannon

# Draw missiles
draw_missiles() # Call the function to draw the missiles

# Draw enemies
draw_enemies() # Call the function to draw the enemies

# Draw target cannon
draw_target_cannon() # Call the function to draw the target cannon

# Detect collisions
detect_collision() # Call the function to detect collisions

# Display score
font = pygame.font.Font(None, 36) # Create a font object
score_text = font.render("Score: " + str(score), True, (255, 255, 255)) # Create a text surface for the score
screen.blit(score_text, (20, 20)) # Draw the score text on the screen

pygame.display.flip() # Update the contents of the entire display
clock.tick(60) # Cap the frame rate at 60 frames per second

Now you can copy paste the following code on Pycharm and run it. The game will be launched and you can begin to play but the goal is not to play the game, it is to create it! So i recommand you to try to fully understand how it works by continuing to read this page and then try to add more implementations from your own perspective. 

Like you can see on the above code, i commented every line of the code so you can have a fully understanding of how things are going on. Later on, i extracted each part of the code and explain the main goals of each function.

How To Recover your Instagram Password

Main Algorithms To Understand

Here’s a comprehensive overview of the main algorithm in the provided cannon game code:

  1. Initialization: The code begins by importing necessary modules and initializing Pygame. It sets up the screen dimensions and creates the game window. Images for the background, cannon, and enemies are loaded and resized to fit the screen.

  2. Attributes Setup: Various attributes are defined, including those for the cannon, missiles, enemies, and target cannon. These attributes include dimensions, positions, and movement speeds.

  3. Drawing Functions: Functions are defined to handle drawing the cannon, missiles, enemies, and the target cannon on the screen. These functions utilize Pygame‘s blit and draw methods to render images and shapes.

  4. Movement and Shooting Functions: Functions to move the cannon and shoot missiles are implemented. The cannon’s horizontal movement is controlled by checking pressed keys, while missiles are added to a list and shot from the cannon’s position.

  5. Enemy Management: Functions for creating and moving enemies are included. Enemies are spawned at random intervals and move downwards. Enemies that go off-screen are removed from the list.

  6. Collision Detection: A function detects collisions between missiles and enemies. When a missile hits an enemy, the score is updated, and the affected missile and enemy are removed from their respective lists.

  7. Main Game Loop: The core of the game runs in a loop that handles events, updates game states, and renders the game. It processes user input, moves the cannon and missiles, spawns and moves enemies, and handles collisions. The screen is cleared and redrawn each frame, and the score is displayed. The frame rate is capped at 60 frames per second to ensure smooth gameplay.

This algorithm outlines a basic but functional cannon game where you can control a cannon, shoot at falling enemies, and track your score. Understanding this code will help you grasp game development fundamentals in Python and Pygame, enabling you to modify and expand the game further.

How To Recover your Instagram Password
Python for beginners

Summary

This Python-based cannon game provides a robust framework for understanding fundamental game development concepts. By utilizing the Pygame library, we’ve created a functional game that features basic mechanics such as cannon movement, missile shooting, enemy spawning, and collision detection. 

The code showcases how to manage game states, handle user inputs, and implement game logic effectively. As you explore and modify the game, you’ll gain valuable insights into game design, graphics handling, and real-time interaction, laying a solid foundation for more complex projects. With this groundwork, you’re equipped to enhance the game further, experiment with new features, and deepen your programming skills.

Post Comment