Top 15 Python Game Project Topics for Beginners, Intermediate, and Advanced Coders
Updated on Mar 18, 2025 | 43 min read | 12.7k views
Share:
For working professionals
For fresh graduates
More
Updated on Mar 18, 2025 | 43 min read | 12.7k views
Share:
The gaming sector has undergone a significant transformation with the emergence of the Python programming language. Python, recognized for its ease of use and clarity, has transformed the landscape for both developers and gamers. Thanks to its vast libraries and frameworks, Python has accelerated game development, making it more efficient and highly scalable.
Although it has not been the primary language for AAA games, it has become popular in indie development, prototyping, and educational games. Python allows developers to efficiently create captivating 2D and 3D games using robust libraries such as Panda3D, Pygame, and Godot.
Let’s investigate the evolution of Python in game development and the analysis of top python game projects topics. Let's delve in!
Below are the top python game projects topics for different levels; Beginners, Intermediate, and Advanced. If you are pursuing a software engineering course these project ideas will come handy.
Brief Intro & Objective: The game creates a random number from 1 to 100, and the player must guess what it is. The program gives input on whether the guessed number is too low or too high until the right number is identified.
Key Concepts & Skills Learned
Libraries Used:
Game Mechanics
Code Breakdown
import random
n = random.randrange(1,100)
guess = int(input("Enter any number: "))
while n!= guess:
if guess < n:
print("Too low")
guess = int(input("Enter number again: "))
elif guess > n:
print("Too high!")
guess = int(input("Enter number again: "))
else:
break
print("you guessed it right!!")
Output:
Estimated Time to complete the project: 1 - 2 Hours
Brief Intro & Objective
ROCK PAPER SCISSORS is a classic game for two players. In every round, participants start by declaring, “rock, paper, scissors, shoot!” Every player raises a fist for the rock, a flat hand for the paper, or their index and middle fingers for scissors on "shoot." The rock smashes the scissors, the scissors slice the paper, and the paper wraps the rock.
Key Concepts & Skills Learned
To comprehend the program provided below, you should possess a fundamental understanding of the following Python concepts:
In this instance, we will utilize the randint() function from the random module. This function will produce a random number within the given range.
Libraries Used
random module
Game Mechanics
Code Breakdown
import random
play = ["Rock", "Paper", "Scissors"]
computer = play[random.randint(0,2)]
player = False
while player == False:
player = input("Rock, Paper, Scissors?")
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
else:
print("You win!", player, "smashes", computer)
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cuts", player)
else:
print("You win!", player, "covers", computer)
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
else:
print("You win!", player, "cuts", computer)
else:
print("That's not a valid play. Check the spelling!")
player = False
computer = play[random.randint(0,2)]
Output:
Estimated Time to complete the project: 1 - 3 Hours
Brief Intro & Objective
Tic Tac Toe is an easy game for two players where they place X and O in a 3×3 grid. The objective is to align three of your symbols in a row, whether horizontally, vertically, or diagonally.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
board = [" " for x in range(9)]
def print_board():
row1 = "| {} | {} | {} |".format(board[0], board[1], board[2])
row2 = "| {} | {} | {} |".format(board[3], board[4], board[5])
row3 = "| {} | {} | {} |".format(board[6], board[7], board[8])
print()
print(row1)
print(row2)
print(row3)
print()
def player_move(icon):
if icon == "X":
number = 1
elif icon == "O":
number = 2
print("Your turn player {}".format(number))
choice = int(input("Enter your move (1-9): ").strip())
if board[choice - 1] == " ":
board[choice - 1] = icon
else:
print()
print("That space is already taken!")
def is_victory(icon):
if (board[0] == icon and board[1] == icon and board[2] == icon) or \
(board[3] == icon and board[4] == icon and board[5] == icon) or \
(board[6] == icon and board[7] == icon and board[8] == icon) or \
(board[0] == icon and board[3] == icon and board[6] == icon) or \
(board[1] == icon and board[4] == icon and board[7] == icon) or \
(board[2] == icon and board[5] == icon and board[8] == icon) or \
(board[0] == icon and board[4] == icon and board[8] == icon) or \
(board[2] == icon and board[4] == icon and board[6] == icon):
return True
else:
return False
def is_draw():
if " " not in board:
return True
else:
return False
while True:
print_board()
player_move("X")
print_board()
if is_victory("X"):
print("X wins! Congratulations!")
break
elif is_draw():
print("It's a draw!")
break
player_move("O")
if is_victory("O"):
print_board()
print("O wins! Congratulations!")
break
elif is_draw():
print("It's a draw!")
break
Output:
Estimated Time to complete the project: 1 - 2 Hours
Brief Intro & Objective
In the hangman game, one participant chooses a word while the other players guess the word one letter at a time. Each time the guessed letter is accurate, the player who chose the word will show where the letter is located.
Key Concepts & Skills Learned
To create the Hangman game using Python, you should apply fundamental Python concepts such as the random module, integers, strings, characters, input and output functions, and Boolean values.
Libraries Used
Game Mechanics
Code Breakdown
import time
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print ("Start guessing...")
time.sleep(0.5)
word = ("secret")
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char,end=""),
else:
print ("_",end=""),
failed += 1
if failed == 0:
print ("You won")
break
guess = input("guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print ("Wrong")
print ("You have", + turns, 'more guesses' )
if turns == 0:
print ("You Lose" )
Output:
Estimated Time to complete the project: 2 - 5 Hours
Brief Intro & Objective
Participants are given a set of questions, and they need to select the right answer from four choices. The game monitors the score, gives instant feedback on the accuracy of every response, and utilizes text-to-speech features to vocalize the questions and choices.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
print("Wellcome to quiz game !!")
print('NOTE: if your spelling is incorrect then it is considered as wrong answer')
score = 0
question_no = 0
playing = input('Do you want to play ? ').lower()
if playing == 'yes':
question_no += 1
ques = input(f'\n{question_no}. what does CPU stand for? ').lower()
if ques == 'central processing unit':
score +=1
print('correct! you got 1 point')
else:
print('Incorrect!')
print(f'current answer is --> central processing unit')
question_no += 1
ques = input(f'\n{question_no}. what does GPU stand for? ').lower()
if ques == 'graphics processing unit':
score +=1
print('correct! you got 1 point')
else:
print('Incorrect!')
print(f'current answer is --> graphics processing unit')
question_no += 1
ques = input(f'\n{question_no}. what does RAM stand for? ').lower()
if ques == 'random access memory':
score +=1
print('correct! you got 1 point')
else:
print('Incorrect!')
print(f'current answer is --> random access memory')
question_no += 1
ques = input(f'\n{question_no}. what does PSU stand for? ').lower()
if ques == 'power supply unit':
score +=1
print('correct! you got 1 point')
else:
print('Incorrect!')
print(f'current answer is --> power supply unit')
question_no += 1
ques = input(f'\n{question_no}. what does ROM stand for? ').lower()
if ques == 'read only memory':
score +=1
print('correct! you got 1 point')
else:
print('Incorrect!')
print(f'current answer is --> read only memory')
else:
print('thankyou you are out of a game.')
quit()
print(f'\nnumber of question is {question_no}')
print(f'your score is {score}')
try:
percentage = (score *100)/question_no
except ZeroDivisionError:
print('0% quetions are correct')
print(f'{percentage}% questions are correct.')
Output:
Estimated Time to complete the project: 1- 3 Hours
Also Read: Free Python Course for Beginners | Free Python Beginners Course
Brief Intro & Objective
A fantastic game that has been increasing in popularity among the public for many generations. The Snake game can be navigated using the four directional buttons based on the way it's moving. The objective of playing the game is to achieve the highest score by collecting food or fruits. The player is unlucky if the snake hits the wall or collides with itself.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
import pygame
import time
import random
snake_speed = 10
width_x = 960
height_y = 720
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 64, 64)
green = pygame.Color(118, 238, 0)
blue = pygame.Color(0, 205, 205)
pygame.init()
pygame.display.set_caption('Snakes Game in Python')
window_snakegame = pygame.display.set_mode((width_x, height_y))
frame_per_sec = pygame.time.Clock()
# Initial snake position
position_snake = [120, 60]
# Initial snake body
body_snake = [
[120, 60],
[110, 60],
[100, 60],
[90, 60],
[80, 60]
]
# Initial food position
position_food = [
random.randrange(1, (width_x // 10)) * 10,
random.randrange(1, (height_y // 10)) * 10
]
spawn_of_food = True
# Initial direction
direction_snake = 'LEFT'
flexible_to_change = direction_snake
score = 0
# Function to display score
def score_metrics(selection, color, font, size):
font_score = pygame.font.SysFont(font, size)
surface_score = font_score.render('The Score earned: ' + str(score), True, color)
rect_score = surface_score.get_rect()
window_snakegame.blit(surface_score, rect_score)
# Function for game over screen
def end_gameover():
font_displayscore = pygame.font.SysFont('Times New Roman', 50)
surface_gameover = font_displayscore.render('The current score for you: ' + str(score), True, red)
rect_gameover = surface_gameover.get_rect()
rect_gameover.midtop = (width_x / 2, height_y / 4)
window_snakegame.blit(surface_gameover, rect_gameover)
pygame.display.flip()
time.sleep(5)
pygame.quit()
quit()
# Main game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction_snake != 'DOWN':
flexible_to_change = 'UP'
if event.key == pygame.K_DOWN and direction_snake != 'UP':
flexible_to_change = 'DOWN'
if event.key == pygame.K_LEFT and direction_snake != 'RIGHT':
flexible_to_change = 'LEFT'
if event.key == pygame.K_RIGHT and direction_snake != 'LEFT':
flexible_to_change = 'RIGHT'
# Updating direction
if flexible_to_change == 'UP':
direction_snake = 'UP'
if flexible_to_change == 'DOWN':
direction_snake = 'DOWN'
if flexible_to_change == 'LEFT':
direction_snake = 'LEFT'
if flexible_to_change == 'RIGHT':
direction_snake = 'RIGHT'
# Moving the snake
if direction_snake == 'UP':
position_snake[1] -= 10
if direction_snake == 'DOWN':
position_snake[1] += 10
if direction_snake == 'LEFT':
position_snake[0] -= 10
if direction_snake == 'RIGHT':
position_snake[0] += 10
# Snake body mechanics
body_snake.insert(0, list(position_snake))
# Check if the snake eats the food
if position_snake[0] == position_food[0] and position_snake[1] == position_food[1]:
score += 10
spawn_of_food = False
else:
body_snake.pop()
if not spawn_of_food:
position_food = [
random.randrange(1, (width_x // 10)) * 10,
random.randrange(1, (height_y // 10)) * 10
]
spawn_of_food = True
window_snakegame.fill(white)
# Draw snake
for position in body_snake:
pygame.draw.rect(window_snakegame, blue, pygame.Rect(position[0], position[1], 10, 10))
# Draw food
pygame.draw.rect(window_snakegame, red, pygame.Rect(position_food[0], position_food[1], 10, 10))
# Collision detection with walls
if position_snake[0] < 0 or position_snake[0] > width_x - 10:
end_gameover()
if position_snake[1] < 0 or position_snake[1] > height_y - 10:
end_gameover()
# Collision detection with itself
for block in body_snake[1:]:
if position_snake[0] == block[0] and position_snake[1] == block[1]:
end_gameover()
# Display score
score_metrics(1, white, 'Times New Roman', 20)
# Update the display
pygame.display.update()
# Control game speed
frame_per_sec.tick(snake_speed)
Output:
Estimated Time to complete the project: 2 - 5 Hours
Brief Intro & Objective
Pong is a well-known computer game that mimics table tennis. In this game, the two participants manage the two paddles located on opposite sides of the game screen. They adjust the paddles higher or lower to strike the moving ball. A player’s score goes up either when they strike the ball or when the rival fails to make the hit.
Key Concepts & Skills Learned
It is recommended that the developer possess prior experience in Python and the Turtle module. Additionally, use the command below to install the Turtle module if it isn't already installed.
Libraries Used
Game Mechanics
Code Breakdown
import turtle
screen = turtle.Screen()
screen.title("DataFlair Pong game")
screen.setup(width=1000 , height=600)
paddle1 = turtle.Turtle()
paddle1.speed(0)
paddle1.shape("square")
paddle1.color("blue")
paddle1.shapesize(stretch_wid=6, stretch_len=2)
paddle1.penup()
paddle1.goto(-400, 0)
paddle2 = turtle.Turtle()
paddle2.speed(0)
paddle2.shape("square")
paddle2.color("red")
paddle2.shapesize(stretch_wid=6, stretch_len=2)
paddle2.penup()
paddle2.goto(400, 0)
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("green")
ball.penup()
ball.goto(0, 0)
ball.dx = 2
ball.dy = -2
player1 = 0
player2 = 0
score = turtle.Turtle()
score.speed(0)
score.penup()
score.hideturtle()
score.goto(0, 260)
score.write("Player1 : 0 Player2: 0", align="center", font=("Courier", 20, "bold"))
def movePad1Up():
y = paddle1.ycor() #Getting the current y-coordinated of the left paddle
y += 15
paddle1.sety(y) #Updating the y-coordinated of the paddle
def movePad1Down():
y = paddle1.ycor()#Getting the current y-coordinated of the left paddle
y -= 15
paddle1.sety(y)#Updating the y-coordinated of the paddle
def movePad2Up():
y = paddle2.ycor()#Getting the current y-coordinated of the right paddle
y += 15
paddle2.sety(y)#Updating the y-coordinated of the paddle
def movePad2Down():
y = paddle2.ycor()#Getting the current y-coordinated of the right paddle
y -= 15
paddle2.sety(y)#Updating the y-coordinated of the paddle
screen.listen()
screen.onkeypress(movePad1Up, "Left")
screen.onkeypress(movePad1Down, "Right")
screen.onkeypress(movePad2Up, "Up")
screen.onkeypress(movePad2Down, "Down")
while True:
screen.update()
ball.setx(ball.xcor()+ball.dx)
ball.sety(ball.ycor()+ball.dy)
if ball.ycor() > 280:
ball.sety(280)
ball.dy *= -1 #Bouncing the ball
if ball.ycor() < -280:
ball.sety(-280)
ball.dy *= -1#Bouncing the ball
if ball.xcor() > 480 or ball.xcor() < -480:
if(ball.xcor() <-480):
player2 += 1 #Increasing the score of right player if left player missed
else:
player1 += 1 #Increasing the score of left player if right player missed
ball.goto(0, 0)
ball.dx *= -1
ball.dy *= -1
score.clear()
score.write("Player1 : {} Player2: {}".format(player1, player2), align="center", font=("Courier", 20, "bold"))
if (ball.xcor() < -360 and ball.xcor() > -370) and (paddle1.ycor() + 50 > ball.ycor() > paddle1.ycor() - 50):
player1 += 1
score.clear()
score.write("Player A: {} Player B: {}".format(player1, player2), align="center", font=("Courier", 20, "bold"))
ball.setx(-360)
if(ball.dy>0 and ball.dy<5): #If dy is positive increasing dy
ball.dy+=0.5
elif(ball.dy<0 and ball.dy>-5): #else if dy is negative decreasing dy
ball.dy-=0.5
if(ball.dx>0 and ball.dx<5):#If dx is positive increasing dx
ball.dx+=0.5
elif(ball.dx<0 and ball.dx>-5): #else if dx is negative decreasing dx
ball.dx-=0.5
ball.dx *=-1
if (ball.xcor() > 360 and ball.xcor() < 370) and (paddle2.ycor() + 50 > ball.ycor() > paddle2.ycor() - 50):
player2 += 1
score.clear()
score.write("Player A: {} Player B: {}".format(player1, player2), align="center", font=("Courier", 20, "bold"))
ball.setx(360)
if(ball.dy>0 and ball.dy<7):#If dy is positive increasing dy
ball.dy+=1
elif(ball.dy<0 and ball.dy>-7):#else if dy is negative decreasing dy
ball.dy-=1
if(ball.dx>0 and ball.dx<7):#If dx is positive increasing dx
ball.dx+=1
elif(ball.dx<0 and ball.dx>-7): #else if dx is negative decreasing dx
ball.dx-=1
ball.dx*=-1
Output:
Estimated Time to complete the project: 1 - 2 Hrs
Brief Intro & Objective
The Space Invader Game is a simple 2D game created with a popular framework for Python called Pygame. The game features a player maneuvering a spaceship, who shoots at opposing spaceships while simultaneously dodging the projectiles aimed at him/her by those enemy ships. Challenges in this game are effectively designed to escalate following the score, featuring heightened speeds and firing rates of adversaries.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
import math
import random
import pygame
from pygame import mixer
pygame.init()
display_width, display_height = 800, 600
display = pygame.display.set_mode((display_width, display_height))
space_bg = pygame.image.load(r"")
mixer.music.load(r"")
mixer.music.play(-1)
pygame.display.set_caption("Space Guardian")
game_icon = pygame.image.load(r"")
pygame.display.set_icon(game_icon)
text_font = pygame.font.Font('freesansbold.ttf', 32)
header_font = pygame.font.Font('freesansbold.ttf', 64)
hero_image = pygame.image.load(r"")
hero_x = 370
hero_y = 500
hero_x_change = 0
hero_y_change = 0
enemy_sprites = []
enemy_x_pos = []
enemy_y_pos = []
enemy_x_change = []
enemy_y_change = []
number_of_enemies = 5
base_enemy_velocity = 0.4
i = 0
while i < number_of_enemies:
enemy_sprites.append(pygame.image.load(r""))
enemy_x_pos.append(random.randint(0, 736))
enemy_y_pos.append(random.randint(50, 150))
enemy_x_change.append(base_enemy_velocity)
enemy_y_change.append(20)
i += 1
bullet_sprite = pygame.image.load(r"")
bullet_x = 0
bullet_y = 500
bullet_x_change = 0
bullet_y_change = 10
bullet_state = "ready"
enemy_bullet_sprite = []
enemy_bullet_x = []
enemy_bullet_y = []
enemy_bullet_y_change = []
enemy_bullet_state = []
j = 0
while j < number_of_enemies:
enemy_bullet_sprite.append(pygame.image.load(r"C:\Users\souvi\OneDrive\Desktop\koko\Space-Invaders-Pygame\laser_bullet.png"))
enemy_bullet_x.append(0)
enemy_bullet_y.append(enemy_y_pos[j])
enemy_bullet_y_change.append(2)
enemy_bullet_state.append("ready")
j += 1
score = 0
game_level = 1
text_x = 10
text_y = 10
game_over_font = pygame.font.Font('freesansbold.ttf', 64)
def start_menu():
display.fill((0, 0, 0))
title_text = header_font.render("Space Guardian", True, (255, 255, 255))
display.blit(title_text, (200, 200))
instructions = text_font.render("Press ENTER to Start", True, (255, 255, 255))
display.blit(instructions, (250, 300))
pygame.display.update()
start = False
while not start:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
start = True
def display_score(x, y):
score_text = text_font.render("Score: " + str(score), True, (255, 255, 255))
display.blit(score_text, (x, y))
def display_level(x, y):
level_text = text_font.render("Level: " + str(game_level), True, (255, 255, 255))
display.blit(level_text, (x, y + 40))
def game_over():
over_text = game_over_font.render("GAME OVER", True, (255, 255, 255))
display.blit(over_text, (200, 250))
def player(x, y):
display.blit(hero_image, (x, y))
def enemy(x, y, index):
display.blit(enemy_sprites[index], (x, y))
def fire_hero_bullet(x, y):
global bullet_state
bullet_state = "fire"
display.blit(bullet_sprite, (x + 16, y + 10))
def fire_enemy_bullet(x, y, index):
global enemy_bullet_state
enemy_bullet_state[index] = "fire"
display.blit(enemy_bullet_sprite[index], (x + 16, y + 10))
def collision_detected(enemy_x, enemy_y, bullet_x, bullet_y):
distance = math.sqrt(math.pow(enemy_x - bullet_x, 2) + (math.pow(enemy_y - bullet_y, 2)))
return distance < 27
def player_hit(player_x, player_y, bullet_x, bullet_y):
distance = math.sqrt(math.pow(player_x - bullet_x, 2) + (math.pow(player_y - bullet_y, 2)))
return distance < 30
def game_loop():
global bullet_x, bullet_y, bullet_state, score, game_level
global hero_x, hero_y, hero_x_change, hero_y_change
global enemy_x_pos, enemy_y_pos, enemy_x_change, enemy_y_change
global enemy_bullet_x, enemy_bullet_y, enemy_bullet_state, enemy_bullet_y_change
try:
hero_x = 368 # Example starting position
hero_y = 480 # Example starting position
hero_x_change = 0
hero_y_change = 0
bullet_x = 0
bullet_y = 500
bullet_state = "ready"
score = 0
game_level = 1
number_of_enemies = 5
enemy_x_pos = [random.randint(0, 736) for _ in range(number_of_enemies)]
enemy_y_pos = [random.randint(50, 150) for _ in range(number_of_enemies)]
enemy_x_change = [base_enemy_velocity for _ in range(number_of_enemies)]
enemy_y_change = [40 for _ in range(number_of_enemies)]
enemy_bullet_x = [0 for _ in range(number_of_enemies)]
enemy_bullet_y = [0 for _ in range(number_of_enemies)]
enemy_bullet_state = ["ready" for _ in range(number_of_enemies)]
enemy_bullet_y_change = [10 for _ in range(number_of_enemies)]
running = True
start_menu() # Call start menu
while running:
display.fill((0, 0, 0))
display.blit(space_bg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
hero_x_change = -5
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
hero_x_change = 5
if event.key == pygame.K_w or event.key == pygame.K_UP:
hero_y_change = -5
if event.key == pygame.K_s or event.key == pygame.K_DOWN:
hero_y_change = 5
if event.key == pygame.K_SPACE and bullet_state == "ready":
bullet_sound = mixer.Sound(r"C:\Users\souvi\OneDrive\Desktop\koko\Space-Invaders-Pygame\laser_sound.wav")
bullet_sound.play()
bullet_x = hero_x
bullet_y = hero_y # Initialize bullet_y when firing
bullet_state = "fire"
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
hero_x_change = 0
if event.key == pygame.K_w or event.key == pygame.K_s:
hero_y_change = 0
hero_x += hero_x_change
hero_y += hero_y_change
if hero_x <= 0:
hero_x = 0
elif hero_x >= 736:
hero_x = 736
if hero_y <= 0:
hero_y = 0
elif hero_y >= 536:
hero_y = 536
e = 0
while e < number_of_enemies:
if enemy_y_pos[e] > 440 or player_hit(hero_x, hero_y, enemy_bullet_x[e], enemy_bullet_y[e]):
for j in range(number_of_enemies):
enemy_y_pos[j] = 2000
game_over()
break
enemy_x_pos[e] += enemy_x_change[e]
if enemy_x_pos[e] <= 0:
enemy_x_change[e] = base_enemy_velocity + (game_level - 1) / 4
enemy_y_pos[e] += enemy_y_change[e]
elif enemy_x_pos[e] >= 736:
enemy_x_change[e] = -(base_enemy_velocity + (game_level - 1) / 4)
enemy_y_pos[e] += enemy_y_change[e]
if enemy_bullet_state[e] == "ready" and random.random() < 0.008:
enemy_bullet_x[e] = enemy_x_pos[e]
fire_enemy_bullet(enemy_bullet_x[e], enemy_bullet_y[e], e)
if enemy_bullet_state[e] == "fire":
fire_enemy_bullet(enemy_bullet_x[e], enemy_bullet_y[e], e)
enemy_bullet_y[e] += enemy_bullet_y_change[e]
if enemy_bullet_y[e] >= 600:
enemy_bullet_y[e] = enemy_y_pos[e]
enemy_bullet_state[e] = "ready"
if bullet_state == "fire":
collision = collision_detected(enemy_x_pos[e], enemy_y_pos[e], bullet_x, bullet_y)
if collision:
explosion_sound = mixer.Sound(r"C:\Users\souvi\OneDrive\Desktop\koko\Space-Invaders-Pygame\explosion.wav")
explosion_sound.play()
bullet_y = 500
bullet_state = "ready"
score += 1
enemy_x_pos[e] = random.randint(0, 736)
enemy_y_pos[e] = random.randint(50, 150)
enemy(enemy_x_pos[e], enemy_y_pos[e], e)
e += 1
if bullet_state == "fire":
fire_hero_bullet(bullet_x, bullet_y)
bullet_y -= bullet_y_change
if bullet_y <= 0:
bullet_y = 500
bullet_state = "ready"
display_score(text_x, text_y)
display_level(text_x, text_y)
player(hero_x, hero_y)
pygame.display.update()
except Exception as e:
print(f"An error occurred: {e}")
finally:
pygame.quit()
if __name__ == "__main__":
game_loop()
Output:
Estimated Time to complete the project: 2 - 3 Hours
Brief Intro & Objective
Flappy Bird is an infinite game featuring a bird guided by the player. The goal of this game is to stop the bird from hitting the ground or crashing into obstacles such as pipes. Each time the bird goes through the pipes, the scores increase by one. The game concludes when the bird hits the pipes or plummets to the ground from gravity.
Key Concepts & Skills Learned
In this endeavor, you will gain knowledge about:
Libraries Used
Game Mechanics
Code Breakdown
import pygame
import sys
import time
import random
pygame.init()
clock = pygame.time.Clock()
def draw_floor():
screen.blit(floor_img, (floor_x, 520))
screen.blit(floor_img, (floor_x + 448, 520))
def create_pipes():
pipe_y = random.choice(pipe_height)
top_pipe = pipe_img.get_rect(midbottom=(467, pipe_y - 300))
bottom_pipe = pipe_img.get_rect(midtop=(467, pipe_y))
return top_pipe, bottom_pipe
def pipe_animation():
global game_over, score_time
for pipe in pipes:
if pipe.top < 0:
flipped_pipe = pygame.transform.flip(pipe_img, False, True)
screen.blit(flipped_pipe, pipe)
else:
screen.blit(pipe_img, pipe)
pipe.centerx -= 3
if pipe.right < 0:
pipes.remove(pipe)
if bird_rect.colliderect(pipe):
game_over = True
def draw_score(game_state):
if game_state == "game_on":
score_text = score_font.render(str(score), True, (255, 255, 255))
score_rect = score_text.get_rect(center=(width // 2, 66))
screen.blit(score_text, score_rect)
elif game_state == "game_over":
score_text = score_font.render(f" Score: {score}", True, (255, 255, 255))
score_rect = score_text.get_rect(center=(width // 2, 66))
screen.blit(score_text, score_rect)
high_score_text = score_font.render(f"High Score: {high_score}", True, (255, 255, 255))
high_score_rect = high_score_text.get_rect(center=(width // 2, 506))
screen.blit(high_score_text, high_score_rect)
def score_update():
global score, score_time, high_score
if pipes:
for pipe in pipes:
if 65 < pipe.centerx < 69 and score_time:
score += 1
score_time = False
if pipe.left <= 0:
score_time = True
if score > high_score:
high_score = score
width, height = 350, 622
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Flappy Bird")
back_img = pygame.image.load("img_46.png")
floor_img = pygame.image.load("img_50.png")
floor_x = 0
bird_up = pygame.image.load("img_47.png")
bird_down = pygame.image.load("img_48.png")
bird_mid = pygame.image.load("img_49.png")
birds = [bird_up, bird_mid, bird_down]
bird_index = 0
bird_flap = pygame.USEREVENT
pygame.time.set_timer(bird_flap, 200)
bird_img = birds[bird_index]
bird_rect = bird_img.get_rect(center=(67, 622 // 2))
bird_movement = 0
gravity = 0.17
pipe_img = pygame.image.load("greenpipe.png")
pipe_height = [400, 350, 533, 490]
pipes = []
create_pipe = pygame.USEREVENT + 1
pygame.time.set_timer(create_pipe, 1200)
game_over = False
over_img = pygame.image.load("img_45.png").convert_alpha ()
over_rect = over_img.get_rect(center=(width // 2, height // 2))
score = 0
high_score = 0
score_time = True
score_font = pygame.font.Font("freesansbold.ttf", 27)
running = True
while running:
clock.tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT: # QUIT event
running = False
sys.exit()
if event.type == pygame.KEYDOWN: # Key pressed event
if event.key == pygame.K_SPACE and not game_over: # If space key is pressed
bird_movement = 0
bird_movement = -7
if event.key == pygame.K_SPACE and game_over:
game_over = False
pipes = []
bird_movement = 0
bird_rect = bird_img.get_rect(center=(67, 622 // 2))
score_time = True
score = 0
if event.type == bird_flap:
bird_index += 1
if bird_index > 2:
bird_index = 0
bird_img = birds[bird_index]
bird_rect = bird_up.get_rect(center=bird_rect.center)
if event.type == create_pipe:
pipes.extend(create_pipes())
screen.blit(floor_img, (floor_x, 550))
screen.blit(back_img, (0, 0))
if not game_over:
bird_movement += gravity
bird_rect.centery += bird_movement
rotated_bird = pygame.transform.rotozoom(bird_img, bird_movement * -6, 1)
if bird_rect.top < 5 or bird_rect.bottom >= 550:
game_over = True
screen.blit(rotated_bird, bird_rect)
pipe_animation()
score_update()
draw_score("game_on")
elif game_over:
screen.blit(over_img, over_rect)
draw_score("game_over")
floor_x -= 1
if floor_x < -448:
floor_x = 0
draw_floor()
pygame.display.update()
pygame.quit()
sys.exit()
Output:
Estimated Time to complete the project: 1 - 2 Hours
Brief Intro & Objective
Memory Puzzle Game is the top-rated memory game or mental workout. The player taps on the tile to uncover it, and when two matching tiles are uncovered, the effect rises and the score goes up. To finish the game, the player needs to uncover all matching pairs of shapes. Once the game concludes, the total moves required to finish the game are shown on the screen.
Key Concepts & Skills Learned
This project demands a solid understanding of Python and the Pygame library. The Pygame module features a graphics library utilized in various programming languages to create the Graphical User Interface, known as GUI.
Libraries Used
Game Mechanics
Also Read: What are Lists in Python?
Code Breakdown
import random
import pygame
import sys
from pygame.locals import *
def main():
global Frame_Speed_Clock, DIS_PlaySurf
pygame.init()
Frame_Speed_Clock = pygame.time.Clock()
DIS_PlaySurf = pygame.display.set_mode((Window_Width, Window_Height))
X_mouse = 0
Y_mouse = 0
pygame.display.set_caption('Memory Game by PythonGeeks')
Board = Randomized_Board()
Boxes_revealed = GenerateData_RevealedBoxes(False)
first_Selection = None
DIS_PlaySurf.fill(BackGround_color)
Start_Game(Board)
while True:
mouse_Clicked = False
DIS_PlaySurf.fill(BackGround_color)
Draw_Board(Board, Boxes_revealed)
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
X_mouse, Y_mouse = event.pos
elif event.type == MOUSEBUTTONUP:
X_mouse, Y_mouse = event.pos
mouse_Clicked = True
x_box, y_box = Box_Pixel(X_mouse, Y_mouse)
if x_box != None and y_box != None:
if not Boxes_revealed[x_box][y_box]:
Draw_HighlightBox(x_box, y_box)
if not Boxes_revealed[x_box][y_box] and mouse_Clicked:
Reveal_Boxes_Animation(Board, [(x_box, y_box)])
Boxes_revealed[x_box][y_box] = True
if first_Selection == None:
first_Selection = (x_box, y_box)
else:
icon1shape, icon1color = get_Shape_Color(Board, first_Selection[0], first_Selection[1])
icon2shape, icon2color = get_Shape_Color(Board, x_box, y_box)
if icon1shape != icon2shape or icon1color != icon2color:
pygame.time.wait(1000)
Cover_Boxes_Animation(Board, [(first_Selection[0], first_Selection[1]), (x_box, y_box)])
Boxes_revealed[first_Selection[0]][first_Selection[1]] = False
Boxes_revealed[x_box][y_box] = False
elif Won(Boxes_revealed):
Game_Won(Board)
pygame.time.wait(2000)
Board = Randomized_Board()
Boxes_revealed = GenerateData_RevealedBoxes(False)
Draw_Board(Board, Boxes_revealed)
pygame.display.update()
pygame.time.wait(1000)
Start_Game (Board)
first_Selection = None
pygame.display.update()
Frame_Speed_Clock.tick(Frame_Speed)
def GenerateData_RevealedBoxes(val):
Boxes_revealed = []
for i in range(Border_Width):
Boxes_revealed.append([val] * Border_Height)
return Boxes_revealed
def Randomized_Board():
icon = []
for color in All_Colors:
for shape in All_Shapes:
icon.append( (shape, color) )
random.shuffle(icon)
num_IconsUsed = int(Border_Width * Border_Height / 2)
icon = icon[:num_IconsUsed] * 2
random.shuffle(icon)
board = []
for x in range(Border_Width):
column = []
for y in range(Border_Height):
column.append(icon[0])
del icon[0]
board.append(column)
return board
def Split_Groups(group_Size, List):
result = []
for i in range(0, len(List), group_Size):
result.append(List[i:i + group_Size])
return result
def leftTop_Coord(x_box, y_box):
left = x_box * (Box_Size + Gap_Size) + X_margin
top = y_box * (Box_Size + Gap_Size) + Y_margin
return (left, top)
def Box_Pixel(x, y):
for x_box in range(Border_Width):
for y_box in range(Border_Height):
left, top = leftTop_Coord(x_box, y_box)
box_Rect = pygame.Rect(left, top, Box_Size, Box_Size)
if box_Rect.collidepoint(x, y):
return (x_box, y_box)
return (None, None)
def Draw_Icon(shape, color, x_box, y_box):
quarter = int(Box_Size * 0.25)
half = int(Box_Size * 0.5)
left, top = leftTop_Coord(x_box, y_box)
if shape == CIRCLE:
pygame.draw.circle(DIS_PlaySurf, color, (left + half, top + half), half - 5)
pygame.draw.circle(DIS_PlaySurf, BackGround_color, (left + half, top + half), quarter - 5)
elif shape == SQUARE:
pygame.draw.rect(DIS_PlaySurf, color, (left + quarter, top + quarter, Box_Size - half, Box_Size - half))
elif shape == DIAMOND:
pygame.draw.polygon(DIS_PlaySurf, color, ((left + half, top), (left + Box_Size - 1, top + half), (left + half, top + Box_Size - 1), (left, top + half)))
elif shape == LINES:
for i in range(0, Box_Size, 4):
pygame.draw.line(DIS_PlaySurf, color, (left, top + i), (left + i, top))
pygame.draw.line(DIS_PlaySurf, color, (left + i, top + Box_Size - 1), (left + Box_Size - 1, top + i))
elif shape == OVAL:
pygame.draw.ellipse(DIS_PlaySurf, color, (left, top + quarter, Box_Size, half))
def get_Shape_Color(board, x_box, y_box):
return board[x_box][y_box][0], board[x_box][y_box][1]
def Box_Cover(board, boxes, coverage):
for box in boxes:
left, top = leftTop_Coord(box[0], box[1])
pygame.draw.rect(DIS_PlaySurf, BackGround_color, (left, top, Box_Size, Box_Size))
shape, color = get_Shape_Color(board, box[0], box[1])
Draw_Icon(shape, color, box[0], box[1])
if coverage > 0: # only draw the cover if there is an coverage
pygame.draw.rect(DIS_PlaySurf, Box_Color, (left, top, coverage, Box_Size))
pygame.display.update()
Frame_Speed_Clock.tick(Frame_Speed)
def Reveal_Boxes_Animation(board, boxesToReveal):
for coverage in range(Box_Size, (-Speed_Reveal) - 1, -Speed_Reveal):
Box_Cover(board, boxesToReveal, coverage)
def Cover_Boxes_Animation(board, boxesToCover):
for coverage in range(0, Box_Size + Speed_Reveal, Speed_Reveal):
Box_Cover(board, boxesToCover, coverage)
def Draw_Board(board, revealed):
for x_box in range(Border_Width):
for y_box in range(Border_Height):
left, top = leftTop_Coord(x_box, y_box)
if not revealed[x_box][y_box]: pygame.draw.rect(DIS_PlaySurf, Box_Color, (left, top, Box_Size, Box_Size))
else:
shape, color = get_Shape_Color(board, x_box, y_box)
Draw_Icon(shape, color, x_box, y_box)
def Draw_HighlightBox(x_box, y_box):
left, top = leftTop_Coord(x_box, y_box)
pygame.draw.rect(DIS_PlaySurf, HighLight_Color, (left - 5, top - 5, Box_Size + 10, Box_Size + 10), 4)
def Start_Game(board):
covered_Boxes = GenerateData_RevealedBoxes(False)
boxes = []
for x in range(Border_Width):
for y in range(Border_Height):
boxes.append( (x, y) )
random.shuffle(boxes)
box_Groups = Split_Groups(8, boxes)
Draw_Board(board, covered_Boxes)
for boxGroup in box_Groups:
Reveal_Boxes_Animation(board, boxGroup)
Cover_Boxes_Animation(board, boxGroup)
def Game_Won (board):
coveredBoxes = GenerateData_RevealedBoxes(True)
color_1 = Light_BackGround_color
color_2 = BackGround_color
for i in range(13):
color_1, color_2 = color_2, color_1
DIS_PlaySurf.fill(color_1)
Draw_Board(board, coveredBoxes)
pygame.display.update()
pygame.time.wait(300)
def Won(Boxes_revealed):
for i in Boxes_revealed:
if False in i:
return False
return True
Frame_Speed = 30
Window_Width = 640
Window_Height = 480
Speed_Reveal = 8
Box_Size = 40
Gap_Size = 10
Border_Width = 10
Border_Height = 7
assert (Border_Width * Border_Height) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches.'
X_margin = int((Window_Width - (Border_Width * (Box_Size + Gap_Size))) / 2)
Y_margin = int((Window_Height - (Border_Height * (Box_Size + Gap_Size))) / 2)
Gray = (100, 100, 100)
Navyblue = ( 60, 60, 100)
White = (255, 255, 255)
Red = (255, 0, 0)
Green = ( 0, 255, 0)
Blue = ( 0, 0, 255)
Yellow = (255, 255, 0)
Orange = (255, 128, 0)
Purple = (255, 0, 255)
Cyan = ( 0, 255, 255)
BackGround_color = Gray
Light_BackGround_color = Navyblue
Box_Color = Cyan
HighLight_Color = Yellow
CIRCLE = 'circle'
SQUARE = 'square'
DIAMOND = 'diamond'
LINES = 'lines'
OVAL = 'oval'
All_Colors = (Red, Green, Blue, Yellow, Orange, Purple, Cyan)
All_Shapes = (CIRCLE, SQUARE, DIAMOND, LINES, OVAL)
assert len(All_Colors)* len(All_Shapes) * 2 >= Border_Width * Border_Height, "Board is too big for the number of shapes/colors defined.”
if __name__ == '__main__':
main()
Output:
Estimated Time to complete the project: 4 - 10 Hours
Brief Intro & Objective
The platformer game is the most cherished genre of video games, tracing back to classics; this 2D action game tests players to run, leap, and fight foes through side-scrolling stages. Conversely, contemporary platformers feature lifelike physics and stunning 3D visuals.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
import pygame
pygame.init()
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption(‘Pixel Platformer‘)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((147, 210, 220))
pygame.display.update()
pygame.quit()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.sprite_sheet = pygame.image.load(‘player.png‘).convert()
self.image = self.get_image(0, 0)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def get_image(self, x, y):
image = pygame.Surface([32, 32])
image.blit(self.sprite_sheet, (0, 0), (x, y, 32, 32))
image.set_colorkey((0, 0, 0)) # Transparent black background
return image
def update(self):
pass
player = Player(100, 300)
all_sprites = pygame.sprite.Group(player)
running = True
while running:
all_sprites.update()
screen.fill((147, 210, 220))
all_sprites.draw(screen)
pygame.display.update()
GRAVITY = 1
PLAYER_SPEED = 5
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
self.vel_x = 0
self.vel_y = 0
self.on_ground = False
def update(self):
self.vel_y += GRAVITY
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.vel_x = -PLAYER_SPEED
elif keys[pygame.K_RIGHT]:
self.vel_x = PLAYER_SPEED
else:
self.vel_x = 0
if keys[pygame.K_UP] and self.on_ground:
self.vel_y = -20
self.rect.x += self.vel_x
self.rect.y += self.vel_y
if self.rect.top > WINDOW_HEIGHT:
self.kill()
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
all_sprites = pygame.sprite.Group()
platforms = pygame.sprite.Group()
p1 = Platform(300, 550, 200, 60)
p2 = Platform(80, 400, 100, 30)
p3 = Platform(500, 300, 150, 30)
all_sprites.add(p1, p2, p3)
platforms.add(p1, p2, p3)
def update(self):
hits = pygame.sprite.spritecollide(self, platforms, False)
if hits:
self.on_ground = True
self.vel_y = 0
self.rect.bottom = hits[0].rect.top
else:
self.on_ground = False
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > WINDOW_WIDTH:
self.rect.right = WINDOW_WIDTH
class Spike(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.image.load(‘spike.png‘).convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
spikes = pygame.sprite.Group()
s1 = Spike(350, 530)
s2 = Spike(100, 380)
all_sprites.add(s1, s2)
spikes.add(s1, s2)
spike_hits = pygame.sprite.spritecollide(player, spikes, False)
if spike_hits:
player.kill()
running = False
class Goal(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.image.load(‘goal.png‘)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
goal = Goal(700, 510)
all_sprites.add(goal)
goal_hit = pygame.sprite.collide_rect(player, goal)
if goal_hit:
level_complete = True
running = False
font = pygame.font.SysFont(None, 48)
win_text = font.render("Level Complete!", True, (255, 255, 255))
lose_text = font.render("Game Over!", True, (255, 255, 255))
if level_complete:
screen.blit(win_text, (WINDOW_WIDTH//2 - win_text.get_width()//2,
WINDOW_HEIGHT//2 - win_text.get_height()//2))
else:
screen.blit(lose_text, (WINDOW_WIDTH//2 - lose_text.get_width()//2,
WINDOW_HEIGHT//2 - lose_text.get_height()//2))
pygame.display.update()
pygame.time.wait(3000)
Output:
upGrad’s Exclusive Data Science Webinar for you –
Transformation & Opportunities in An
Estimated Time to complete the project: 15 - 20 Days
Brief Intro & Objective
A game in which your primary goal is to rival others. Simply click on a tile to position your piece. The system is designed to create a contest among your friends or siblings.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
#Game.py
import pygame, sys
from pygame.locals import *
import pickle
import select
import socket
WIDTH = 400
HEIGHT = 400
BUFFERSIZE = 2048
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Game')
clock = pygame.time.Clock()
sprite1 = pygame.image.load('images/BlueThing/BlueThing_front.png')
sprite2 = pygame.image.load('images/Ladette/Ladette_front.png')
sprite3 = pygame.image.load('images/TrashPanda/TrashPanda_front.png')
sprite4 = pygame.image.load('images/Tubby/Tubby_front.png')
serverAddr = '127.0.0.1'
if len(sys.argv) == 2:
serverAddr = sys.argv[1]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((serverAddr, 4321))
playerid = 0
sprites = { 0: sprite1, 1: sprite2, 2: sprite3, 3: sprite4 }
class Minion:
def __init__(self, x, y, id):
self.x = x
self.y = y
self.vx = 0
self.vy = 0
self.id = id
def update(self):
self.x += self.vx
self.y += self.vy
if self.x > WIDTH - 50:
self.x = WIDTH - 50
if self.x < 0:
self.x = 0
if self.y > HEIGHT - 50:
self.y = HEIGHT - 50
if self.y < 0:
self.y = 0
if self.id == 0:
self.id = playerid
def render(self):
screen.blit(sprites[self.id % 4], (self.x, self.y))
#game events
#['event type', param1, param2]
#
#event types:
# id update
# ['id update', id]
#
# player locations
# ['player locations', [id, x, y], [id, x, y] ...]
#user commands
# position update
# ['position update', id, x, y]
class GameEvent:
def __init__(self, vx, vy):
self.vx = vx
self.vy = vy
cc = Minion(50, 50, 0)
minions = []
while True:
ins, outs, ex = select.select([s], [], [], 0)
for inm in ins:
gameEvent = pickle.loads(inm.recv(BUFFERSIZE))
if gameEvent[0] == 'id update':
playerid = gameEvent[1]
print(playerid)
if gameEvent[0] == 'player locations':
gameEvent.pop(0)
minions = []
for minion in gameEvent:
if minion[0] != playerid:
minions.append(Minion(minion[1], minion[2], minion[0]))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT: cc.vx = -10
if event.key == K_RIGHT: cc.vx = 10
if event.key == K_UP: cc.vy = -10
if event.key == K_DOWN: cc.vy = 10
if event.type == KEYUP:
if event.key == K_LEFT and cc.vx == -10: cc.vx = 0
if event.key == K_RIGHT and cc.vx == 10: cc.vx = 0
if event.key == K_UP and cc.vy == -10: cc.vy = 0
if event.key == K_DOWN and cc.vy == 10: cc.vy = 0
clock.tick(60)
screen.fill((255,255,255))
cc.update()
for m in minions:
m.render()
cc.render()
pygame.display.flip()
ge = ['position update', playerid, cc.x, cc.y]
s.send(pickle.dumps(ge))
s.close()
# Server.py
import socket
import asyncore
import select
import random
import pickle
import time
BUFFERSIZE = 512
outgoing = []
class Minion:
def __init__(self, ownerid):
self.x = 50
self.y = 50
self.ownerid = ownerid
minionmap = {}
def updateWorld(message):
arr = pickle.loads(message)
print(str(arr))
playerid = arr[1]
x = arr[2]
y = arr[3]
if playerid == 0: return
minionmap[playerid].x = x
minionmap[playerid].y = y
remove = []
for i in outgoing:
update = ['player locations']
for key, value in minionmap.items():
update.append([value.ownerid, value.x, value.y])
try:
i.send(pickle.dumps(update))
except Exception:
remove.append(i)
continue
print ('sent update data')
for r in remove:
outgoing.remove(r)
class MainServer(asyncore.dispatcher):
def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(('', port))
self.listen(10)
def handle_accept(self):
conn, addr = self.accept()
print ('Connection address:' + addr[0] + " " + str(addr[1]))
outgoing.append(conn)
playerid = random.randint(1000, 1000000)
playerminion = Minion(playerid)
minionmap[playerid] = playerminion
conn.send(pickle.dumps(['id update', playerid]))
SecondaryServer(conn)
class SecondaryServer(asyncore.dispatcher_with_send):
def handle_read(self):
recievedData = self.recv(BUFFERSIZE)
if recievedData:
updateWorld(recievedData)
else: self.close()
MainServer(4321)
asyncore.loop()
Output:
Estimated Time to complete the project: Several Months
Brief Intro & Objective
The 3D Maze Game is an engaging Python project in which players maneuver through a procedurally created 3D maze to achieve an objective. This initiative strengthens essential Python programming abilities, game creation principles, and 3D rendering methods. The aim is to develop a playable maze exploration game that is both functional and visually captivating.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import random
# Define the maze dimensions and structure
maze_size = 10
maze = [[random.choice([0, 1]) for _ in range(maze_size)] for _ in range(maze_size)]
maze[0][0] = 0 # Start point
maze[maze_size - 1][maze_size - 1] = 0 # End point
# Colors
WHITE = (1, 1, 1)
BLACK = (0, 0, 0)
RED = (1, 0, 0)
# Initialize Pygame and OpenGL
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)
glTranslatef(-5, -5, -20)
# Player movement variables
player_x, player_y = 0, 0
speed = 0.5
def draw_cube(x, y, z):
"""Draws a cube at the given position."""
glBegin(GL_QUADS)
for surface in ((0, 1, 2, 3), (3, 2, 6, 7), (7, 6, 5, 4), (4, 5, 1, 0), (1, 5, 6, 2), (4, 0, 3, 7)):
for vertex in surface:
glVertex3fv(((x, y, z)[vertex % 3],) * 3)
glEnd()
def draw_maze():
"""Draw the 3D maze."""
for row in range(maze_size):
for col in range(maze_size):
if maze[row][col] == 1:
draw_cube(col, row, 0)
def move_player():
"""Move the player within the maze."""
global player_x, player_y
keys = pygame.key.get_pressed()
if keys[K_LEFT] and player_x > 0 and maze[player_y][player_x - 1] == 0:
player_x -= 1
if keys[K_RIGHT] and player_x < maze_size - 1 and maze[player_y][player_x + 1] == 0:
player_x += 1
if keys[K_UP] and player_y > 0 and maze[player_y - 1][player_x] == 0:
player_y -= 1
if keys[K_DOWN] and player_y < maze_size - 1 and maze[player_y + 1][player_x] == 0:
player_y += 1
def game_loop():
"""Main game loop."""
running = True
while running:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
draw_maze()
move_player()
glPushMatrix()
glTranslatef(player_x, player_y, 0)
glColor(RED)
draw_cube(0, 0, 0)
glPopMatrix()
pygame.display.flip()
pygame.time.wait(10)
pygame.quit()
if __name__ == "__main__":
game_loop()
Output:
Estimated Time to complete the project: 40+ Hours
Brief Intro & Objective
Chess is a classic board game of strategy and wit, played by two individuals on an 8x8 grid with alternating light and dark squares. At the start of the game, every player sets up 16 pieces, arranging them in the rows nearest to themselves. Pawns are placed on the second row, while other pieces fill the first row. The objective of the game is to move your pieces to a position where you can take your opponent's king and achieve a "checkmate," resulting in your victory. Each piece follows specific movement guidelines that players must adhere to.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
import pygame
import time
import sys
board = [[' ' for i in range(8)] for i in range(8)]
class Piece:
def __init__(self, team, type, image, killable=False):
self.team = team
self.type = type
self.killable = killable
self.image = image
bp = Piece('b', 'p', 'b_pawn.png')
wp = Piece('w', 'p', 'w_pawn.png')
bk = Piece('b', 'k', 'b_king.png')
wk = Piece('w', 'k', 'w_king.png')
br = Piece('b', 'r', 'b_rook.png')
wr = Piece('w', 'r', 'w_rook.png')
bb = Piece('b', 'b', 'b_bishop.png')
wb = Piece('w', 'b', 'w_bishop.png')
bq = Piece('b', 'q', 'b_queen.png')
wq = Piece('w', 'q', 'w_queen.png')
bkn = Piece('b', 'kn', 'b_knight.png')
wkn = Piece('w', 'kn', 'w_knight.png')
starting_order = {(0, 0): pygame.image.load(br.image), (1, 0): pygame.image.load(bkn.image),
(2, 0): pygame.image.load(bb.image), (3, 0): pygame.image.load(bk.image),
(4, 0): pygame.image.load(bq.image), (5, 0): pygame.image.load(bb.image),
(6, 0): pygame.image.load(bkn.image), (7, 0): pygame.image.load(br.image),
(0, 1): pygame.image.load(bp.image), (1, 1): pygame.image.load(bp.image),
(2, 1): pygame.image.load(bp.image), (3, 1): pygame.image.load(bp.image),
(4, 1): pygame.image.load(bp.image), (5, 1): pygame.image.load(bp.image),
(6, 1): pygame.image.load(bp.image), (7, 1): pygame.image.load(bp.image),
(0, 2): None, (1, 2): None, (2, 2): None, (3, 2): None,
(4, 2): None, (5, 2): None, (6, 2): None, (7, 2): None,
(0, 3): None, (1, 3): None, (2, 3): None, (3, 3): None,
(4, 3): None, (5, 3): None, (6, 3): None, (7, 3): None,
(0, 4): None, (1, 4): None, (2, 4): None, (3, 4): None,
(4, 4): None, (5, 4): None, (6, 4): None, (7, 4): None,
(0, 5): None, (1, 5): None, (2, 5): None, (3, 5): None,
(4, 5): None, (5, 5): None, (6, 5): None, (7, 5): None,
(0, 6): pygame.image.load(wp.image), (1, 6): pygame.image.load(wp.image),
(2, 6): pygame.image.load(wp.image), (3, 6): pygame.image.load(wp.image),
(4, 6): pygame.image.load(wp.image), (5, 6): pygame.image.load(wp.image),
(6, 6): pygame.image.load(wp.image), (7, 6): pygame.image.load(wp.image),
(0, 7): pygame.image.load(wr.image), (1, 7): pygame.image.load(wkn.image),
(2, 7): pygame.image.load(wb.image), (3, 7): pygame.image.load(wk.image),
(4, 7): pygame.image.load(wq.image), (5, 7): pygame.image.load(wb.image),
(6, 7): pygame.image.load(wkn.image), (7, 7): pygame.image.load(wr.image),}
def create_board(board):
board[0] = [Piece('b', 'r', 'b_rook.png'), Piece('b', 'kn', 'b_knight.png'), Piece('b', 'b', 'b_bishop.png'), \
Piece('b', 'q', 'b_queen.png'), Piece('b', 'k', 'b_king.png'), Piece('b', 'b', 'b_bishop.png'), \
Piece('b', 'kn', 'b_knight.png'), Piece('b', 'r', 'b_rook.png')]
board[7] = [Piece('w', 'r', 'w_rook.png'), Piece('w', 'kn', 'w_knight.png'), Piece('w', 'b', 'w_bishop.png'), \
Piece('w', 'q', 'w_queen.png'), Piece('w', 'k', 'w_king.png'), Piece('w', 'b', 'w_bishop.png'), \
Piece('w', 'kn', 'w_knight.png'), Piece('w', 'r', 'w_rook.png')]
for i in range(8):
board[1][i] = Piece('b', 'p', 'b_pawn.png')
board[6][i] = Piece('w', 'p', 'w_pawn.png')
return board
def on_board(position):
if position[0] > -1 and position[1] > -1 and position[0] < 8 and position[1] < 8:
return True
def convert_to_readable(board):
output = ''
for i in board:
for j in i:
try:
output += j.team + j.type + ', '
except:
output += j + ', '
output += '\n'
return output
def deselect():
for row in range(len(board)):
for column in range(len(board[0])):
if board[row][column] == 'x ':
board[row][column] = ' '
else:
try:
board[row][column].killable = False
except:
pass
return convert_to_readable(board)
def highlight(board):
highlighted = []
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 'x ':
highlighted.append((i, j))
else:
try:
if board[i][j].killable:
highlighted.append((i, j))
except:
pass
return highlighted
def check_team(moves, index):
row, col = index
if moves%2 == 0:
if board[row][col].team == 'w':
return True
else:
if board[row][col].team == 'b':
return True
def select_moves(piece, index, moves):
if check_team(moves, index):
if piece.type == 'p':
if piece.team == 'b':
return highlight(pawn_moves_b(index))
else:
return highlight(pawn_moves_w(index))
if piece.type == 'k':
return highlight(king_moves(index))
if piece.type == 'r':
return highlight(rook_moves(index))
if piece.type == 'b':
return highlight(bishop_moves(index))
if piece.type == 'q':
return highlight(queen_moves(index))
if piece.type == 'kn':
return highlight(knight_moves(index))
def pawn_moves_b(index):
if index[0] == 1:
if board[index[0] + 2][index[1]] == ' ' and board[index[0] + 1][index[1]] == ' ':
board[index[0] + 2][index[1]] = 'x '
bottom3 = [[index[0] + 1, index[1] + i] for i in range(-1, 2)]
for positions in bottom3:
if on_board(positions):
if bottom3.index(positions) % 2 == 0:
try:
if board[positions[0]][positions[1]].team != 'b':
board[positions[0]][positions[1]].killable = True
except:
pass
else:
if board[positions[0]][positions[1]] == ' ':
board[positions[0]][positions[1]] = 'x '
return board
def pawn_moves_w(index):
if index[0] == 6:
if board[index[0] - 2][index[1]] == ' ' and board[index[0] - 1][index[1]] == ' ':
board[index[0] - 2][index[1]] = 'x '
top3 = [[index[0] - 1, index[1] + i] for i in range(-1, 2)]
for positions in top3:
if on_board(positions):
if top3.index(positions) % 2 == 0:
try:
if board[positions[0]][positions[1]].team != 'w':
board[positions[0]][positions[1]].killable = True
except:
pass
else:
if board[positions[0]][positions[1]] == ' ':
board[positions[0]][positions[1]] = 'x '
return board
def king_moves(index):
for y in range(3):
for x in range(3):
if on_board((index[0] - 1 + y, index[1] - 1 + x)):
if board[index[0] - 1 + y][index[1] - 1 + x] == ' ':
board[index[0] - 1 + y][index[1] - 1 + x] = 'x '
else:
if board[index[0] - 1 + y][index[1] - 1 + x].team != board[index[0]][index[1]].team:
board[index[0] - 1 + y][index[1] - 1 + x].killable = True
return board
def rook_moves(index):
cross = [[[index[0] + i, index[1]] for i in range(1, 8 - index[0])],
[[index[0] - i, index[1]] for i in range(1, index[0] + 1)],
[[index[0], index[1] + i] for i in range(1, 8 - index[1])],
[[index[0], index[1] - i] for i in range(1, index[1] + 1)]]
for direction in cross:
for positions in direction:
if on_board(positions):
if board[positions[0]][positions[1]] == ' ':
board[positions[0]][positions[1]] = 'x '
else:
if board[positions[0]][positions[1]].team != board[index[0]][index[1]].team:
board[positions[0]][positions[1]].killable = True
break
return board
def bishop_moves(index):
diagonals = [[[index[0] + i, index[1] + i] for i in range(1, 8)],
[[index[0] + i, index[1] - i] for i in range(1, 8)],
[[index[0] - i, index[1] + i] for i in range(1, 8)],
[[index[0] - i, index[1] - i] for i in range(1, 8)]]
for direction in diagonals:
for positions in direction:
if on_board(positions):
if board[positions[0]][positions[1]] == ' ':
board[positions[0]][positions[1]] = 'x '
else:
if board[positions[0]][positions[1]].team != board[index[0]][index[1]].team:
board[positions[0]][positions[1]].killable = True
break
return board
def queen_moves(index):
board = rook_moves(index)
board = bishop_moves(index)
return board
def knight_moves(index):
for i in range(-2, 3):
for j in range(-2, 3):
if i ** 2 + j ** 2 == 5:
if on_board((index[0] + i, index[1] + j)):
if board[index[0] + i][index[1] + j] == ' ':
board[index[0] + i][index[1] + j] = 'x '
else:
if board[index[0] + i][index[1] + j].team != board[index[0]][index[1]].team:
board[index[0] + i][index[1] + j].killable = True
return board
WIDTH = 800
WIN = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("Chess")
WHITE = (255, 255, 255)
GREY = (128, 128, 128)
YELLOW = (204, 204, 0)
BLUE = (50, 255, 255)
BLACK = (0, 0, 0)
class Node:
def __init__(self, row, col, width):
self.row = row
self.col = col
self.x = int(row * width)
self.y = int(col * width)
self.colour = WHITE
self.occupied = None
def draw(self, WIN):
pygame.draw.rect(WIN, self.colour, (self.x, self.y, WIDTH / 8, WIDTH / 8))
def setup(self, WIN):
if starting_order[(self.row, self.col)]:
if starting_order[(self.row, self.col)] == None:
pass
else:
WIN.blit(starting_order[(self.row, self.col)], (self.x, self.y))
def make_grid(rows, width):
grid = []
gap = WIDTH // rows
print(gap)
for i in range(rows):
grid.append([])
for j in range(rows):
node = Node(j, i, gap)
grid[i].append(node)
if (i+j)%2 ==1:
grid[i][j].colour = GREY
return grid
def draw_grid(win, rows, width):
gap = width // 8
for i in range(rows):
pygame.draw.line(win, BLACK, (0, i * gap), (width, i * gap))
for j in range(rows):
pygame.draw.line(win, BLACK, (j * gap, 0), (j * gap, width))
def update_display(win, grid, rows, width):
for row in grid:
for spot in row:
spot.draw(win)
spot.setup(win)
draw_grid(win, rows, width)
pygame.display.update()
def Find_Node(pos, WIDTH):
interval = WIDTH / 8
y, x = pos
rows = y // interval
columns = x // interval
return int(rows), int(columns)
def display_potential_moves(positions, grid):
for i in positions:
x, y = i
grid[x][y].colour = BLUE
def Do_Move(OriginalPos, FinalPosition, WIN):
starting_order[FinalPosition] = starting_order[OriginalPos]
starting_order[OriginalPos] = None
def remove_highlight(grid):
for i in range(len(grid)):
for j in range(len(grid[0])):
if (i+j)%2 == 0:
grid[i][j].colour = WHITE
else:
grid[i][j].colour = GREY
return grid
create_board(board)
def main(WIN, WIDTH):
moves = 0
selected = False
piece_to_move=[]
grid = make_grid(8, WIDTH)
while True:
pygame.time.delay(50) ##stops cpu dying
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
y, x = Find_Node(pos, WIDTH)
if selected == False:
try:
possible = select_moves((board[x][y]), (x,y), moves)
for positions in possible:
row, col = positions
grid[row][col].colour = BLUE
piece_to_move = x,y
selected = True
except:
piece_to_move = []
print('Can\'t select')
#print(piece_to_move)
else:
try:
if board[x][y].killable == True:
row, col = piece_to_move ## coords of original piece
board[x][y] = board[row][col]
board[row][col] = ' '
deselect()
remove_highlight(grid)
Do_Move((col, row), (y, x), WIN)
moves += 1
print(convert_to_readable(board))
else:
deselect()
remove_highlight(grid)
selected = False
print("Deselected")
except:
if board[x][y] == 'x ':
row, col = piece_to_move
board[x][y] = board[row][col]
board[row][col] = ' '
deselect()
remove_highlight(grid)
Do_Move((col, row), (y, x), WIN)
moves += 1
print(convert_to_readable(board))
else:
deselect()
remove_highlight(grid)
selected = False
print("Invalid move")
selected = False
update_display(WIN, grid, 8, WIDTH)
main(WIN, WIDTH)
Output:
Estimated Time to complete the project: 5 - 7 Days
Brief Intro & Objective
A Python-based RTS (Real-Time Strategy) game allows players to control units and structures in real-time, overseeing resources, constructing armies, and devising strategies to outsmart rivals. The objective is generally to conquer the opponent by either annihilating their base, overpowering their troops, or achieving particular goals in the game.
Key Concepts & Skills Learned
Libraries Used
Game Mechanics
Code Breakdown
import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up display
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Basic RTS Game")
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Define a basic unit class
class Unit(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((40, 40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = 5
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT]:
self.rect.x += self.speed
if keys[pygame.K_UP]:
self.rect.y -= self.speed
if keys[pygame.K_DOWN]:
self.rect.y += self.speed
def draw(self, surface):
surface.blit(self.image, self.rect)
# Create a sprite group for all units
all_units = pygame.sprite.Group()
# Function to create a new unit
def create_unit(x, y):
unit = Unit(x, y)
all_units.add(unit)
# Main game loop
def game_loop():
clock = pygame.time.Clock()
running = True
# Create the first unit
create_unit(100, 100)
while running:
screen.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update and draw all units
all_units.update()
all_units.draw(screen)
pygame.display.flip()
clock.tick(60) # 60 FPS
pygame.quit()
sys.exit()
if __name__ == "__main__":
game_loop()
Output:
Estimated Time to complete the project: 12 - 24 Months
Also Read: Python Banking Project [With Source Code]
upGrad is a platform that provides you with the resources to excel in game development and succeed in the gaming sector. If you are kick-starting your journey or aiming to boost your career in python, upGrad’s programs are designed to support you at every stage.
Master of Design in User Experience
Professional Certificate Program in UI/UX Design & Design Thinking
AI-Powered Full Stack Development Course by IIITB
Learn Basic Python Programming
Learn Python Libraries: NumPy, Matplotlib & Pandas
Benefit from the free career counselling from experts at upGrad and take a step towards your programming dreams.
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources