Python Game Programming by Example. Full Code 2024
Python Game Programming by Example. Full Code 2024
Submit Guess
Score: 0
import tkinter as tk
from tkinter import messagebox
import random
class NumberGuessingGame:
def_ init_ (self, master):
self.master = master
self.master.title("Number Guessing Game")
self.total_levels = 5
self.level = 1
self.target_number = self.generate_target_number()
self.guesses_left = 10
self.score = 0
self.label = tk.Label(
master, text="Guess the number between 1 and 100:")
self.label.pack(pady= 10)
self.entry = tk.Entry(master)
self.entry.pack(pady= 10)
self.level_label = tk.Label(
master, text=f'Level: {self.level}", font=("Helvetica", 16))
self.level_label.pack(pady= 10)
self.reset_button = tk.Button(
master, text="Play Again", command=self.reset_game)
self.reset_button.pack(pady= 10)
self.reset-button.packjforgetO
self.start_level_message()
def generateJ:arget_number(self):
return random.randint(l, 10 * self.level)
def start_level_message(self):
level_message = f'Welcome to Level {self.level)! The target number range is now 1 to {10 * self.level}."
self.level_label.config(text=level_message)
# Display for 3 seconds
self.master.after(3000, self.clear_level_message)
def clear_level_message(self):
self.entry.delete(O, tk.END)
self.entry.focus_set()
def check_guess(self):
user_input = self.entry.get()
if not user_input:
self.result_label.config(text="Please enter a valid guess.")
return
try:
user_guess = int(user_input)
except ValueError:
self.result_label.config(text="Please enter a valid integer.")
return
if user_guess == self.target_number:
self.result_label.config(
text=f'Congratulations! You guessed the correct number. Score: {self.calculate_score()}")
self.submit_button.config(state=tk.DISABLED)
self.reset_button.pack(pady= 10)
def calculate_score(self):
score = self.guessesjeft * 10 * self.level
self.score += score
self.update_score_label()
return self.score
def update_score_label(self):
self.score_label.config(text=f'Score: {self.score}")
def next_level_message(self):
self.level + = 1
self.target.number = self.generate_target_number()
self.guesses_left = 10
self.submit_button.config(state=tk.NORMAL)
self.level_label.config(text=f'Level: {self.level}")
self.start_level_message()
def show_performance_feedback(self):
feedback = f'All levels completed! Your total score is {self.score}."
messagebox.showinfo("Game Over", feedback)
def reset_game(self):
self.level = 1
self.target.number = self.generate_target_number()
self.guesses_left =10
self.label.config(text="Guess the number between 1 and 100:")
self.result_label.config(text="")
self.submit_button.config(state=tk.NORMAL)
self.reset_button.pack_forget()
self.score = 0
self.update_score_label()
self.level_label.config(text=f'Level: {self.level}")
self.start_level_message()
This Python script creates a simple number guessing game using the Tkinter library for the
graphical user interface ( GUI). Let's break down the code step by step :
Importing Libraries:
• tkinter : This library is used for creating GUI applications .
NumberGuessingGame Class:
This class represents the main functionality of the game .
Constructor (_ init_ ):
• Initializes the game parameters such as total_levels , level, target_number,
guessesjeft, and score .
• Sets up the GUI elements including labels, entry fields, buttons, etc .
• Calls start_level_message () method to display a welcome message for the first level.
generate_target_number () Method:
• Generates a random target number within a specific range based on the current level.
start_level_message () Method:
• Displays a welcome message for the current level.
clear_level_message () Method:
• Clears the entry field after displaying the level message .
check_guess () Method:
• Checks the user's guess against the target number .
• Handles cases where the input is invalid, the guess is correct, or the guess is incorrect.
calculate_score () Method:
• Calculates the score based on the remaining guesses and the current level.
update_score_label () Method:
• Updates the score label with the current score .
next_level_message () Method:
• Prepares for the next level by updating parameters and generating a new target number .
show_performance_feedback () Method:
• Shows a message box with the performance feedback when all levels are completed .
reset_game () Method:
• Resets the game parameters to start a new game .
• Clears the GUI elements and sets up for the first level.
Main Script:
• Creates a Tkinter Tk instance.
•» A window will appear with the title " Number Guessing Game " and the initial level
message .
3. Making a Guess :
° Enter your guess into the entry field .
4. Receiving Feedback:
° If your guess is correct, you'll receive a congratulatory message and your score for that
round.
•> If your guess is incorrect, you'll receive a hint ( too low or too high ) , the remaining
» The game will update the target number range for the new level.
6. Game Over:
° The game ends when you complete all levels or run out of guesses .
’ If you complete all levels, a message box will appear with your total score .
7. Playing Again:
- Click the " Play Again " button to reset the game and start from Level 1 .
Tips:
• Pay attention to the level message for the updated target number range .
• Try to guess the correct number within the given number of attempts to maximize your score .
• If you run out of guesses, the correct number will be revealed, and you can choose to play again .
2. Crossword Generator
j Crossword Puzzle Generator — □ X
c r 0 s 5 w 0 r d
e X a m P 1 e 9
t n P
k e u
i r z
n a z
p y t h 0 n t t 1
e 0 e
c 0 d e r r
python
crossword
puzzle
Word List generator
tkinter
code
example
import tkinter as tk
from tkinter import messagebox
3 I import random
c class CrosswordGenerator:
def__init_ (self, root):
self.root = root
self.root.title("Crossword Puzzle Generator")
12.
13. self.rows_entry = tk.Entry(root)
14. self.rows_entry.grid(row=0, column=l, padx=10, pady=10)
15.
16. self.cols.entry = tk.Entry(root)
17. self.cols_entry.grid(row=0, column=2, padx=10, pady=10)
18.
19. self.generate_button = tk.Button(
20. root, text="Generate Puzzle", command=self.generate_puzzle)
21 self.generate_button.grid(row=0, column=3, padx=10, pady=10)
22
self.puzzle_frame = tk.Frame(root)
24. self.puzzle_frame.grid(row=l, column=0, columnspan=4, padx=10, pady=10)
25.
26. self.word_list_label = tk.Label(root, text="Word List:")
27. self.word_list_label.grid(
28. row=2, column=0, padx=10, pady=10, columnspan=2)
29
30 self.word_list_var = tk.StringVar()
self.word_list_display = tk.Label(
32 root, textvariable=self.word_list_var, wraplength=200, justify="left")
33 self.word_list_display.grid(
34 row=2, column=2, padx=10, pady=10, columnspan=2)
35
36 def generate_puzzle(self):
try:
38. rows = int(self.rows_entry.get())
39. cols = int(self.cols_entry.get())
40
41. if rows < = 0 or cols < = 0:
42. messagebox.showerror(
43. "Error", "Grid size should be positive integers.")
44. return
45.
46. puzzle, wordjist = self.create_puzzle(rows, cols)
47. self.display_puzzle(puzzle)
48. self.display_word_list(word_list)
49.
50. except ValueError:
51. messagebox.showerror(
52. "Error", "Please enter valid integers for grid size.")
56.
57. words = ["python", "crossword", "puzzle", "generator", "tkinter", "code", "example"]
58
59 wordjist = "\n".join(words)
60
61. for word in words:
62. direction = random.choice(['across', 'down'])
63. placed = False
64.
for _ in range(lO): # Try placing the word multiple times
66. if direction == ’across’:
67. row = random.randint(0, rows -1)
68. col = random.randint(0, cols - len(word))
69. if all(puzzle[row][col + i] = = " for i in range(len(word))):
70. for i in range(len(word)):
71. puzzle[row][col + i] = word[i]
72. placed = True
73. break
74. else:
75. row = random.randint(0, rows - len(word))
76. col = random.randint(0, cols -1)
77. if all(puzzle[row + i][col] = = " for i in range(len(word))):
78. for i in range(len(word)):
79. puzzle[row + i][col] = word[i]
80. placed = True
81. break
82.
83. if not placed:
84. messagebox.showwarning("Warning", f'Unable to place the word '{word}' in the puzzle.")
85.
86. return puzzle, wordjist
87.
88.
90.
91.
92. def display_puzzle(self, puzzle):
93. for widget in self.puzzle_frame.winfo_children():
94. widget.destroyO
95.
96. for i, row in enumerate(puzzle):
97. for j, cell in enumerate(row):
QQ label = tk.Label(self.puzzle_frame, text=cell,
width=4, height=2, relief="solid", borderwidth=l)
100. label.grid(row=i, column=j)
101.
L 02. def display_word_list(self, word_list):
L 03. self. word_listjvar. set (word_list)
104.
L 05. if name == " main
L06. root = tk.Tk()
L 07. crossword_generator = CrosswordGenerator(root)
108. root .mainloopO
This Python script creates a simple Crossword Puzzle Generator using the Tkinter library .
The program has a graphical user interface ( GUI) with input fields to specify the grid
size and a button to generate a crossword puzzle . Let's break down the components of the
script:
1. Imports:
• tkinter : The standard GUI toolkit for Python .
■> messagebox : A submodule of Tkinter used for displaying various types of message
boxes.
2. Class: CrosswordGenerator
Initialization (_ init_ ):
■ Initializes the Tkinter window ( TOOt ) and sets its title .
■ Creates various GUI elements such as labels, entry fields, buttons, and a frame
to display the crossword puzzle .
o Method: generate_puzzle :
■ Retrieves the grid size ( number of rows and columns ) entered by the user .
o Method: create_puzzle :
■ Takes the number of rows and columns as input and initializes an empty grid .
toio) if unsuccessful.
■ Returns the generated puzzle grid and the formatted word list.
o Method: display_puzzle :
■ Clears the existing widgets in the puzzle frame .
■ Iterates through the puzzle grid and creates Tkinter labels for each cell,
displaying the characters in a grid layout.
o Method: display_word_list:
■ Sets the Tkinter StringVar ( WOrd_list_var ) with the formatted word
list.
3. Main Block:
• Creates a Tkinter root window and an instance of the CrosswordGenerator class .
- Enters the Tkinter event loop ( root . mainloop () ) to handle user interactions .
4. Example Words:
o The script uses a predefined list of words for the crossword puzzle . You can modify the
6. Note:
• The script has some basic error handling to ensure valid input and warns the user if a
word cannot be placed in the puzzle .
prompted.
2. View Puzzle:
•> The crossword puzzle grid and word list will be displayed in the Tkinter window .
4. Manually Solve:
• You can manually solve the puzzle by looking at the words in the list and entering them
into the corresponding cells in the grid .
5. Check Placement:
* Crossword puzzles typically follow certain rules, such as words intersecting at a common
letter . Ensure that your entries respect these rules .
6. Verify Correctness:
• Compare your filled - in puzzle with the word list to ensure you’ve correctly placed all the
words .
3. Hangman Game
/ Hangman Game — □ X
__t____
Enter a letter
I
Guess
Restart
import tkinter as tk
from tkinter import messagebox
import random
eye_radius = 4
mouth_radius = 8
head_y=O
class HangmanGUI:
def__init_ (self, master):
self.master = master
self.master.title("Hangman Game")
self.guess.entry = tk.Entry(self.master)
self.guess_entry.pack()
self.guess_button = tk.Button(
self.master, text="Guess", command=self.make_guess)
self.guess_button.pack()
self.restart_button = tk.Button(
self.master, text="Restart", command=self. restart_game)
self.restart_button.pack()
self.draw_canvas()
self.choose_word()
self.update_word_label()
def draw_canvas(self):
self.canvas = tk.Canvas(self.master, width=300, height=300)
self.canvas.packQ
def choose_word(self):
self.word_to_guess = random.choice(self.word_list)
def update_word_label(self):
display =""
for letter in self.word_to_guess:
if letter in self.guesses:
display += letter + ""
else:
display += V______________________
self.word_label.config(text=display.stripO)
def make_guess(self):
guess = self.guess_entry.get().lower()
if guess.isalphaO and len(guess) = = 1:
if guess in self.guesses:
messagebox.showinfo(
"Already Guessed", f'You have already guessed the letter '{guess}'.")
else:
self.guesses.add(guess)
if guess not in self.word_to_guess:
self.attemptsjeft -= 1
self.draw_hangman()
self.update_word_label()
if self.attempts_left == 0:
self.game_over()
elifnot in self.word_label.cget("text"):
self.game_win()
else:
messagebox.showinfo(
"Invalid Input", "Please enter a valid single letter.")
self.guess_entry.delete(O, tk.END)
def draw_hangman(self):
# Clear the canvas before drawing
self.canvas.delete("all")
# Disable the guess button when the head reaches the top of the pole
if head.y == min_head_y:
self.guess_button.config(state=tk.DISABLED)
# Draw eyes
eye_x_left = 150-8
eye_y = head.y - 6
self.canvas.create_oval(
eye_x_left - eye_radius, eye_y - eye_radius,
eye_x_left + eye_radius, eye_y + eye_radius, fill="black") # Left eye
eye_x_right =150 + 8
self.canvas.create_oval(
eye_x_right - eye_radius, eye_y - eye_radius,
eye_x_right + eye_radius, eye_y + eye_radius, fill="black") # Right eye
def game_over(self):
# Draw eyes
eye_x_left = 150-8
eye_y = head.y - 6
self.canvas.create_oval(
eye_x_left - eye_radius, eye_y - eye_radius,
eye_x_left + eye_radius, eye_y + eye_radius, fill="black") # Left eye
eye_x_right =150 + 8
self.canvas.create_oval(
eye_x_right - eye_radius, eye_y»eye_radius,
eye_x_right + eye_radius, eye_y + eye_radius, fill="black") # Right eye
def game_win(self):
messagebox.showinfo("Congratulations",
"Congratulations! You guessed the word.")
def restart_game(self):
# Reset game state
self.choose_word()
self.guesses = set()
self.attempts_.left = self.max_attempts
self.guess_button.config(state=tk.NORMAL)
self.update_word_label()
def main():
root = tk.Tk()
hangman_game = HangmanGUI(root)
root.mainloopO
if _name_ == "_main_":
main()
The provided Python Code is an implementation of a simple Hangman game using the
Tkinter library for the graphical user interface . Let's go through the code in detail:
HangmanGUI Class:
1. Initialization (_ init_ method):
The constructor initializes the main aspects of the game .
Sets up the Tkinter window and basic elements like labels, entry fields, buttons, and a
canvas for drawing.
o Defines attributes such as the word list, word to guess, guessed letters, maximum
attempts, attempts left, and head radius .
2. draw_canvas Method:
» Initializes and draws the static parts of the hangman ( pole and base ) on the canvas .
3. choose_word Method:
° Randomly selects a word from the predefined word list.
4. update_word_label Method:
o Updates the word label based on the guessed letters, showing underscores for unguessed
letters .
5. make_guess Method:
* Retrieves the guessed letter from the entry field .
° Checks if the guess is valid ( a single alphabetical character ) and whether it has been
guessed before .
° Updates the game state, checks for a win or loss, and handles invalid inputs .
6. draw_hangman Method:
o Draws the hangman figure based on the number of attempts left.
Handles the progression of the hangman figure as incorrect guesses are made .
7. game_over Method:
’ Displays a game over message and draws a sad face when the player runs out of attempts .
8. game_win Method:
° Displays a congratulations message when the player successfully guesses the word .
9. restart_game Method:
*> Resets the game state for a new round .
Main Function:
• Creates a Tkinter root window and initializes the HangmanGUI class .
Usage:
• The player interacts with the game by entering a single letter in the entry field and clicking the " Guess "
button .
• The canvas displays the hangman figure, and the word to guess is shown with underscores for unguessed
letters .
• The game ends when the player either correctly guesses the word or runs out of attempts .
Additional Notes:
• The game uses a predefined word list, and a new word is chosen for each round .
• The maximum attempts are set to 6 by default, and the hangman figure progressively appears as
incorrect guesses are made .
• The game provides options to restart and play again after a win or loss .
Make sure you have Tkinter installed (import tkinter as tk) before running this code . You
can run it as a Python script to play the Hangman game in a simple GUI window .
° Make sure you have Tkinter installed ( it's usually included with Python installations ).
3. Game Start:
o The game will start by choosing a random word from the predefined word list.
4. Guess a Letter :
° Enter a single letter in the entry field provided .
5. Game Progress:
- The word to guess will be displayed with underscores for unguessed letters .
•» The hangman figure will appear on the canvas based on incorrect guesses .
6. Continue Guessing:
• Keep entering letters and clicking the " Guess " button .
• The game will update the word display and hangman figure accordingly .
7. Winning:
- If you correctly guess the entire word, a congratulatory message will appear .
8. Losing:
«> If you run out of attempts, a game over message will be displayed, and a sad face will
appear.
9. Restart:
«> You can restart the game by clicking the " Restart " button .
«> A new word will be chosen, and the game state will be reset.
10. Repeat:
o Continue playing by guessing letters and trying to guess the word .
Remember:
• Only enter a single alphabetical letter as a guess .
• The game tracks guessed letters, and entering the same letter again will show a message .
• The maximum attempts are set to 6, and the hangman figure will progressively appear as you make
incorrect guesses .
4. Tic Tac Toe Game
f TicTacToe — □ X
0 X
0 X
0 X
Player 2
Player 1 Symbol: X Player 2 Symbol: 0 Reset |
import tkinter as tk
from tkinter import messagebox
class TicTacToe:
def_init_ (self):
self, window = tk.Tk()
self.window.title("Tic Tac Toe")
self.board_size =10
self.board = [[" for _ in range(self.board_size)]
for _ in range(self.board_size)]
self.current_player = tk.StringVar()
self.current_player.set("Player 1")
self, player 1 .symbol = tk.StringVar()
self.player2_symbol = tk.StringVar()
self, player l_symbol.set("X")
self.player2_symbol.set("O")
self.playerl_score = 0
self.player2_score = 0
self.create_widgets()
def create.widgets(self):
for i in range(self.board_size):
for j in range(self.board_size):
btn = tk.Button(self. window, text=", font=('normar, 12), width=5, height=2,
command=lambda row=i, col=j: self.on_button_click(row, col))
btn.grid(row=i, column=j, padx=0, pady=0, sticky="nsew")
self.board[i][j] = btn
for i in range(self.board.size):
self.window.grid_rowconfigure(i, weight=l, uniform="row")
self, window. grid_columnconfigure(i, weight=l, uniform="col")
self.reset.button = tk.Button(
self, window, text="Reset", command=self.reset_board)
self.reset_button.grid(row=self.board_size + 1, column=4)
self.playerl_score_label = tk.Label(
self.window, text="Player 1 Score: 0")
self.playerl_score_label.grid(row=self.board_size + 2, column=0)
self.player2_score_label = tk.Label(
self.window, text="Player 2 Score: 0")
self.player2_score_label.grid(row=self.board_size + 2, column=2)
def on_button_click(self, row, col):
if self.board[row][col]["text"] ==
self.board[row][col]["text"] = self.playerl_symbol.get(
) if self.current_player.get() == "Player 1" else self.player2_symbol.get()
if self.check_winner(row, col):
messagebox.showinfo(
"Game Over", f'{self.current_player.get()} wins!")
self.update_scores()
self.reset_board()
elif self.check_draw():
messagebox.showinfo("Game Over", "It's a draw!")
self.reset_board()
else:
self.switch_player()
# Check row
if all(self.board[row][c]["text"] == symbol for c in range(self.board_size)):
return True
# Check column
if all(self.board[r][col]["text"] == symbol for r in range(self.board_size)):
return True
# Check diagonals
if row == col and all(self.board[i][i]["text"] == symbol for i in range(self.board_size)):
return True
if row + col == self.board_size - 1 and all(self.board[i][self.board_size - 1 - i]["text"] == symbol for i in
range(self.board_size)):
return True
return False
def check_draw(self):
for i in range(self.board_size):
for j in range(self.board_size):
if self.board[i][j]["text"] ==
return False
return True
def switch_player(self):
self.current_player.set(
"Player 2" if self.current_player.get() == "Player 1" else "Player 1")
def update_scores(self):
if self.current_player.get() = = "Player 1":
self.playerl_score + = 1
self.playerl_score_label.config(
text=f'Player 1 Score: {self.playerl.score}")
else:
self.player2_score + = 1
self.player2_score_label.config(
text=f Player 2 Score: {self.player2_score}")
def reset_board(self):
for i in range(self.board_size):
for j in range(self.board_size):
self.board[i][j]["text"] = "
self.current_player.set("Player 1")
This is a simple implementation of the classic Tic Tac Toe game using the Tkinter library in
Python . Let's break down the code and understand each component:
1. Class Definition ( TicTacToe ):
The TicTacToe class is initialized with the creation of a Tkinter window .
It sets the title of the window to " Tic Tac Toe " and defines the size of the game board
( 10x10 ) and initializes the board with an empty state .
• > CUirent_player ( to track the current player ) ,
Various attributes are defined, such as
• > Labels are set up to display the current player, player symbols, and player scores .
-> Checks for a winner using the check_winner method . If a winner is found, a
message box is displayed, scores are updated, and the board is reset.
° If the game is a draw ( no winner and no empty spaces left ) , it shows a message box and
8. Main Block:
• TicTacToe class is created, and the Tkinter main loop is started
An instance of the
o Each cell in the grid represents a position where a player can place their symbol.
2. Player Assignment:
There are two players, often referred to as " Player 1 " and " Player 2
Player 1 typically uses " X, " and Player 2 uses 11 O
Gameplay:
3. Starting the Game :
•» The game starts with an empty board .
4. Taking Turns:
° Players take turns to make a move .
° Player 1 ( X ) goes first, followed by Player 2 ( O ) , and they continue alternating turns .
5. Making a Move :
° On a player's turn, they choose an empty cell on the grid to place their symbol.
•> If the board is filled with symbols, and there is no winner, the game is a draw .
Some implementations include a " Reset " button to clear the board and start over .
Example Gameplay:
Player 1 ( X ) makes a move by clicking on an empty cell.
• Players continue taking turns until one player gets three symbols in a row, or the board is filled .
Winning Combinations:
• Horizontal:
mathematica Code
X|X|X
O|O|
I I
• Vertical:
mathematica Code
X|O|
X|O|
XI I
• Diagonal Z
mathematica Code
X|O|
IX|o
I IX
Tips:
• Pay attention to the opponent's moves and plan ahead to block potential winning combinations .
• Try to create your own winning opportunities while preventing your opponent from doing the same .
Tic Tac Toe is a game of strategy and anticipation, often enjoyed for its simplicity and quick
gameplay . It's a great introductory game for those new to strategy board games .
5. Maze Solver Game
/ Maze Solver □
Solve Maze
Clear Maze
A* —J
import tkinter as tk
from queue import PriorityQueue, Queue
class MazeSolver:
def_ init_ (self, root, rows, cols):
self.root = root
self.rows = rows
self.cols = cols
self.canvas_size = 400
self.cell_size = self.canvas_size // max(rows, cols)
self.canvas = tk.Canvas(
root, width=self.canvas_size, height=self.canvas_size)
self.canvas.pack()
self.start = None
self.end = None
self.maze = [[0] * cols for _ in range(rows)]
self.draw_grid()
self.canvas.bind("<Button-l >", self.on.click)
self.solve.button = tk.Button(
root, text="Solve Maze", command=self.solve_maze)
self.solve_button.pack()
self.clear.button = tk.Button(
root, text="Clear Maze", command=self.clear_maze)
self.clear_button.pack()
self.algorithm_var = tk.StringVar(root)
self.algorithm_var.set("A*")
self.algorithm_menu = tk.OptionMenu(
root, self.algorithm.var, "A*", "Dijkstra", "BFS")
self.algorithm_menu.pack()
def draw_grid(self):
for i in range(self.rows):
for j in range(self.cols):
xl, yl = j * self.celLsize, i * self.celLsize
x2, y2 = xl + self.cell_size, y 1 + self.celLsize
self.canvas.create_rectangle(
xl, yl, x2, y2, fill="white", outline="black")
def clear_maze(self):
self.start = None
self.end = None
self.maze = [[0] * self.cols for _ in range(self.rows)]
self.canvas.deleteC'all")
self.draw_grid()
def solve_maze(self):
algorithm = self.algorithm_var.get()
path = self.run_algorithm(algorithm)
if path:
self.highlight_path(path)
def astar(self):
start = self.start
end = self.end
open_set = PriorityQueue()
open_set.put((0, start))
came_from = {start: None}
g_score = {start: 0}
return None
def dijkstra(self):
start = self.start
end = self.end
open_set = PriorityQueue()
open_set.put((0, start))
came_from = {start: None}
g_score = {start: 0}
while not open_set.empty():
current = open_set.get()[l]
if current == end:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
return path[::-l]
return None
defbfs(self):
start = self.start
end = self.end
queue = Queue()
queue.put(start)
came_from = {start: None}
while not queue.empty():
current = queue.get()
if current == end:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
return path[::-l]
return None
<• Queue and PriorityQueue : Used for implementing the queue data structure for
BFS and the priority queue for A and Dijkstra's algorithm .
2. MazeSolver Class:
o Initialization (_ init_ ):
■ Initializes the GUI components, such as the main window ( root ) , canvas
for drawing the maze, buttons for solving and clearing the maze, and an
option menu for selecting the algorithm .
■ Sets up variables for the number of rows and columns in the maze, cell size,
and other parameters .
■ Initializes the maze grid, start and end points, and binds the left - click event
to the on_click method .
on a cell.
■ A * and Dijkstra’s algorithms use priority queues, while BFS uses a regular
queue.
cells .
° Run the script using the command : python maze_solver . py ( or the equivalent
command for your Python environment ).
2. GUI Interface:
” A window titled " Maze Solver " will appear .
«» The GUI consists of a canvas where you can create a maze, buttons for solving and
clearing the maze, and an option menu for selecting the solving algorithm .
3. Creating a Maze :
’ Left - click on the white cells in the canvas to create a maze . Clicking on a cell toggles it
between an empty cell and an obstacle ( black cell ).
■ Click on another white cell to set the end point ( red rectangle ).
4. Selecting an Algorithm :
° Choose the solving algorithm from the drop - down menu ( A * , Dijkstra, or BFS ).
path .
points .
8. Repeat and Experiment:
o You can create different mazes, change the start and end points, and explore how
different algorithms find solutions .
6. Snake Game
/ Snake Game
Score: 0
Speed: 10
Level: 1
Restart Pause/Resume
import tkinter as tk
import random
import winsound # For Windows systems
class SnakeGame:
def_ init_ (self, master, width=400, height=400):
self.master = master
self.master.title("Snake Game")
self.canvas = tk.Canvas(self.master, width=width,
height=height, bg="black")
self.canvas.packQ
self.canvas.focus_set()
self.button_frame = tk.Frame(self.master)
self.button_frame.pack(side="bottom")
restart_button = tk.Button(
self.button_frame, text="Restart", command=self.restart_game)
restart_button.pack(side="left")
pause_button = tk.Button(
self.button_frame, text="Pause/Resume", command=self.toggle.pause)
pause_button.pack(side="left")
self.canvas.bind("<Key>", self.change_direction)
self.master.after(self.speed, self.update)
def create_food(self):
x = random.randint(l, 39) * 10
y = random.randint(l, 39) * 10
self.canvas.create_rectangle(
x, y, x + 10, y + 10, outline="red", fill="red", tags="food")
winsound.Beep(523, 100) # Beep sound when the snake eats food
return x, y
def create_obstacles(self):
obstacles = []
for _ in range(5 * self.level): # Adjust obstacle count based on level
x = random.randint(l, 39) * 10
y = random.randint(l, 39) * 10
self.canvas.create_rectangle(
x, y, x + 10, y + 10, outline="white", fill="white", tags="obstacle")
obstacles.append((x, y))
return obstacles
def move(self):
if self.game_over_flag or self.paused:
return
head = self.snake[O]
if self.direction == "Right":
new_head = (head[0] +10, head[lj)
elif self, direction == "Left":
new_head = (head[O] -10, head[l])
elif self.direction == "Up":
new_head = (head[0], head[l] -10)
elif self.direction == "Down":
new_head = (head[0], head[l] +10)
self.snake.insert(O, new_head)
if new_head == self.food:
self.score + = 1
self.canvas.delete("food")
self.food = self.create_food()
self.increase_speed()
self.check_win() # Check if the player has won after increasing the score
else:
self.canvas.delete(self.snake[-l])
self.snake.popO
self.check_collision()
def increase_speed(self):
level-thresholds = [5,10,15, 20, 25, 30, 35, 40,45, 50]
if self.level == len(level_thresholds):
self.display_completion_message()
def display_completion_message(self):
self.canvas.create_text(
200, 200, text="All Levels Completed’XnCongratulations!", fill="white", font=("Helvetica", 16), tags="gameover"
def check_collision(self):
head = self.snake[O]
if(
head[O] < 0
or head[0] >= 400
or head[l] < 0
or head[l] >= 400
or head in self.snake[l:]
or head in self.obstacles
):
self.game_over()
def check_win(self):
if self.level = = 4 and self.score >= 20:
self.game_over_flag = True
if self.score > self.high_score:
self.high_score = self.score
self.canvas.create_text(
200, 200, text=f 'Congratulations!\nYou passed all levels!\nScore: {self.score}\nHigh Score: {self.high_score}",
fill="white", font=("Helvetica", 16), tags="gameover")
# Play a win sound
winsound.PlaySoundCgame_win.wav", winsound.SNDJFILENAME)
def game_over(self):
self.game_over_flag = True
if self.score > self.high_score:
self.high_score = self.score
self.canvas.create_text(
200, 200, text=f'Game Over\nScore: {self.score]\nHigh Score: {self.high_score}",
fill="white", font=("Helvetica", 16), tags="gameover")
winsound.PlaySound("game_over.wav", winsound.SNDJFILENAME)
def restart_game(self):
self.canvas.delete("all")
self.snake = [(100,100), (90,100), (80,100)]
self.direction = "Right"
self.food = self.create_food()
self.obstacles = self.create_obstacles()
self.score = 0
self.level = 1
self.speed =100
self.game_over_flag = False
self.paused = False
self.draw()
self.updateO
def toggle_pause(self):
self.paused = not self.paused
def update(self):
self.moveO
self.drawO
if not self.game_over_flag:
self.master.after(self.speed, self.update)
def draw(self):
self.canvas.delete("all")
# Border around the game area
self.canvas.create_rectangle(O,0,400, 400, outline="white")
This is a Snake Game implemented using the Tkinter library in Python . Let's break down
the code and understand each component:
1. Imports:
Python Code
import tkinter as tk
import random
import winsound
» tkinter : The standard Python interface to the Tk GUI toolkit.
• random : Used for generating random numbers for the initial positions of the food and
obstacles .
2. SnakeGame Class:
Python Code
class SnakeGame :
<• This class represents the main game logic .
3. Initialization:
Python Code
def__init ( self, master, width = 400, height = 400 ):
° The constructor initializes the game with a Tkinter window ( master ) and sets the default
° It sets up the canvas, snake, initial direction, food, level, obstacles, score, speed, and other game -
related attributes .
o The game state is displayed on the Tkinter window using labels and buttons .
4. create_food method:
Python Code
defcreate_food ( self):
° Generates random coordinates for the food and creates a red rectangle at that position on the
canvas .
«> Plays a beep sound when the snake eats the food .
5. create_obstacles method:
Python Code
def create_obstacles ( self):
«> Generates a specified number of obstacles at random positions on the canvas .
6. move method:
Python Code
def move ( self):
• Updates the snake's position based on the current direction .
* Handles collisions with food, updates the score, and increases the speed and level when certain
conditions are met.
° Checks for collisions with obstacles or the game boundaries .
7. increase_speed method:
Python Code
defincrease_speed (self):
«> Increases the game speed based on the player's score and updates the level.
8. display_completion_message method:
Python Code
def display_completion_message ( self):
Displays a congratulatory message when the player completes all levels .
9. check_collision method:
Python Code
def check_collision ( self):
<• Checks for collisions with walls, snake body, and obstacles .
2. Initial Setup:
” The game starts with a snake ( a series of white rectangles ) and a red square
representing food.
° The snake will continuously move in the chosen direction until the game ends .
4. Objective:
• The goal is to navigate the snake to eat the red food squares .
o Each time the snake consumes food, it grows longer, and the player earns points .
5. Avoid Collisions:
“ Avoid running into the walls of the game area .
6. Scoring:
° The score is displayed at the top of the game window .
•> Each time the snake eats food, the score increases .
• There are multiple levels in the game, and with each level, the difficulty increases .
° The current speed, level, and score are displayed on the right side of the game window .
8. Winning:
° If you reach a certain level and achieve a specific score, you win the game .
9. Losing:
° The game ends if the snake collides with a wall, itself, or an obstacle .
<> A game over message is displayed with your final score, and a game over sound plays .
Remember, the key to success is strategic movement, avoiding obstacles, and growing the
snake by consuming food. As the game progresses, the challenge increases, making it an
engaging and entertaining experience .
Play Again
import tkinter as tk
from tkinter import messagebox
import random
class MemoryPuzzle:
def_ init_ (self, root, rows=6, columns=6):
self.root = root
self.root.titlef'Memory Puzzle")
self.rows = rows
self.columns = columns
self.tiles = [i for i in range(l, (rows * columns) // 2 + 1)] * 2
random.shuffle(self.tiles)
self.buttons = []
self.create_buttons()
self.first_click = None
self.moves = 0
def reset_game(self):
# Reset the game by destroying the current window and creating a new one
self.root.destroyO
new_root = tk.Tk()
new_game = MemoryPuzzle(new_root, rows=6, columns=6)
new_root.mainloop()
def show_game_over_message(self):
messagebox.showinfo(
"Game Over", f'Congratulations! You won in {self.moves} moves.")
def center_window(self):
# Calculate the center position on the screen
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
x_position = (screen_width - self.initial_width) // 2
y_position = (screen_height - self.initial_height) // 2
self.root.geometry(
f'{self.initial_width}x{self.initial_height} + {x_position} + {y_position}")
This Python script uses the Tkinter library to create a simple memory puzzle game . Let's
go through the code step by step :
1. Importing Libraries :
Python Code
import tkinter as tk
from tkinter import messagebox
import random
» tkinter : GUI library used for creating the graphical interface .
2. MemoryPuzzle Class:
Python Code
class MemoryPuzzle :
def__init_ ( self, root, rows = 6, columns = 6 ):
# Initialization method for the MemoryPuzzle class .
# Takes the Tkinter root window and optional rows and columns
parameters .
# Set the initial form width and height, and center the window .
self. initial_width = 350
self. initial_height = 350
self. center_window ()
parameters .
• Create_buttons : Creates buttons for the game grid and the " Play Again " button .
o flip_tile: Handles the click event for each tile, flipping it and checking for matches .
• check_match : Compares the values of two clicked tiles and updates the game accordingly
- reset_game : Destroys the current window and creates a new one to reset the game .
3. Main Section:
Python Code
if_ name_ == "_ main_
root = tk . Tk ()
game = MemoryPuzzle ( root, rows = 6, columns = 6 )
root. mainloop ()
° Checks if the script is being run as the main module .
• Creates the Tkinter root window and initializes the MemoryPuzzle game .
» The goal is to find matching pairs by clicking on two buttons with the same value .
• The game provides feedback on successful matches and displays a " Game Over "
Note : The game window is initially centered on the screen, and the " Play Again " button
allows the player to restart the game after completing it.
How To Play Memory Puzzle Game
The Memory Puzzle game is a classic memory matching game where the player needs to
find matching pairs of tiles . Here's a step - by - step guide on how to play the Memory
Puzzle game:
1. Objective:
o The goal of the game is to match all pairs of tiles .
2. Game Setup:
° When you start the game, a grid of face - down tiles is displayed on the screen .
3. Game Mechanics:
• Click on a tile to reveal its value .
° If the values of the two revealed tiles match, they stay face - up, and you score a point.
° If the values do not match, the tiles are flipped face - down again .
5. Strategy:
° The key to success is to remember the positions of the tiles and match them efficiently .
° Use your memory to recall where different values are located in the grid .
6. Game Progress:
” The game keeps track of the number of moves you make .
° Once all pairs are matched, a " Game Over " message will be displayed, showing the
game window.
• This will reset the game, shuffle the tiles, and allow you to start a new game .
9. Have Fun:
o Enjoy the process of testing and improving your memory skills .
Remember, the Memory Puzzle game is not only entertaining but also a great exercise for
your memory and concentration . Good luck, and have fun playing !
8. Quiz Game
/ Quiz Game
Question 5
What is the capital of Japan?
C Beijing
C Seoul
• Tokyo
•' Bangkok
Next
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
import time
class QuizGame:
def_ init_ (self, root):
self.root = root
self.root.title("Quiz Game")
self.root.geometry("600x450")
self.root.attributesC-topmost1, True)
self.current.question = 0
self.score = 0
self.timer_seconds =10
self.timer_label = None
self.progress_bar = None
self.questions =
self.create_widgets()
def center_window(self):
self.root.update_idletasks()
window_width = self.root.winfo_width()
window_height = self.root.winfo_height()
position_left = int(
self.root.winfo_screenwidth() / 2 - window_width / 2)
position_top = int(self.root.winfo_screenheight() /
2 - window_height / 2)
selfToot.geometry(f'+{positionJeft} + {position_top}")
def create_widgets(self):
self.title_label = tk.Label(
self.root, text="Quiz Game", font=("Helvetica", 18, "bold"))
self.title_label.pack(pady= 10)
self.label_question = tk.Label(
self.root, text="", font=("Helvetica", 12))
self.label_question.pack(pady = 10)
self.var.option = tk.StringVar()
self.option_buttons = []
for option in self.questions[self.current_question]["options"]:
radio_button = tk.Radiobutton(
self.root, text=option, variable=self. var_option, value=option, font=("Helvetica", 10))
self.option_buttons.append(radio_button)
radio_button.pack()
self.btn_next = tk.Button(
self.root, text="Next", command=self.next_question, font=("Helvetica", 12))
self.btn_next.pack(side=tk.BOTTOM, pady=20)
self.timer_label = tk.Label(
self.root, text=f"Time left: {self.timer_seconds} seconds", font=("Helvetica", 10))
self.timer_label.pack()
self.progress_bar = ttk.Progressbar(
self.root, length=200, mode="determinate")
self.progress_bar.pack(pady= 10)
self.update_question()
self.start_timer()
def next_question(self):
user_answer = self.var_option.get()
if user_answer == self.questions[self.current_question]["correct_answer"]:
self.score + = 1
self.current.question + = 1
def update_question(self):
self.title_label.config(text=f'Question {self.current.question + 1}")
self.label_question.config(
text=self.questions[self.current_question]["question"])
self.var_option.set(None)
for button in self.option.buttons:
button.destroyO
self.option_buttons = []
for option in self.questions[self.current_question]["options"]:
radio_button = tk.Radiobutton(
self.root, text=option, variable=self.var_option, value=option, font=("Helvetica", 10))
self.option_buttons.append(radio_button)
radio_button.pack()
def start_timer(self):
self.timer_label.config(text=f'Time left: {self.timer_seconds} seconds")
self.progress_bar["value"] = 100 # Reset progress bar
self.update_timer()
def update_timer(self):
if self.current_question < len(self.questions):
self.timer_seconds -= 1
self.timer_label.config(text=f'Time left: {self.timer_seconds} seconds")
self.progress_bar["value"] = (self.timer.seconds / 10) * 100
if self.timer_seconds >= 0:
# Increase the delay to slow down the progress bar
self.root.after(6000, self.update_timer)
else:
self.next_question()
def show_result(self):
result_text = f'You scored {self.score} out of {len(self.questions)}!"
messagebox.showinfo("Quiz Completed", result-text)
#self.root.destroy()
This is a simple quiz game implemented using the Tkinter library in Python . Let's break
down the code and understand each part in detail:
1. Importing Libraries :
Python Code
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
import time
< • tkinter : This is the standard GUI ( Graphical User Interface ) toolkit that comes with
Python .
• messagebox : Provides a set of convenience functions for creating standard modal dialogs .
• ttk : Themed Tkinter, which provides access to the Tk themed widget set.
2. QuizGame Class:
Python Code
class QuizGame :
- This class encapsulates the entire quiz game .
3. Initializer (_ init_ ):
Python Code
def__init_ ( self, root):
«• Initializes the QuizGame class with the given TOOt Tkinter window .
4. Window Configuration:
° Sets up the basic configuration for the Tkinter window, including title, size, and position .
- initializes variablescurrent_question,
like score, timer_seconds,
timer_label, and progress_bar .
5. List of Questions :
Python Code
self. questions =[...]
Contains a list of dictionaries, where each dictionary represents a question with its options and
correct answer .
6. create.widgets Method:
° Configures and creates various widgets ( GUI components ) such as labels, radio
- Calls update_question and Start—timer to initialize the first question and start
the timer.
7. center_window Method:
° Centers the Tkinter window on the screen .
8. next_question Method:
• Handles the logic for moving to the next question .
o Checks if the user's answer is correct, updates the score, and moves to the next question .
9. update_question Method:
» Updates the GUI with the current question and its options .
° Calls itself recursively with a delay using after method until the timer reaches zero .
This implementation provides a simple interactive quiz game with a countdown timer
for each question and a final score display at the end. Players can answer questions by
selecting options, and the game keeps track of their score .
quiz_game . py).
” Open a terminal or command prompt.
Code
python quiz_game . py
2. This will launch the quiz game window .
3. Answering Questions:
• The quiz game window will display the first question and multiple - choice options .
• Click on the radio button next to the answer you think is correct.
4. Next Question:
° Click the " Next " button to move to the next question .
5. Timer Countdown :
Pay attention to the timer label and progress bar .
6. Scoring:
o Your score increases when you select the correct answer .
7. End of Quiz :
•» After answering all the questions, a message box will appear with your final score .
9. Note:
• The quiz game has a set of predefined questions and answers . If you want to customize
the quiz content, you can modify the self. questions list in the script.
9. 2048 Game
Vi 2048 Game
import pygame
import random
# Initialize pygame
pygame.init()
# Constants
GRID_SIZE = 4
TILE_SIZE = 100
GRID-MARGIN = 10
SCREEN-SIZE = (GRID-SIZE * TILE.SIZE + (GRID-SIZE + 1) * GRID-MARGIN,
GRID_SIZE * TILE_SIZE + (GRID-SIZE + 1) * GRID-MARGIN)
BACKGROUND-COLOR = (187, 173,160)
GRID-COLOR = (205, 193, 180)
FONT-COLOR = (255, 255, 255)
# Initialize screen
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("2048 Game")
# Fonts
font = pygame.font.Font(None, 36)
def draw_grid():
for row in range(GRID_SIZE):
for col in range(GRID_SIZE):
pygame.draw.rect(screen, GRID_COLOR, [
(GRID_MARGIN + TILE_SIZE) * col + GRID-MARGIN,
(GRID-MARGIN + TILE_SIZE) * row + GRID-MARGIN,
TILE_SIZE,
TILE SIZE
1)
def draw_tiles(grid):
for row in range(GRID_SIZE):
for col in range(GRID_SIZE):
value = grid[row][col]
if value != 0:
pygame.draw.rect(screen, TILE_COLORS[value], [
(GRID.MARGIN + TILE.SIZE) * col + GRID-MARGIN,
(GRID-MARGIN + TILE.SIZE) * row + GRID-MARGIN,
TILE_SIZE,
TILE_SIZE
def generate_tile(grid):
empty_cells = [(row, col) for row in range(GRID_SIZE)
for col in range(GRID_SIZE) if grid[row][col] == 0]
if empty_cells:
row, col = random.choice(empty_cells)
grid[row][col] = random.choice([2,4])
ef move_tiles(grid, direction):
# Transpose the grid for easier handling of rows and columns
if direction == 'left':
grid = [list(row) for row in zip(*grid)]
elif direction == 'up':
grid = [list(col) for col in grid[::-1 ]]
elif direction == 'down':
grid = [list(col[::-1 ]) for col in grid]
return grid
def is_game_over(grid):
for row in grid:
if 0 in row or any(row[i] == row[i + 1] for i in range(GRID_SIZE -1)):
return False
for col in zip(*grid):
if any(col[i] == col[i + 1] for i in range(GRID_SIZE -1)):
return False
return True
def game_over_screen():
screen.mi(BACKGROUND_COLOR)
game_over_text = font.render("Game Over!", True, FONT_COLOR)
text_rect = game_over_text.get_rect(
center=(SCREEN_SIZE[O] // 2, SCREEN_SIZE[1] // 2 - 30))
screen.blit(game_over_text, text.rect)
restart_text = font.render("Press R to Restart", True, FONT_COLOR)
text_rect = restart_text.get_rect(
center=(SCREEN_SIZE[O] 11 2, SCREEN_SIZE[1] // 2 + 30))
screen.blit(restart_text, text_rect)
pygame.display.flipO
def display_high_score(high_score):
high_score_text = font.render(
f 'High Score: {high_score}", True, FONT_COLOR)
screen.blit(high_score_text, (GRID_MARGIN,
SCREEN SIZE[1] - GRID-MARGIN - 60))
screen.blit(text, text.rect)
draw_animated_tiles(grid, animation_progress)
pygame.display.flipO
pygame.time.delay(ANIMATION_SPEED)
return grid
return current-grid
running = True
game_over = False
game_won = False
score = 0
high_score = 0
state_stack = [([row[:] for row in grid], score, high_score)]
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if not game_over and not game_won:
if event.key == pygame.K_LEFT:
state_stack.append(
([row[:] for row in grid], score, high_score))
grid = move_animated_tiles(grid, 'left', 0)
grid = move_tiles(grid, 'left')
if grid != state_stack[-l][O]:
generate_tile(grid)
score += calculate_score(state_stack[-l][0], grid)
grid = animateJ:ile_movement(
state_stack[-l][O], grid, 'left', score, high_score)
elif event.key == pygame.K_RIGHT:
state_stack.append(
([row[:] for row in grid], score, high_score))
grid = move_animated_tiles(grid, 'right', 0)
grid = move_tiles(grid, 'right')
if grid != state_stack[-l][O]:
generate_tile(grid)
score += calculate_score(state_stack[-l][0], grid)
elif event.key == pygame.KJUP:
state_stack.append(
([row[:] for row in grid], score, high_score))
grid = move_animated_tiles(grid, 'up', 0)
grid = move_tiles(grid, 'up')
if grid != state_stack[-l][O]:
generate_tile(grid)
score += calculate_score(state_stack[-l][0], grid)
elif event.key == pygame.KJDOWN:
state_stack.append(
([row[:] for row in grid], score, high_score))
grid = move_animated_tiles(grid, 'down', 0)
grid = move_tiles(grid, 'down')
if grid != state_stack[-l][O]:
generate_tile(grid)
score += calculate_score(state_stack[-l][0], grid)
elif event.key == pygame.K.r:
grid = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
generate_tile(grid)
generate_tile(grid)
game_over = False
game.won = False
if score > high_score:
high_score = score
score = 0
state_stack = [
([row[:] for row in grid], score, high_score)]
elif event.key == pygame.K.u and len(state_stack) > 1:
grid, score, high_score = undo_move(state_stack)
# Additional update to reflect the undone move
game_over = False
game_won = False
if is_game_over(grid):
game_over = True
if score > high_score:
high_score = score
game_over_screen()
pygame.quitQ
This Python script implements a simple version of the popular game "2048 " using the
Pygame library. The game involves sliding numbered tiles on a 4x4 grid, merging tiles
with the same number when they collide, and aiming to reach the tile with the number
2048 .
Let's break down the key components and functionalities of the script:
Pygame Initialization:
• The script starts by importing the Pygame library and initializing it.
Python Code
import pygame
Constants and Configuration:
• Various constants and configurations are set for the game, including grid size, tile size, colors, fonts,
animation speed, winning condition, and color themes .
Python Code
GRID_SIZE = 4
TILE_SIZE = 100
GRID-MARGIN =10
SCREEN-SIZE = ( GRID.SIZE * TILE_SIZE + ( GRID.SIZE + 1 ) * GRID-MARGIN,
GRID_SIZE * TILE_SIZE + ( GRID.SIZE + 1 ) * GRID.MARGIN )
BACKGROUND-COLOR =( 187,173,160 )
GRID_COLOR = ( 205, 193, 180 )
FONT_COLOR = ( 255, 255, 255 )
# ... other constants ...
Pygame Screen Initialization:
• The Pygame screen is initialized with the specified size and a caption .
Python Code
screen = pygame . display. set_mode ( SCREEN_SIZE )
pygame . display. set_caption (" 2048 Game ")
Grid and Tile Drawing:
• Functions for drawing the grid and tiles on the screen are defined .
Python Code
def draw_grid ():
# Draws the grid on the screen
Python Code
TILE_COLORS = {
# ... tile colors based on their values ...
COLOR-THEMES = {
'default': TILE COLORS,
'dark': {
# ... colors for a dark theme ...
Tile Movement and Animation:
• Functions for moving tiles in different directions, generating new tiles, and handling animations are
defined.
Python Code
def move_tiles (grid, direction):
# Moves the tiles in the specified direction
Python Code
defis_game_over (grid):
# Checks if the game is over
Python Code
def undo_move ( state_stack):
# Undoes the last move
Python Code
if_ name_ =="_ main_
main ()
Overall, this script provides a functional implementation of the 2048 game with basic
features and Pygame for handling graphics and user input. Players can move tiles, merge
them, achieve a winning condition, and restart the game .
° Two tiles with a value of either 2 or 4 are randomly placed on the grid .
2. Controls:
” You can control the movement of tiles using the arrow keys on your keyboard .
• Press the left arrow key to move all tiles to the left.
< • Press the right arrow key to move all tiles to the right.
< > Press the down arrow key to move all tiles downwards .
3. Gameplay:
o Tiles with the same value can be merged into a single tile by moving them towards each
other.
° When you make a move, a new tile with a value of 2 or 4 will appear in an empty spot.
* The goal is to keep merging tiles to create larger values and reach the tile with a value of
2048 .
•> The game continues until you either reach the 2048 tile ( winning the game ) or the grid
4. Scoring:
” Your score is based on the values of the tiles you merge .
° Each time two tiles are merged, the value of the resulting tile is added to your score .
5. Special Features:
• The game includes a winning condition where reaching the 2048 tile displays a victory
screen.
’ There is an undo feature ( press the U key ) that allows you to undo your last move .
6. Game Over:
° The game ends when you reach the 2048 tile, displaying a victory screen .
o If the grid is full and no more moves are possible, the game ends, and a game over screen
is displayed .
• You can restart the game at any time by pressing the R key .
7. High Score:
*> The game keeps track of the highest score achieved during the session .
8. Additional Details:
° The grid and tiles are displayed using the Pygame library, and the game provides a
graphical interface .
Overall, the 2048 game involves strategic thinking, planning your moves, and aiming to
create the largest possible tiles to achieve the highest score . It's a simple yet challenging
puzzle game that requires both skill and a bit of luck .
class BlackjackGame:
def__ init_ (self, master):
self.master = master
self.master.title("Blackjack")
self.deck = self.get_deck()
self.player.hand = []
self.dealer.hand = []
self.player.balance = 1OOO # Initial balance
self.create_widgets()
def get_deck(self):
suits = ['Hearts’, 'Diamonds', 'Clubs', ’Spades1]
ranks = ['2','3', '4','5','6','7',
'8','9','10', 'J', 'O', 'K','A']
deck = [{'suit': suit, 'rank': rank]
for suit in suits for rank in ranks]
random.shuffle(deck)
return deck
self.deal_card(self.player_hand)
self.update_display()
player_score = self.calculate_score(self.player_hand)
if player_score >21:
self.end_game("You went over. You lose!")
def dealer_play(self):
while self.calculate_score(self.dealer_hand) <17:
self.deal_card(self.dealer_hand)
self.update_display()
player_score = self.calculate_score(self.player_hand)
dealer_score = self.calculate_score(self.dealer_hand)
def restart_game(self):
self.deck = self.get_deck()
self.player_hand.clear()
self.dealer_hand.clear()
self.player_canvas.delete("all")
self.dealer_canvas.delete("all")
def update_display(self):
self.update_player_hand()
self.update_dealer_hand()
self.update_score() # Update score label after each action
def update_player_hand(self):
self.player_canvas.delete("aH")
for card in self.player.hand:
img_path = f'C:/Users/Suchat/Playing Cards/Playing Cards/PNG-cards-l.S/fcardfrank'B-OfJcardl'suit'B.png"
self._display_card(img_path, 50, 200, self.player.canvas, self.player_card_images)
def update_dealer_hand(self):
self.dealer_canvas.delete("aU")
for card in self.dealer_hand:
img_path = f'C:/Users/Suchat/Playing Cards/Playing Cards/PNG-cards-1.3/{card['rank']}_of_{card['suit']}
self._display_card(img_path, 50, 50, self.dealer_canvas, self.dealer_card_images)
def update_score(self):
self.score_label.config(text=f'Balance: ${self.player_balance}")
def create_widgets(self):
self.playerjiand = [self.deal_card(
self.player_hand), self.deal_card(self.player_hand)]
self.dealer_hand = [self.deal_card(
self.dealer.hand), self.deal_card(self.dealer_hand)]
self.player.canvas = tk.Canvas(
self.master, width=600, height=300, bg="green")
self.player_canvas.pack()
self.dealer.canvas = tk.Canvas(
self.master, width=600, height=300, bg="green")
self.dealer_canvas.pack()
self.hit_button = tk.Button(
self.master, text="Hit", command=self.player_hit)
self.hit_button.pack(side=tk.LEFT, padx= 10)
self.stand_button = tk.Button(
self.master, text="Stand", command=self.dealer_play)
self.stand_button.pack(side=tk.RIGHT, padx= 10)
self.restart_button = tk.Button(
self.master, text="Restart", command=self.restart_game)
self.restart_button.pack(side=tk.BOTTOM, pady= 10)
self.score.label = tk.Label(
self.master, text=f Balance: ${self.player_balance}")
self.score_label.pack(side=tk.BOTTOM)
self.update_display()
def main():
root = tk.Tk()
game = BlackjackGame(root)
root.mainloopO
if_ name_ == "__ main_
main()
This Python script uses the tkinter library to create a simple graphical user interface ( GUI)
for a Blackjack game . Let's go through the details of the script:
Import Statements:
Python Code
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
import random
• tkinter : The main library for creating the GUI.
• Image and ImageTk from the PIL ( Pillow ) library for working with images .
BlackjackGame Class:
Python Code
class BlackjackGame :
def__init_ ( self, master):
# Initialization method
# Initialize the main window and set the title
self. master = master
self, master. title (" Blackjack")
Overall Flow:
1. The game starts with an initial deck, player hand, and dealer hand .
5. When the game ends, a message box is displayed with the result.
6. Player can restart the game for a new round .
The game combines basic Blackjack logic with a simple GUI for user interaction .
♦ The game starts by creating an instance of the BlackjackGame class in the main
function .
* The get_deck method creates a standard deck of 52 playing cards, shuffles it, and
* The player and dealer hands are initialized with two cards each .
Python Code
self. deck = self. get_deck ()
self. player_hand = [ self. deal_card ( self. player_hand),
self. deal_card ( self. player_hand)]
self. dealer_hand = [ self. deaLcard ( self. dealer_hand),
self. deaLcard ( self. dealer_hand)]
3. Game Logic:
The deaLcard method deals a card from the deck to a specified hand .
• The calculate_score method calculates the total score of a given hand, considering the
- The player_hit method handles player actions when they choose to hit, updating the
Python Code
def player_hit ( self):
# ... ( disabled hit button during execution)
self. deal_card ( self. player_hand)
self. update_display ()
player_score = self. calculate_score ( self. player_hand)
if player_score >21:
self. end_game (" You went over . You lose !")
# ... ( checking for blackjack)
elif player_score <=21:
# ... ( enabled hit button after execution if the score is still under 21)
4. End Game Conditions :
• The end_game method updates the player's balance based on win / loss conditions and
Python Code
def end_game ( self, message ):
# ... ( deduct 100 from balance when losing)
messagebox . showinfo (" Game Over ", message + f " \nYour balance : $
{self. player_balance}")
self. update_score ()
5. Dealer's Turn
- The dealer_play method handles the dealer's turn, drawing cards until their score is at
least 17 .
• It compares the final scores of the player and dealer to determine the game outcome .
Python Code
defdealer_play (self):
# ... ( dealer draws cards until score is at least 17 )
if dealer_score > 21 or dealer_score < player_score :
self. end_game (" You win !")
self. player_balance += 100
elif dealer_score > player_score :
self. end_game (" You lose !")
self. player_balance -= 100
else :
self. end_game (" It's a draw !")
6. Restarting the Game :
<• The restart_game method resets the game state, including the deck, hands, and player
balance.
Python Code
defrestart_game ( self):
# ... (resetting game state )
self. update_display ()
7. GUI Elements :
<• The GUI elements include two canvases for displaying player and dealer cards, " Hit " and
" Stand " buttons for player actions, a " Restart " button, and a label showing the player's
balance.
Python Code
self. player_canvas = tk . Canvas ( self, master, width = 600, height = 300, bg =" green ")
# ... ( similarly for dealer_canvas, hit_button, stand_button, restart_button, score_label)
8. Card Display:
° The _display_card method handles the display of card images on the canvases .
Python Code
def _display_card ( self, img_path, x, y, canvas, card_images = None ):
# ... ( opens and resizes the image, creates a Tkinter PhotoImage, and displays it on the
canvas)
9. Updating the Display :
’ The update_display method updates the player and dealer hands, as well as the score
Python Code
defupdate_display (self):
self. update_player_hand ()
self. update_dealer_hand ()
self. update_score ()
10. Card Images:
o The card images are loaded from PNG files, and their paths are generated based on the
card's rank and suit.
Python Code
img_path = f " C :/ Users / Suchat / Playing Cards / Playing Cards / PNG - cards -1.3/
{card [ 'rank' ] }_of_{card [ 'suit' ]}. png"
To play the game :
• Run the script.
• Click the " Stand " button to end the player's turn and let the dealer play .
• The game automatically determines the winner and updates the balance .
• Click the " Restart" button to start a new game with a fresh deck .
Note : Ensure that the file paths for the card images are correct, and the image files are
available in the specified directory .
import tkinter as tk
import random
class SudokuSolverGUI:
def__ init_ (self, master):
self.master = master
self.master.title("Sudoku Solver")
self.grid_size = 9
self.cells = [[tk.StringVar() for _ in range(self.grid_size)]
for _ in range(self.grid_size)]
# Error highlighting
row, col = self.get_cell_position(event.widget)
num = int(event.char) if event.char.isdigitQ else 0
if not self.is_valid_move(row, col, num):
event.widget.config(fg='red')
else:
event.widget.config(fg='black')
def clear_grid(self):
# Clear all values in the grid
for i in range(self.grid_size):
for j in range(self.grid_size):
self.cells[i][j].set("")
# Instead of using config on StringVar, change the text color of Entry widget directly
self.get_entry_widget(i, j).config(
fg='black') # Reset text color
def solve_sudoku(self):
# Extract values from the GUI grid to create a Sudoku board
board = [[0] * self.grid.size for _ in range(self.grid_size)]
for i in range(self.grid_size):
for j in range(self.grid_size):
value = self.cells[i][j].get()
if value.isdigitO and int(value) in range(l, 10):
board[i][j] = int(value)
if self.solve_sudoku_backtracking(board):
# Update the GUI with the solved Sudoku
for i in range(self.grid_size):
for j in range(self.grid_size):
self.cells[i][j].set(str(board[i][j]))
# Instead of using config on StringVar, change the text color of Entry widget directly
self.get_entry_widget(i, j).config(
fg='black') # Reset text color
else:
printf'No solution found.")
if not empty_cell:
return True
if self.solve_sudoku_backtracking(board):
return True
board[row][col] = 0
return False
def generate_sudoku_puzzle(self):
# Implement the logic to generate a new Sudoku puzzle
# For simplicity, let's use a backtracking algorithm to fill in the board
self.clear_grid()
• import random : This imports the random module, which will be used for generating random
Python Code
class SudokuSolverGUI:
def_ init_ ( self, master):
self. master = master
self. master. title (" Sudoku Solver")
self. grid_size = 9
self. cells = [[ tk . StringVar () for _ in range ( self. grid_size )]
for _ in range ( self. grid_size )]
• class SudokuSolverGUI :: This defines a class named SudokuSolverGUI.
• def__init ( self, master ): : This is the constructor method for the class . It initializes the class
instance with the given master widget ( typically the root window of the GUI ).
Solver ".
• self. grid_size = 9: This sets the grid size for the Sudoku board to 9x9 .
Python Code
# Create the GUI grid
for i in range ( self. grid_size ):
for j in range ( self. grid_size ):
cell_entry = tk . Entry ( master, width = 3, font =(
'Arial', 16 ), textvariable = self. cells [ i ][ j ])
cell_entry. grid ( row = i, column = j)
cell_entry. bind ('< KeyRelease >', lambda event,
i = i, j = j: self. update_entry_color ( event, i, j))
• This loop iterates over each cell in the Sudoku grid and creates an Entry widget for each cell.
• tk . Entry ( master, width = 3, font =( 'Arial', 16 ), textvariable = self, cells [ i ]
[ j ]) : This creates an Entry widget with a width of 3 characters, using the Arial font with size 16, and
associates it with a corresponding StringVar object from the self. cells list.
• cell_entry . grid ( row = i, column = j ) : This places the Entry widget in the grid layout at the
Python Code
# Create Solve button
solve_button = tk . Button ( master, text =" Solve ",
command = self. solve_sudoku)
solve_button . grid ( row = self. grid_size, columnspan = self. grid_size )
• This creates a " Solve" button widget using the tk . Button class, which calls the solve_sudoku
method when clicked.
• solve_button . grid (row = self. grid_size, columnspan = self. grid_size ): This
places the Solve button in the grid layout, spanning across the entire bottom row of the grid .
Python Code
# Create Clear button
clear_button = tk . Button ( master, text =" Clear", command = self. clear_grid)
clear_button . grid (row = self. grid_size + 1, columnspan = self. grid_size )
• This creates a " Clear " button widget using the tk . Button class, which calls the clear_grid
method when clicked.
Python Code
# Create Generate button
generate_button = tk . Button (
master, text =" Generate ", command = self. generate_board)
generate_button . grid (row = self. grid_size + 2, columnspan = self. grid_size )
• This creates a " Generate" button widget using the tk . Button class, which calls the
This covers the initialization and setup of the GUI components in the SudokuSolverGUI
class .
° Copy the provided Python Code into a file, save it with a . py extension, and run the
script.
• This will open a graphical window with the Sudoku Solver game .
° Click the " Solve " button to let the program solve the puzzle . The solved puzzle will be
5. Generating a Puzzle :
° Click the " Generate " button to create a new Sudoku puzzle . The program will generate
6. Input Validation:
o The program validates your input. If you enter an invalid number ( e . g . , a number
outside the range of 1 to 9 ) or if the entered number violates the rules of Sudoku, the
7. Error Highlighting:
o As you input numbers, the program checks for errors and highlights the text in red if
there's a conflict in the current row, column, or 3x3 box .
8. Closing the Game :
• Close the game window when you're done playing .
Remember, the Sudoku Solver game is designed to allow you to solve existing puzzles, clear
the grid to create new ones, and enjoy the process of solving Sudoku puzzles interactively .
You can experiment with different puzzles and observe how the backtracking algorithm
efficiently solves them.
class ConnectFour:
def__ init_ (self, vs_ai=False):
self.window = tk.Tk()
self.window.title("Connect Four")
self.player_names - ["Player 1", "Player 2"]
self.scores = [0, 0]
self.vs_ai = vs_ai
self.board = [[0] * 7 for _ in range(6)]
self.current_player = 1
self.create_widgets()
self.window.mainloopO
def create_widgets(self):
self.buttons = [[None] * 7 for _ in range(6)]
self.player.label = tk.Label(
self.window, text=f'Current Player: {self.player_names[self.current_player-l]}")
self.player_label.grid(row=6, columnspan=7)
self.score.label = tk.Label(
self.window, text=f'Scores: {self.scores[0]} - {self.scores[l]}")
self.score_label.grid(row=7, columnspan=7)
restart_button = tk.Button(
self.window, text="Restart", command=self.reset_game)
rest art_button.grid(ro w=8, columnspan=7)
fori in range(l,4):
r, c = row + i * dr, col + i * de
fori in range(l,4):
r, c = row - i * dr, col - i * de
if count >= 4:
return True
return False
def switch_player(self):
self.current_player = 3 - self.current.player # Switch player between 1 and 2
self.player_label.config(
text=P'Current Player: {self.player_names[self.current_player-1 ]}")
def reset_game(self):
for row in range(6):
for col in range(7):
self.buttons[row][col].config(text="", state=tk.NORMAL)
self.board[row][col] = 0
self.current_player = 1
self.player_label.config(
text=fCurrent Player: {self.player_names[self.current_player-l]}")
def update_score_label(self):
self.score_label.config(
text=f Scores: {self.scores[0]} - {self.scores[l]}")
def ai_drop_piece(self):
valid_moves = [(r, c) for r in range(6)
for c in range(7) if self.board[r][c] == 0]
if valid_moves:
row, col = random.choice(valid_moves)
self.board[row] [col] = self.current_player
self.update_button_text(row, col)
if self.check_winner(row, col):
messagebox.showinfo(
"Winner!", f'Player {self.current_player} wins’")
self.scores[self.current_player - 1] + = 1
self.update_score_label()
self.reset_game()
name ____ H
main
# Set vs_ai to False for two-player mode, or True for single-player vs Al mode
ConnectFour(vs_ai=True)
against an Al.
Python Code
self. window = tk . Tk ()
self. window. title (" Connect Four ")
Creates the main window for the game using Tkinter, with the title " Connect Four
Python Code
self. player_names = [" Player 1 ", " Player 2 "]
self, scores = [ 0,0 ]
• Initializes a list of player names and a list to store the scores .
Python Code
self. vs_ai = vs_ai
• Stores the value of VS_ai in the class instance, determining whether the game is played against an Al
or another player .
Python Code
self. board = [[ 0 ] * 7 for _ in range ( 6 )]
• Initializes a 6x7 game board represented as a list of lists, where each element is initialized to 0 .
Python Code
self. current_player = 1
• Sets the initial player to Player 1 .
Python Code
self. create_widgets ()
self. window. mainloop ()
• Calls the create_widgetS method to set up the GUI components and starts the Tkinter event loop .
Python Code
def create,widgets ( self):
• Defines a method to create the GUI components of the game .
Python Code
self. buttons = [[ None ] * 7 for _ in range ( 6 )]
• Initializes a 2D list Self. buttons to store the button widgets in the GUI.
Python Code
for row in range ( 6 ):
for col in range ( 7 ):
self, buttons [ row ][ col ] = tk . Button ( self, window, text ="", width = 5,
height = 2,
command = lambdar = row, c = col:
self. drop_piece ( r, c ))
self. buttons [ row ][ col ]. grid ( row = row, column = col)
• Creates a 6x7 grid ofbuttons, where each button is associated with the drop_piece method using the
command parameter . The buttons are displayed in the Tkinter window using the grid method .
Python Code
self. player_label = tk . Label (
self. window, text = f " Current Player :
{self. player_names [ self. current_player - 1 ]}")
self. player_label. grid ( row = 6, columnspan = 7 )
• Creates a label to display the current player's turn and places it at the bottom of the window .
Python Code
self. score_label = tk . Label (
self. window, text = f " Scores : {self. scores [ 0 ]} - {self. scores [ 1 ] } ")
self. score_label. grid (row = 7, columnspan = 7 )
• Creates a label to display the scores and places it below the player label.
Python Code
restart_button = tk . Button (
self, window, text =" Restart", command = self. reset_game )
restart_button . grid ( row = 8, columnspan = 7 )
• Creates a restart button and associates it with the reset_game method .
Python Code
def drop_piece ( self, row, col):
• Defines the drop_piece method, which is called when a player clicks a button to drop a game piece .
Python Code
if self, board [ row ][ col ] = = 0 :
self, board [ row ][ col ] = self. current_player
self. update_button_text ( row, col)
• Checks if the selected cell is empty, then updates the game board and button text with the current
player's move .
Python Code
if self. check_winner ( row, col):
messagebox. showinfo (
" Winner !", f " Player {self. current_player] wins !")
self. scores [ self. current_player - 1 ] + = 1
self. update_score_label ()
self. reset_game ()
Checks if the current move results in a win . If so, displays a message box, updates the scores, and resets
the game .
Python Code
else:
if not self. vs_ai:
self. switch_player ()
else :
self. ai_drop_piece ()
self. switch_player ()
• If the game is not against an Al, switches to the next player . Otherwise, the Al makes a move, and then
Python Code
def update_button_text ( self, row, col):
• Defines a method to update the button text with the player's symbol.
Python Code
player_symbol = " X" if self. current_player = = 1 else" O "
self, buttons [ row ][ col ]. config (text = player_symbol, state = tk . DISABLED )
• Determines the player's symbol based on the current player and updates the button text. Disables the
Python Code
def check_winner ( self, row, col):
• Defines the check_winner method to determine if a player has won the game .
Python Code
directions = [( 0,1 ), (1,0), (1,1), (-1,1)]
• Defines four possible directions to check for winning combinations I right, down, diagonal right, and
diagonal left.
Python Code
for dr, de in directions :
count = 1 # Number of consecutive pieces in the current direction
• Iterates through each direction and initializes a counter for consecutive pieces .
Python Code
fori in range ( 1,4):
r, c = row + i * dr, col + i * de
if 0< = r < 6 and 0< = c < 7 and self. board [ r ][ c ] = = self. current_player :
count += 1
else :
break
• Checks for consecutive pieces in the positive direction of the current direction .
Python Code
fori in range ( 1, 4 ):
r, c = row - i * dr, col - i * de
if 0< = r < 6 and 0< = c < 7 and self. board [ r ][ c ] = = self. current_player :
count += 1
else :
break
• Checks for consecutive pieces in the negative direction of the current direction .
Python Code
if count > = 4 :
return True
• If there are four or more consecutive pieces in any direction, the player wins .
Python Code
return False
• If no winning combination is found, returns False .
Python Code
def switch_player ( self):
• Defines the S witch_player method to switch between players .
Python Code
self. current_player = 3 - self. current_player # Switch player between 1 and 2
self. player_label. config (
text = f " Current Player : {self. player_names [ self. current_player - 1 ]}")
• Toggles between players 1 and 2 and updates the player label accordingly .
Python Code
defreset_game ( self):
Defines the reset_game method to reset the game board and player turns .
Python Code
for row in range ( 6 ):
for col in range ( 7 ):
self. buttons [ row ][ col ]. config (text ="", state = tk . NORMAL )
self. board [ row ] [ col ] = 0
self. current_player = 1
self. player_label. config (
text = f " Current Player : {self. player_names [ self. current_player - 1 ]}")
• Clears the button texts, enables the buttons, resets the game board, sets the current player to 1, and
updates the player label.
Python Code
def update_score_label (self):
• Defines the Update_SCOre_label method to update the displayed scores .
Python Code
self. score_label. config (
text = f " Scores : {self, scores [ 0 ]} - {self, scores [ 1 ]}")
• Updates the score label with the current scores .
Python Code
defai_drop_piece ( self):
• Defines the ai_drop_piece method for the Al to make a move .
Python Code
valid_moves = [( r, c) for r in range ( 6 )
for c in range ( 7 ) if self. board [ r ][ c ] = = 0 ]
• Creates a list of valid moves ( empty cells ) for the Al to choose from .
Python Code
if valid_moves :
row, col = random . choice (valid_moves )
self. board [ row ][ col ] = self. current_player
self. update_button_text (row, col)
• If there are valid moves, the Al randomly selects a move, updates the game board, and updates the button
text.
Python Code
if self. check_winner (row, col):
messagebox. showinfo (
" Winner !", f " Player {self. current_player} wins !")
self. scores [ self. current_player - 1 ] + = 1
self. update_score_label ()
self. reset_game ()
• Checks if the Al move results in a win and handles the game outcome accordingly .
Python Code
if_ name_ == "_ main_
ConnectFour (vs_ai = True )
If the script is run as the main program, it creates an instance of the ConnectFour class with Al mode
enabled.
• Each player is assigned a color ( commonly red and yellow ) or a symbol ( like 11 X " and " O ").
2 . Starting Player :
• Players decide who goes first. This can be done through a coin toss, rock - paper - scissors, or any other
3 . Taking Turns :
• Players take turns dropping one of their pieces into any of the seven columns on the grid .
• The piece will fall to the lowest available space in the chosen column .
4 . Goal:
• The goal is to be the first to connect four of your pieces in a row, either horizontally, vertically, or
diagonally .
5 . Winning:
• The game ends as soon as one player successfully connects four of their pieces in a row .
• The winning player should announce their victory, and the game concludes .
6 . Draw:
• If the entire grid is filled without any player achieving four in a row, the game is a draw .
7. Restarting:
• After a game concludes, players may decide to play again by resetting the board .
8. Strategies:
• Pay attention to your opponent's moves to block potential winning combinations .
• Follow the same rules, but be prepared for strategic decisions from the Al opponent.
10. Enjoyment:
• Connect Four is a fun and quick game . Focus on enjoying the strategic aspects and friendly competition .
Remember that Connect Four is a game of skill and strategy, and with practice, you can
improve your ability to anticipate and block your opponent's moves while creating winning
opportunities for yourself.
13. Flappy Bird Clone Game
Flappy Bird Clone — X
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 600, 400
FPS = 30 # Adjust the frame rate
GRAVITY =1.0 # Adjust the gravity
JUMP-HEIGHT =10 # Adjust the jump height
PIPE-WIDTH = 50
PIPE-HEIGHT = 200
PIPE_GAP = 250 # Adjust the gap between pipes
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Scale images
bird-image = pygame.transform.scale(
bird-image, (30, 30)) # Adjust the bird size
pipe.image = pygame.transform.scale(pipe_image, (PIPE-WIDTH, PIPE-HEIGHT))
class Bird:
def_init_ (self):
self.x =100
self.y = HEIGHT // 2
self.width = 30 # Adjust the bird's width
self.height = 30 # Adjust the bird's height
self, velocity = 0
def jump(self):
self, velocity = -JUMP-HEIGHT
def update(self):
self, velocity += GRAVITY
self.y + = self, velocity
def draw(self):
screen.blit(bird_image, (self.x, self.y))
class Pipe:
def__ init_ (self, x):
self.x = x
self.gap_top = random.randint(50, HEIGHT - PIPE_GAP - 50)
def update(self):
self.x -= 5
def draw(self):
screen.blit(pipe_image, (self.x, 0))
lower_pipe_top = self.gap.top + PIPE.GAP
screen.blit(pipe_image, (self.x, lower_pipe_top))
Create objects
ird = Bird()
ipes = []
# Update objects
bird.updateO
for pipe in pipes:
pipe.updateQ
# Collision detection
for pipe in pipes:
bird_rect = pygame.Rect(bird.x, bird.y, bird, width, bird.height)
upper_pipe_rect = pygame.Rect(pipe.x, 100, PIPE_WIDTH, pipe.gap_top)
lower_pipe_top = pipe.gap_top + PIPE.GAP
lower_pipe_rect = pygame.Rect(
pipe.x, lower_pipe_top+5, PIPE_WIDTH, HEIGHT - lower_pipe_top)
# Draw background
screen.fill(WHITE)
screen.blit(background_image, (0,0))
# Draw objects
bird.drawO
for pipe in pipes:
pipe.drawQ
# Update display
pygame.display.flipO
let's go through the provided code line by line to understand its functionality:
Python Code
import pygame
import sys
import random
These lines import the necessary libraries for the game : pygame for game development,
sys for system - related functionality, and random for generating random numbers .
Python Code
# Initialize Pygame
pygame . init ()
This line initializes the Pygame library .
Python Code
# Constants
WIDTH, HEIGHT = 600,400
FPS = 30 # Adjust the frame rate
GRAVITY =1.0# Adjust the gravity
JUMP-HEIGHT =10# Adjust the jump height
PIPE_WIDTH =50
PIPE-HEIGHT = 200
PIPE_GAP = 250 # Adjust the gap between pipes
Here, various constants are defined, such as the width and height of the game window,
frame rate ( FPS ), gravity for the bird's movement, jump height, and dimensions for the
pipes .
Python Code
# Colors
WHITE =( 255,255, 255 )
BLACK = ( 0, 0, 0 )
These lines define color constants using RGB values .
Python Code
# Create the game window
screen = pygame . display. set_mode (( WIDTH, HEIGHT ))
pygame . display. set_caption (" Flappy Bird Clone ")
These lines create the game window with the specified width and height and set the
window caption.
Python Code
# Load images
bird_image = pygame . image . load (" bird . png ")
background_image = pygame . image . load (" background . png ")
pipe_image = pygame . image . load (" pipe . png ")
These lines load the images for the bird, background, and pipe from files .
Python Code
# Scale images
bird_image = pygame . transform . scale (bird_image, ( 30, 30 )) # Adjust the bird size
pipe_image = pygame . transform . scale (pipe_image, ( PIPE_WIDTH, PIPE_HEIGHT ))
The images are scaled to the desired dimensions .
Python Code
# Clock to control the frame rate
clock = pygame . time . Clock ()
A clock object is created to control the frame rate
Python Code
class Bird:
def_ init_ ( self ):
self, x = 100
self.y = HEIGHT // 2
self. width = 30 # Adjust the bird's width
self, height =30 # Adjust the bird's height
self. velocity = 0
«» Save the provided code in a Python file, for example, " flappy_bird_clone . py
o Open a terminal or command prompt, navigate to the directory containing the Python
file, and run it using python flappy_bird_clone . py .
2. Game Controls:
o Press the Spacebar to make the bird jump .
3. Game Objective:
° Navigate the bird through the gaps between the pipes without hitting them .
4. Game Mechanics:
•> The bird will fall due to gravity, and you must use the spacebar to make it jump .
- The pipes move from right to left, and new pipes are generated periodically .
° The goal is to keep the bird flying and pass through as many gaps between pipes as
possible .
5. Game Over:
° The game ends if the bird collides with the pipes .
° When a collision occurs, the game will print " Game Over, " reset the bird's position,
6. Repeat:
- The game will continue to run in a loop, allowing you to play again after each Game Over .
7. Adjustments:
o You can modify constants in the code ( such as GRAVITY , JUMP-HEIGHT ,
FPS , etc .) to change the difficulty or behavior of the game .
Remember that Flappy Bird is known for its challenging and addictive gameplay . Try to
beat your high score by maneuvering the bird through the pipes with well - timed jumps .
Good luck and have fun playing your Flappy Bird clone !
14. Pong Game
& Pong Game — X
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 600, 400
BALL_RADIUS = 10
PADDLE WIDTH, PADDLE HEIGHT = 10, 60
FPS = 60
WHITE = (255, 255,255)
# Create screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")
# Initialize velocities
□ all_speecLx = 3 * random.choice([l, -1])
□ all_speed_y = 3 * random.choice([l, -1])
player_speed = 0
opponent_speed = 2 # Adjust opponent's paddle speed
# Initialize score
player_score = 0
opponent_score = 0
def reset_ball():
ball.x = WIDTH // 2 - BALL.RADIUS // 2
ball.y = HEIGHT // 2 - BALL-RADIUS // 2
# Game loop
clock = pygame.time.ClockQ
while True:
for event in pygame.event.getQ:
if event.type == pygame.QUIT:
pygame.quitO
sys.exitQ
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player_speed = -3
elif event.key == pygame.K_DOWN:
player_speed = 3
elif event.key == pygame.K_r:
# Restart the game when 'R' is pressed
player_score = 0
opponent_score = 0
player.paddle.y = HEIGHT 11 2 - PADDLE_HEIGHT // 2
reset_ball()
ball_speed_x = 3 *random.choice([l, -1])
ball_speed_y = 3 * random.choice([l, -1])
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.KJDOWN:
player_speed = 0
# Opponent Al
if opponent_paddle.centery < ball.centery:
opponent_paddle.y += min(opponent_speed,
ball.centery - opponent.paddle.centery)
elif opponent_paddle.centery > ball.centery:
opponent-paddle.y -= min(opponent_speed,
opponent-paddle.centery - ball.centery)
# Draw everything
screen.fill((O, 0,0))
pygame.draw.rect(screen, WHITE, player_paddle)
pygame.draw.rect(screen, WHITE, opponent_paddle)
pygame.draw.ellipse(screen, WHITE, ball)
# Draw scores
font = pygame.font.Font(None, 36)
player_text = font.render(str(player_score), True, WHITE)
opponent-text = font.render(str(opponent_score), True, WHITE)
screen.blit(player_text, (WIDTH // 4, 20))
screen.blit(opponent_text, (3 * WIDTH // 4 -
opponent_text.get_width(), 20))
2. Controls:
° Use the up arrow key to move your paddle up .
3. Game Objective:
• Your objective is to prevent the ball from passing your paddle while trying to hit the ball
past your opponent's paddle .
4. Paddle Movement:
- Move your paddle up and down to position it for hitting the ball.
o Be strategic in your movements to intercept the ball and send it towards your opponent's
side .
5. Ball Movement:
• The ball will bounce off the top and bottom walls, as well as the paddles .
•» If the ball passes your opponent's paddle on the left side or your paddle on the right side,
your opponent or you score a point, respectively .
6. Scoring:
The scores are displayed at the top of the screen .
If the ball passes your opponent's paddle, your opponent scores a point.
7. Game Over:
• The game continues indefinitely until you decide to close the window or exit the game
manually.
•» You can also press the 'R' key to restart the game at any time .
8. Opponent Al:
° The opponent paddle has its own Al to follow the ball vertically, making the game more
challenging .
Remember, Pong is a classic and straightforward game, making it easy to pick up and play .
The more you play, the better you'll become at predicting the ball's movements and scoring
against your opponent.
15. Word Search Generator Game
/ Word Search Generator — □ X
computer
Mark Words
Clear Markings
C T D C R C R Q P E
J O U H L C B K D T
U L E K C c U F L O
E M Y S S o S S H H
J N A I U m H D B X
Y D M S W P Z U B W
R G L I W u Y R B J
E F P X Z t Y P X F
M T F C E e K U C X
I F X Q C r L B A R
import tkinter as tk
import random
class WordSearchGenerator:
def__ init_ (self, root):
self.root = root
self.root.title("Word Search Generator")
self.word_list_label = tk.Label(
root, text="Enter words (comma-separated):")
self.word_list_label.pack()
self.word_list_entry = tk.Entry(root)
self.word_list_entry.pack()
self.generate_button = tk.Button(
root, text="Generate Word Search", command=self.generate_word_search)
self.generate_button.pack()
self.mark_button = tk.Button(
root, text="Mark Words", command=self.mark_words)
self.mark_button.pack()
self.clear.button = tk.Button(
root, text="Clear Markings", command=self.clear_markings)
self.clear_button.pack()
def clear_markings(self):
if hasattr(self, 'word_search_canvas'):
self.word_search_canvas.delete("markings")
def generate_word_search(self):
self.clear_canvas()
words = self.word_list_entry.get().split(',’)
self. word_search = self.create_word_search(words)
self.display_word_search(self.word_search)
def mark_words(self):
if hasattr(self, 'word_search'):
words_to_mark = self.word_list_entry.get().split(7)
for i in range(len(self.word_search)):
for j in range(len(self.word_search[i])):
for word in words_to_mark:
# Check horizontally
if self.word_search[i][j:j + len(word)] == list(word):
self.mark_rectangle(i, j, len(word), "horizontal”)
# Check vertically
if i + len(word) < = len(self.word_search) and all(self.word_search[i + kJ[j] = = word[k] for k in range(len(word))):
self.mark_rectangle(i, j, len(word), "vertical”)
if direction == "diagonall":
self.word_search_canvas.create_rectangle(start_col * cell_size, start_row * cell_size,
(start_col + length) *
cell_size, (start_row +
length) * cell_size,
outline="red", width=2, tags="markings")
elif direction == "diagonal":
self.word_search_canvas.create_rectangle((start_col - length + 1) * cell_size, start_row * cell_size,
(start_col+ 1)*
cell_size, (start_row +
length) * cell_size,
outline="red", width=2, tags="markings")
def clear_canvas(self):
self.word_search_canvas.delete("all")
elif direction == 'diagonal' and start_row + len(word) <= word_search_size and start_col + len(word) < =
word_search_size:
for i in range(len(word)):
word_search[start_row + i][start_col + i] = word[i]
placed = True
attempts + = 1
# Fill in the remaining spaces with random letters
for i in range(word_search_size):
for j in range(word_search_size):
if word_search[i][j] ==
word_search[i][j] = chr(random.randint(65, 90))
return word_search
Python Code
class WordSearchGenerator:
def__init ( self, root):
self. root = root
self. root. title (" Word Search Generator ")
• Define a class WordSearchGenerator with an __ init_ method. It takes the root as a
parameter, representing the Tkinter root window . Sets the title of the root window to " Word Search
Generator ",
Python Code
self. word_list_label = tk . Label (
root, text =" Enter words ( comma - separated):")
self. word_list_label. pack ()
Create a Tkinter label for instructing the user to enter words . The label is added to the root window .
Python Code
self. word_list_entry = tk . Entry (root)
self. word_list_entry. pack ()
• Create a Tkinter entry widget for users to input words ( comma - separated ). It is added to the root
window .
Python Code
self. generate_button = tk . Button (
root, text =" Generate Word Search ", command = self. generate_word_search)
self. generate_button . pack ()
• Create a button labeled " Generate Word Search" with a command to call the
generate_WOrd_search method when clicked . The button is added to the root window .
Python Code
self. mark_button = tk . Button (
root, text =" Mark Words ", command = self. mark_words )
self. mark-button . pack ()
• Create a button labeled " Mark Words " with a command to call the mark_WOrds method when
clicked . The button is added to the root window .
Python Code
self. clear_button = tk . Button (
root, text =" Clear Markings ", command = self. clear_markings )
self. clear_button . pack ()
• Create a button labeled " Clear Markings " with a command to call the clear_markingS method
Python Code
self. word_search_canvas = tk . Canvas (
root, width = 300, height = 300, bg =" white ")
self. word_search_canvas . pack ()
• Create a Tkinter canvas for displaying the word search grid . It is given a size of 300x300 pixels and a
Python Code
def clear_markings ( self):
if hasattr ( self, 'word_search_canvas'):
self. word_search_canvas . delete (" markings ")
• Define a method clear_markingS to clear any marked rectangles on the canvas . It checks if the
canvas attribute exists before attempting to delete markings .
Python Code
def generate_word_search ( self):
self. clear_canvas ()
words = self. word_list_entry. get (). split ()
self. word_search = self. create_word_search ( words )
self. display_word_search ( self. word_search)
• Define a method generate_WOrd_Search to generate a new word search grid. It first clears
the canvas, then retrieves the words from the entry widget. It generates a word search using the
create_word_search method and displays it using display_word_search .
Python Code
defmark_words (self):
if hasattr ( self, 'word_search'):
words_to_mark = self. word_list_entry. get (). split ()
for i in range (len ( self. word_search )):
for j in range (len ( self. word_search [ i ])):
for word in words_to_mark :
# Check horizontally
if self. word_search [ i ] [ j: j + len (word)] = = list ( word):
self. mark_rectangle (i, j, len ( word), " horizontal")
# Check vertically
if i + len ( word) <= len ( self. word_search) and
all ( self. word_search [ i + k ] [ j ] == word [ k ] for k in range (len ( word))):
self. mark_rectangle (i, j, len (word), " vertical")
# Check diagonally (top - left to bottom - right)
ifi + len ( word) < = len ( self. word_search) andj + len ( word)
< = len ( self. word_search [ i ]) and all ( self. word_search [ i + k ][ j + k ] = = word [ k ]
for k in range (len (word))):
self. mark_diagonal (i, j, len ( word), " diagonal 1 ")
( start_col + 1 ) *
cell_size, (start_row +
length) * cell_size,
outline =" red", width = 2,
tags =" markings")
• Define a method mark_diagonal to mark a diagonal rectangle on the canvas . The direction
Python Code
def mark_rectangle ( self, start_row, start_col, length, direction ):
cell_size = 30
if direction == " horizontal
self. word_search_canvas . create_rectangle ( start_col * cell_size, start_row *
cell_size,
( start_col + length) *
cell_size, (start_row +
1 ) * cell_size,
outline =" red", width = 2,
tags =" markings")
elif direction == " vertical
self. word_search_canvas . create_rectangle ( start_col * cell_size, start_row *
cell_size,
( start_col + 1 ) *
cell_size, (start_row +
length) * cell_size,
outline =" red", width = 2,
tags =" markings")
elif direction = = " diagonal
self. word_search_canvas . create_rectangle ( start_col * cell_size, start_row *
cell size,
( start_col + length) *
cell_size, (start_row +
length) * cell_size,
outline =" red", width - 2,
tags =" markings")
• Define a method mark_rectangle to mark a rectangle on the canvas . The direction parameter
Python Code
defclear_canvas (self):
self. word_search_canvas . delete (" all")
• Define a method clear_canvas to clear the entire canvas .
Python Code
def display_word_search ( self, word_search ):
cell_size = 30
for i in range (len ( word_search )):
for j in range (len (word_search [ i ])):
self. word_search_canvas . create_text (j * cell_size + cell_size // 2, i *
cell_size + cell_size // 2,
text = word_search [ i ][ j ],
font =(" Helvetica", 10, " bold "))
• Define a method display_WOrd_search to display the generated word search on the canvas . It
uses create_text to place each character in the appropriate cell.
Python Code
def create_word_search ( self, words):
word_search_size =10
word_search = [[ " for _ in range (word_search_size )]
for _ in range ( word_search_size )]
for word in words :
placed = False
attempts = 0
attempts += 1
return word_search
• Define a method create_WOrd_search to generate a word search grid based on the input words . It
randomly places the words in different directions and fills the remaining spaces with random letters .
Python Code
if_ name_ =="_ main_
root = tk . Tk ()
app = WordSearchGenerator (root)
root. mainloop ()
• If the script is run as the main program, create a Tkinter root window and instantiate the
WordSearchGenerator class, starting the Tkinter event loop with root. mainloop ().
o The graphical user interface ( GUI ) will appear, featuring an entry field, buttons, and a
canvas .
2. Enter Words:
- In the " Enter words ( comma - separated ):" entry field, type the words you want to
search for in the word search grid . Separate the words with commas .
4. Mark Words:
- After generating the word search, you can mark specific words on
the grid . Enter the words you want to mark in the entry field again .
• Click the " Mark Words " button . The application will search for the
entered words horizontally, vertically, and diagonally on the grid . It
will mark the found words with red rectangles on the canvas .
5. Clear Markings:
• If you want to clear the marked rectangles from the canvas, click the " Clear Markings "
button.
6. Explore the Word Search :
• Explore the word search grid visually . The marked words will be highlighted, making
7. Additional Features:
- You can modify the word list, generate a new word search, mark different words, and
clear markings as many times as you want.
Enjoy playing the Word Search Generator, and have fun finding the hidden words in the
generated grids !
16. Battleship Game
/ Battleship Game
Battleship Game
Click on the buttons to find the battleships!
Score: 1
Turns left: 0
High Score: 2.0
import tkinter as tk
from random import randint
import time
class BattleshipGame:
def_ init_ (self, root):
self.root = root
self.root.title("Battleship Game")
self.board_size = 5
self.ship.size = 3
self.max.turns = 10
self.turns_left = self.max_turns
self.score = 0
self.board = [[0] * self.board_size for _ in range(self.board_size)]
self.ships = []
self.load_high_score()
self.create_info_panel()
self.create_board()
self.place_ships()
def load_high_score(self):
try:
with openf'high_score.txt", "r") as file:
high_score_str = file.read().strip()
if high_score_str.lower() == "inf":
self.high_score = float('inf')
else:
self.high_score = float(high_score_str)
except FileNotFoundError:
self.high_score = float('inf')
def save_high_score(self):
with openChigh_score.txt", "w") as file:
if self.high_score == float('inf'):
file.write("inf")
else:
file.write(f'{self.high_score:.2f}")
def create_info_panel(self):
info_label = tk.Label(
self.root, text="Battleship Game", font=("Helvetica", 16, "bold"))
info_label.grid(row=0, column=0, columnspan=self.board_size)
instruction-label = tk.Label(
self.root, text="Click on the buttons to find the battleships!", font=("Helvetica", 12))
instruction_label.grid(row= 1, column=0, columnspan=self.board_size)
score_label = tk.Label(
self.root, text=f’Score: {self.score}", font=("Helvetica", 12))
score_label.grid(row=2, column=0, columnspan=self.board_size)
turnsjabel = tk.Label(
self.root, text=f'Tur ns left: {self.turns_left)", font=("Helvetica", 12))
turns_label.grid(row=3, column=0, columnspan=self.board_size)
high_score_label = tk.Label(
self.root, text=f*High Score: {'inf' if self.high_score == float('inf') else round(self.high_score, 2)}", font=("Helvetica",
12))
high_score_label.grid(row=4, column=0, columnspan=self.board_size)
def create_board(self):
for i in range(self.board_size):
for j in range(self.board_size):
btn = tk.Button(self.root, text="", width=5, height=2,
command=lambda i=i, j=j: self.click_cell(i, j))
btn.grid(row=i + 5, column=j)
def place_ships(self):
for _ in range(self.ship_size):
ship_row = randint(O, self.board_size -1)
ship_col = randint(O, self.board_size -1)
while self.board[ship_row][ship_col] = = 1:
ship_row = randint(O, self.board_size -1)
ship_col = randint(O, self.board_size -1)
self.ships.append((ship_row, ship_col))
self.board[ship_row][ship_col] = 1
def update_info_panel(self):
self.root.grid_slaves(row=2, column=0)[0].config(
text=P'Score: {self.score}")
self.root.grid_slaves(row=3, column=0)[0].config(
text=P’Turns left: {self.turns_left}")
self.root.grid_slaves(row=4, column=0)[0].config(
text=f'High Score: {'inf' if self.high_score == float('inf') else round(self.high_score, 2)}")
def reset_game(self):
if self.score > 0:
# Save the current score as high score if some ships were sunk
if self.score < self.high_score:
self.high_score = self.score
self.save_high_score()
self.root.grid_slaves(row=4, column=0)[0].config(
text=f'High Score: {round(self.high_score, 2)}")
self.score = 0
self.turns_left = self.max_turns
self.ships = []
self.board = [[0] * self.board_size for _ in range(self.board_size)j
self.update_info_panel()
default_bg_color = self.root.cget("bg")
for i in range(self.board_size):
for j in range(self.board_size):
btn = self.root.grid_slaves(row=i + 5, column=j)[0]
btn.config(state=tk.NORMAL, bg=default_bg_color, text="")
if self.turns_left > 0:
self.place_ships()
self.start_time = time.time()
self.turns_left -= 1
self.update_info_panel()
if self.score == self.ship.size:
elapsed.time = round(time.time() - self.start_time, 2)
self.display_message(
f'Congratulations! You sunk all the battleships in {elapsed_time} seconds.")
if elapsed_time < self.high_score:
self.high_score = elapsed.time
self.save_high_score()
self.root.grid_slaves(row=4, column=0)[0].config(
text=P'High Score: {'inf' if self.high.score == float('inf') else round(self.high_score, 2)}")
self.reset_game() # Reset only when all ships are sunk
elif self.turns.left == 0:
self.display_message("Game Over. You ran out of turns.")
if self.score > 0 and self.score < self.ship.size:
# If some ships were sunk, save the current score as high score
if self.score > self.high.score:
self.high.score = self.score
self.save_high_score()
self.root.grid_slaves(row=4, column=0)[0].config(
text=f'High Score: {round(self.high_score, 2)}")
• The title " Battleship Game " is displayed at the top of the window .
o Below the title, there are instructions guiding you to click on the buttons to find the
battleships .
•> The score, turns left, and high score are displayed in the information panel.
3. Click Buttons:
° To uncover battleships, click on the buttons in the grid .
4. Gameplay:
•> The game starts with battleships randomly placed on the board .
° If you hit a battleship ( click on a cell containing a battleship ) , your score increases .
• You have a limited number of turns to find and sink all the battleships .
5. Game Over:
• The game ends when you run out of turns .
o A message will be displayed, indicating that the game is over, and you've exhausted all
turns .
6. Congratulations:
o If you successfully sink all the battleships within the allowed turns, a congratulatory
message will be displayed .
•> The elapsed time to complete the game is also shown in seconds .
Enjoy playing Battleship and try to beat your high score by sinking all the battleships in the
shortest time !
17. Space Invader Game
Space Invaders
Score: 0
X
Level: 1
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 600, 400
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Player
player_size = 50
player_speed = 5
# Enemy
enemy_size = 30
enemy_speed = 2
initial_enemy_spawn_rate = 25
min_enemy_spawn_rate = 5 # Minimum spawn rate
# Bullet
'Ullet-Speed = 7
# Load images
player_image = pygame.image.load("player.png")
enemy_image = pygame.image.load("enemy.png")
bullet_image = pygame.image.load("bullet.png")
# Load sounds
explosion_sound = pygame.mixer.Sound("explosion.wav"
shooting_sound = pygame.mixer.Sound("shooting.wav’')
# Player class
class Player(pygame.sprite.Sprite):
def_init_ (self):
super()._ init_ ()
self.image = pygame.transform.scale(
player_image, (player_size, player_size))
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH // 2
self.rect.bottom = HEIGHT -10
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and self.rect.left > 0:
self.rect.x -= player_speed
if keys[pygame.K_RIGHT] and self.rect.right < WIDTH:
self.rect.x + = player_speed
Enemy class
class Enemy(pygame.sprite.Sprite):
def_init_ (self):
super()._ init_ ()
self.image = pygame.transform.scale(
enemy_image, (enemy_size, enemy_size))
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, WIDTH - enemy_size)
self.rect.y = random.randint(-HEIGHT, 0)
def update(self):
self.rect.y += enemy_speed
if self.rect.top > HEIGHT:
self.rect.x = random.randint(0, WIDTH - enemy_size)
self.rect.y = random.randint(-HEIGHT, 0)
Bullet class
class Bullet(pygame.sprite.Sprite):
def__ init_ (self, x, y):
super()._ init_ ()
self.image = pygame.transform.scale(bullet_image, (10, 20))
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
def update(self):
self.rect.y -= bullet_speed
if self.rect.bottom < 0:
self.killO
# Create player
player = Player()
all_sprites.add(player)
if not game_over:
# Spawn enemies
if random.randint(l, initial_enemy_spawn_rate) = = 1:
enemy = EnemyO
all_sprites.add(enemy)
enemies.add(enemy)
# Update sprites
all_sprites.update()
# Draw everything
screen.fill(BLACK)
all_sprites.draw(screen)
# Draw "Game Over" text in yellow, centered within the white rectangle
game_over_text = font.render(
"Game Over, Press R to Restart", True, (0, 0, 255)) # Yellow color
textjrect = game_over_text.get_rect(center=white_rect.center)
screen.blit(game_over_text, text_rect.topleft)
# Update display
pygame.display.flipO
let's go through the code line by line and explain what each part does :
Python Code
import pygame
import sys
import random
Here, you're importing the necessary modules : pygame for creating the game, sys for
interacting with the system, and random for generating random numbers .
Python Code
pygame . init ()
This initializes Pygame.
Python Code
# Constants
WIDTH, HEIGHT = 600,400
FPS = 30
WHITE =(255,255,255 )
BLACK = ( 0, 0, 0 )
These lines define some constants used throughout the game, such as the screen width and
height, frames per second, and colors .
Python Code
# Player
player_size =50
player_speed = 5
Defines properties for the player character, such as its size and movement speed .
Python Code
# Enemy
enemy_size = 30
enemy_speed = 2
initial_enemy_spawn_rate = 25
min_enemy_spawn_rate = 5 # Minimum spawn rate
Defines properties for the enemy characters, such as size, speed, and spawn rate .
Python Code
# Bullet
bullet_speed = 7
Defines the speed of the bullets fired by the player .
Python Code
# Initialize the screen
screen = pygame . display. set_mode (( WIDTH, HEIGHT ))
pygame . display. set_caption (" Space Invaders ")
Initializes the game window with the specified width and height and sets the window
caption.
Python Code
# Load images
player_image = pygame . image . load (" player. png")
enemy_image = pygame . image . load (" enemy. png")
bullet_image = pygame . image . load (" bullet. png")
Loads the images for the player, enemy, and bullet from their respective image files .
Python Code
# Load sounds
explosion_sound = pygame . mixer. Sound (" explosion . wav ")
shooting_sound = pygame . mixer. Sound (" shooting . wav ")
Loads the sound effects for explosions and shooting .
Python Code
# Clock for controlling the frame rate
clock = pygame . time . Clock ()
Creates a Clock object to control the frame rate of the game .
The next section defines classes for the player, enemy, and bullet sprites, each with their
respective properties and methods .
The main game loop begins with a while loop that continuously runs until the game is
exited.
Inside the game loop, events such as quitting the game or pressing keys are handled .
If the game is not over, enemies are spawned randomly, sprites are updated, collisions are
checked, and the screen is drawn accordingly .
If the game is over, a " Game Over " message is displayed .
Python Code
# Update display
pygame . display. flip ()
Updates the display to show the changes made during this iteration of the game loop .
Python Code
# Increase difficulty with levels
if not game_over and score > = level *100:
level += 1
enemy_speed += 0.001
initial_enemy_spawn_rate -= 1 # Decrease the spawn rate
# Ensure it doesn't go below min rate
initial_enemy_spawn_rate = max (
initial_enemy_spawn_rate, min_enemy_spawn_rate)
Checks if the game is not over and if the score has reached a multiple of 100 . If so, increases
the level, enemy speed, and decreases the spawn rate of enemies .
Python Code
# Cap the frame rate
clock . tick ( FPS )
Limits the frame rate to the specified FPS value, ensuring the game runs at a consistent
speed across different devices .
This is a high - level overview of the code structure and functionality. Each part
contributes to creating a simple space invaders game using Pygame .
3. Player Movement:
• Use the left and right arrow keys to move your player spaceship horizontally across the
bottom of the screen .
4. Shooting:
• Press the spacebar to shoot bullets upward from your player spaceship .
5. Enemy Ships:
’ Enemy ships will spawn at the top of the screen and move downward towards your
player .
•> Your objective is to shoot down these enemy ships before they reach the bottom of the
screen.
6. Scoring:
You earn points for each enemy ship you successfully shoot down .
7. Levels:
As your score increases, you will progress through levels .
Each level may bring increased difficulty, such as faster enemy ships .
8. Game Over:
° The game ends if an enemy ship collides with your player spaceship .
•> If you want to restart after a game over, press the 'R' key .
again .
levels .
Remember, the game's difficulty increases as you progress through levels, so stay alert,
dodge enemy fire, and aim accurately to succeed !
18. Chess Game
Chess Game
import pygame
import sys
import os
# Initialize pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 600, 600
BOARD_SIZE = 8
SQUARE-SIZE = WIDTH // BOARD-SIZE
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
pm mi mi mi mi mi mi mil
pm mi mi mi mi mi mi mil
I//;////!/
pin mi mi mi mi mi mi mil
selected_piece = None
selected_row = None
selected_col = None
if piece ==
return False # No piece to move
if not (0 <= row_start < 8 and 0 < = col_start < 8 and 0 < = row_end < 8 and 0 < = col_end < 8):
return False # Check if the move is within the board boundaries
if (piece.islowerO and row_end <= row_start) or (piece.isupper() and row_end >= row_start):
return False # Ensure pawns are moving in the correct direction
if piece[0].lower() == *p':
# Pawn specific rules
ifcol_start == col_end andboard[row_end][col_end] ==
# Pawn moves forward one square
if abs(row_end - row_start) = = 1:
return True
# Pawn initial two-square move
elif abs(row_end - row_start) == 2 and row_start in (1, 6) and board[row_start + (1 if piece.islowerO else -1)]
[coLstart] ==
return True
elif abs(row_end - row_start) = = 1 and abs(col_end - col_start) == 1:
# Pawn captures diagonally
if board[row_end][col_end] != "" and piece.islowerO != board[row_end][col_end].islower():
return True
return False
if piece[0].lower() == *r':
# Rook specific rules
return row_start == row_end or col_start == col_end and not is_obstructed(start, end, board)
if piece[0].lower() == 'n':
# Knight specific rules
return (abs(row_end - row_start) == 2 and abs(col_end - col_start) == 1) or (abs(row_end - row_start) == 1 and
abs(col_end - col_start) == 2)
if piece[0].lower() == *b':
# Bishop specific rules
return abs(row_end - row_start) == abs(col_end - col_start) and not is_obstructed(start, end, board)
if piece[0].lower() == 'q':
# Queen specific rules
return (row_start == row_end or col_start == col_end or abs(row_end - row_start) == abs(col_end - col_start)) and
not is_obstructed(start, end, board)
if piece[0].lower() == 'k':
# King specific rules
return abs(row_end - row_start) < = 1 and abs(col_end - col_start) < = 1
return False
return False
return False
return promotion_piece
return piece
running = True
while running and not is_in_checkmate(chess_board, 'w') and not is_in_checkmate(chess_board, 'b'):
selected_piece_available_moves = []
for i in range(8):
for j in range(8):
if selected_piece and selected_row is not None and selected_col is not None:
move_valid = is_valid_move(
selected_piece, (selected_row, selected_col), (i, j), chess_board)
if move_valid:
selected_piece_available_moves.append((i, j))
piece_image = pieces[piece_key]
screen.blit(
piece_image, (col * SQUARE-SIZE, row * SQUARE_SIZE))
if selected_piece:
pygame.draw.rect(screen, (0, 255, 0), (selected_col * SQUARE-SIZE,
selected-row * SQUARE-SIZE, SQUARE-SIZE, SQUARE-SIZE), 4)
pygame.display.flipO
# Checkmate message
if is_in_checkmate(chess_board, 'w'):
print("Checkmate! Player B wins!")
elif is_in_checkmate(chess_board, 'b'):
printf'Checkmate! Player W wins!")
pygame.quit()
sys.exitQ
let's go through the provided Python Code line by line :
Python Code
import pygame
import sys
import os
• The code starts by importing the necessary libraries : pygame for game development, Sys for
system - related operations, and OS for interacting with the operating system .
Python Code
pygame . init ()
Initializes the pygame library . This must be called before using any pygame functions .
Python Code
WIDTH, HEIGHT = 600,600
BOARD_SIZE = 8
SQUARE-SIZE = WIDTH // BOARD-SIZE
WHITE =( 255,255, 255 )
BLACK = ( 0, 0, 0 )
• Sets up some constants for the dimensions of the game window, the size of the chessboard, the size of
each square on the chessboard, and color constants .
Python Code
chess_board = [
[mi f ini
/
mi
f
mi
/
mi
/
mi
/
mi
/
mil
J/
[mi f
mi mi
f f
mi
f
mi
r
mi
f
mi
f
mil
Jf
mil
[nil f
im mi
f f
mi
f
mi
/
mi
f
mi
f 1/
pi p ii ii p ii ii p ii ii p it ii p ii ii p if it p ii ii p nJ
[" R ", " N ", " B", " Q", " K ", " B", " N ", " R "],
]
• Initializes the chessboard as a list of lists representing the initial configuration of chess pieces .
Python Code
screen = pygame . display. set_mode (( WIDTH, HEIGHT ))
pygame . display. set_caption (" Chess Game ")
Creates the game window with the specified dimensions and sets the window caption .
Python Code
pieces = {}
for color in [ 'w', 'b' ]:
for piece in [ 'r', 'n', 'b', 'q', 'k', 'p' ]:
img_path = os . path . join (" images ", f" {color}{piece . lower ()}. png")
pieces [ color + piece ] = pygame . transform . scale (
pygame . image . load (img_path ), ( SQUARE_SIZE, SQUARE_SIZE ))
• Loads chess piece images from files located in the " images " directory and scales them to match the size
of a chessboard square . The images are stored in the pieces dictionary with keys like " wr " for a
white rook.
Python Code
selected_piece = None
selected_row = None
selected_col = None
• Initializes variables to keep track of the currently selected chess piece and its position on the board .
The code then defines several functions: is valid move, is obstructed, is in check,
findjking, is_in_checkmate , is_en_passant, and pawn_promotion . These functions are
responsible for checking various conditions related to chess moves and game state .
The code then enters a game loop using a while statement, where it continuously updates
the game state and checks for user input and events .
The game loop includes logic for handling mouse clicks, updating the display, and checking
for checkmate conditions . The loop continues until the game is either closed or a
checkmate is detected.
Finally, after exiting the game loop, the code prints a message indicating the winner (if
any), closes the pygame window, and exits the program .
•» If the move is valid, the piece will be moved to the new position .
4. Pawn Promotion:
- If a pawn reaches the opposite end of the board, you will be prompted to choose a piece for
promotion ( Queen, Rook, Knight, Bishop ).
• If a king is in check, the board will display a message indicating the check .
•» If a checkmate occurs, the game will end, and the winner will be announced .
7. Observing Rules:
o The code enforces standard chess rules, including valid moves for each piece, castling, en
passant, and pawn promotion .
° Images of chess pieces are expected to be in the " images " directory . Make sure you
have the necessary images for each piece ( e . g . , wr. png for a white rook ).
Keep in mind that this code provides a basic interface for playing chess, and it's meant for
educational purposes . It doesn't include features like an Al opponent, saving games, or
advanced graphical elements . If you're looking for a more user - friendly and feature - rich
chess - playing experience, consider using dedicated chess software or online platforms .
19. Roulette Simulator Game
/ Roulette Simulator
Bet Amount: 50
Deposit Money
Number
Red
Spin
Black
Odd
Even
Result: 'he result is: 17
Money Balance: $999585.00
import tkinter as tk
from tkinter import messagebox
import random
class RouletteSimulator:
def__ init_ (self, master):
self.master = master
self.master.title("Roulette Simulator")
# Bet Controls
self.bet_label_frame = tk.LabelFrame(master, text="Place Your Bet")
self.bet_label_frame.grid(
row=0, column=0, padx=10, pady=10, sticky="w")
self.bet_amount_label = tk.Label(
self.bet_label_frame, text="Bet Amount:")
self.bet_amount_label.grid(row=0, column=0, pady=5)
self.bet_amount_var = tk.StringVar()
self.bet_amount_entry = tk.Entry(
self.bet_label_frame, textvariable=self.bet_amount_var, width = 10)
self.bet_amount_entry.grid(row=0, column=l, pady=5)
self.bet_number_label = tk.Label(
self.bet-labeljffame, text="Guessing Number:")
self.bet_number_label.grid(row=l, column=0, pady=5)
self.bet_number_var = tk.StringVar()
self.bet_number_entry = tk.Entry(
self.bet-label-frame, textvariable=self. bet_number_var, width = 10)
self.bet_number_entry.grid(row= 1, column= 1, pady=5)
self.bet_type_var = tk.StringVar()
self.bet_type_var.set("Number")
bet_types = ["Number", "Red", "Black", "Odd", "Even"]
self.bet_type_menu = tk.OptionMenu(
self.bet_label_frame, self.bet_type_var, *bet_types)
self.bet_type_menu.grid(row=2, column= 1, pady=5)
# Deposit Controls
self.deposit_label_frame = tk.LabelFrame(master, text="Deposit Money”)
self.deposit_label_frame.grid(
row=0, column=l, padx=10, pady=10, sticky=”w”)
self.deposit_label = tk.Label(
self.deposit_label_frame, text=”Deposit Amount:”)
self.deposit_label.grid(row=0, column=0, pady=5)
self.deposit_var = tk.StringVar()
self.deposit_entry = tk.Entry(
self.deposit_label_frame, textvariable=self. deposit_var, width= 10)
self.deposit_entry.grid(row=0, column=l, pady=5)
self.deposit_button = tk.Button(
self.deposit_label_frame, text="Deposit”, command=self.deposit_money)
self.deposit_button.grid(row=0, column=2, pady=5, padx=(10, 0))
# Spin Button
self.spin.button = tk.Button(
master, text=”Spin”, command=self.start_spin, width=20, state='disabled')
self.spin_button.grid(row=l, column=0, columnspan=2, pady=15)
# Result and Balance Labels
self.result_label = tk.Label(
master, text="Result:", font=("Helvetica", 10, "bold"))
self.result_label.grid(row=2, column=0, pady=(5, 0), sticky="w")
self.result_var = tk.StringVar()
self.result_value_label = tk.Label(
master, textvariable=self.result_var, font=("Helvetica", 16))
self.result_value_label.grid(row=2, column=l, pady=(5, 0), sticky="w")
self.balance.label = tk.Label(
master, text=f'Money Balance: ${self.money_balance:.2f}", font=("Helvetica", 12, "bold"))
self.balance_label.grid(row=3, column=0, columnspan=2, pady=(10, 0))
self.is_spinning = False
self.spin_interval = 100 # milliseconds
self.spin_count = 0
self.stop_spin_count =10
self.money_balance += deposit.amount
self.update_balance_label()
def start_spin(self):
if not self.is_spinning:
self.spin_count = 0
self.is_spinning = True
self.spin()
def spin(self):
if self.is_spinning:
# 0 to 3 6 for numbers, 3 7 for '00'
result = random.choice(range(37))
self.result_var.set(result)
self.spin.count + = 1
if win_amount > 0:
self.show_outcome_message(
f'Congratulations! You win ${win_amount - bet_amount}!")
else:
self.show_outcome_message("You lose!")
outcome_label = tk.Label(
outcome_window, text=message, font=("Helvetica", 12))
outcome_label.pack(padx=20, pady=10)
def update_balance_label(self):
self.balance_label.config(
text=f'Money Balance: ${self.money_balance:.2f}")
• self . master . geometry (...) : Sets the window size and position .
controls .
result.
• Choose the type of bet you want to place using the " Bet Type " dropdown menu .
Options include :
- Depending on the selected bet type, additional input may be required ( e . g . , guessing
a specific number ).
3. Deposit Money:
° In the " Deposit Money " section, enter the amount you want to deposit in the " Deposit
Amount11 entry .
o Click the " Deposit " button to add money to your balance .
o Click the " Spin " button to start the roulette wheel.
’ The outcome will show whether you won or lost and the specific result.
6. Outcome Message:
” A pop - up window will appear with a message indicating whether you won or lost.
7. Repeat or Adjust:
“ You can repeat the process by placing new bets, changing bet types, or depositing more
money.
• Adjust your bets and strategy based on the outcomes and your remaining balance .
8. Quit the Game :
’ Close the main window to exit the game .
Remember that this is a simplified roulette simulator, and the goal is to enjoy the
experience of betting and spinning the wheel without real money involved. Have fun
exploring different bet types and strategies !
20. MancalaGame
/ Mancala Game
Reset Game
import tkinter as tk
from tkinter import ttk, messagebox
from ttkthemes import ThemedStyle
class MancalaGame:
def__ init_ (self, master):
self.master = master
self.master.title("Mancala Game")
# Mancalas
self.pl_mancala = tk.Label(
master, text="0", font=('Arial', 12, 'bold'))
self.p2_mancala = tk.Label(
master, text="0", font=('Arial', 12, 'bold'))
# Score labels
self.score_label_pl = tk.Label(
master, text="Player 1 Score:", font=('Arial', 10, 'italic'))
self.score_label_p2 = tk.Label(
master, text="Player 2 Score:", font=('Arial', 10, 'italic'))
# Reset button
self.reset_button = tk.Button(
master, text="Reset Game", command=self.reset_game, font=('Arial', 10, 'bold'))
def create_layout(self):
style = ThemedStyle(self.master)
style.set_theme("plastik") # You can choose other available themes
# Score labels
self.score_label_pl .grid(
row=3, column=0, padx=10, pady=5, columnspan=4)
self.score_label_p2.grid(
row=3, column=5, padx=10, pady=5, columnspan=4)
# Reset button
self.reset_button.grid(row=4, column=0, columnspan=10, pady=10)
self.board[pit_index] + = 1
stones -= 1
self.update_gui()
self.check_extra_turn(pit_index)
self.check_end_game()
if not self.extra_turn:
# Switch player only if there is no extra turn
# Switch between player 1 and player 2
self.current_player = 3 - self.current_player
def update_gui(self):
# Update Player l's side
for i in range(8):
self.pl_pits[i]["text"] = str(self.board[i])
self.pl_mancala["text"] = str(self.board[8])
self.p2_mancala["text"] = str(self.board[15])
# Update scores
self.score_label_pl["text"] = f'Player 1 Score: [sum(self.board[:8])}"
self.score_label_p2 ["text"] = f'Player 2 Score: {sum(self.board[8:16])!"
def check_end_game(self):
if all(pit = = 0 for pit in self.board[:8]) or all(pit = = 0 for pit in self.board[8:16]):
self.end_game()
def end_game(self):
pl_score = sum(self.board[:8])
p2_score = sum(self.board[8:16])
ifpl_score > p2_score:
winner = "Player 1"
elifpl.score < p2_score:
winner = "Player 2"
else:
winner = "It's a tie!"
def reset_game(self):
self.board = [4] * 16
self.current_player = 1
self.extra_turn = False
self.update_gui()
self. update_gui ()
self. check_extra_turn ( pit_index)
self. check_end_game ()
# Update scores
self. score_label_pl [" text"] = f " Player 1 Score : {sum ( self, board [: 8 ])}"
self. score_label_p2 [" text"] = f " Player 2 Score : {sum ( self, board [8:16])}"
The update_gui method updates the text on the buttons and labels to reflect the current
state of the game .
Python Code
def check_extra_turn ( self, last_pit_index):
i f self. current_player == 1 and 0< = last_pit_index < 8 and
self, board [ last_pit_index ] == 1 :
self. extra_turn = True
elif self. current_player = = 2 and 8< = last_pit_index < 15 and
self. board [ last_pit_index ] = = 1 :
self. extra_turn = True
else:
self. extra_turn = False
The check_extra_turn method determines whether an extra turn is granted based on the
last pit index where a stone was placed .
Python Code
def check_end_game ( self):
if all (pit == 0 for pit in self. board [: 8 ]) or all (pit == 0 for pit in
self, board [8:16]):
self. end_game ()
The check_end_game method checks if the game has ended by examining whether all pits
on one side are empty.
Python Code
defend_game (self):
pl_score = sum ( self. board [: 8 ])
p2_score = sum ( self, board [8:16])
ifpl_score > p2_score :
winner = " Player 1 "
elifpl_score < p2_score:
winner = " Player 2 "
else:
winner = " It's a tie !"
messagebox . showinfo (" Game Over ", f " The game is over ! \n{winner} wins !")
The end_game method displays a message box announcing the end of the game and the
winner or a tie .
Python Code
def reset_game ( self):
self. board = [ 4 ] * 16
self. current_player = 1
self. extra_turn = False
self. update_gui ()
The reset_game method resets the game state by setting the board to its initial
configuration, resetting the current player and extra turn variables, and updating the GUI.
Python Code
if_ name_ = = "_ main_
root = tk . Tk ()
mancala_game = MancalaGame (root)
root. mainloop ()
The script creates a Tkinter root window, initializes an instance of the MancalaGame class,
and starts the main event loop using root. mainloop (). This loop keeps the GUI responsive
to user interactions .
2. At the ends of the board, each player has a larger pit called the " Mancala
3. Place an equal number of stones or seeds in each of the 12 smaller pits. A common starting
configuration is four stones in each pit.
2. Decide who goes first. Players may use a coin toss, rock - paper - scissors, or any other method to
Gameplay:
1. On a player's turn, they select one of the pits from their row that contains stones or seeds .
2. The player then picks up all the stones or seeds from the chosen pit and distributes them, one by one,
in a counterclockwise direction into the succeeding pits, including their own Mancala but skipping the
opponent's Mancala.
3. If the last stone or seed is dropped into the player's Mancala, they get another turn . If the last stone
lands in an empty pit on their side, the player captures that stone and any stones in the opponent's pit
directly opposite . These captured stones are placed in the player's Mancala .
4. The game continues with players taking turns until one side of the board is empty .
Ending the Game : The game ends when one player no longer has stones or seeds in their
pits . The remaining stones on the opposite side of the board are captured by the other
player . The player with the most stones or seeds in their Mancala is declared the winner .
Winning : The player with the most stones or seeds in their Mancala at the end of the game
is the winner . If the Mancalas have an equal number of stones or seeds, the game is a tie .
Tips:
• Pay attention to the number of stones or seeds in each pit to plan strategic moves .
• Think about capturing your opponent's stones by landing the last stone in an empty pit on your side .
Mancala is a game that combines skill and strategy, making each move crucial to the
outcome . Enjoy playing and have fun !
21. Tower Defense game
Tower Defense Game
Score: 0
High Score: 0
import pygame
import sys
import random
£ Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
FPS = 60
WHITE = (255, 255, 255)
RED = (255,0, 0)
BLUE = (0,128,255)
YELLOW = (255, 255,0)
# Player
player_size = 50
player.pos = [WIDTH // 2 - player_size // 2, HEIGHT - player_size * 2]
player_color = BLUE
player_speed = 5
can_shoot = True
# Towers
tower_size = 30
ower_color = (0, 255, 0)
owers = []
# Bullets
bullet_size =10
bullet.color = YELLOW
bullets = []
bullet_speed = 8
# Enemies
enemy_size = 30
enemy_color = RED
enemy_speed = 3
enemies = []
# Score
score = 0
high_score = 0
font = pygame.font.Font(None, 36)
# Game state
game_over = False
restart_message = font.render("Game Over! Restart Please Press R", True, RED)
restart_message_rect = restart_message.get_rect(
center=(WIDTH // 2, HEIGHT // 2))
# Pause state
pause = False
pause_message = font.render("Game Paused. Press P to Resume", True, BLUE)
pause_message_rect = pause_message.get_rect(center=(WIDTH // 2, HEIGHT // 2))
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quitO
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_r and game_over:
# Reset the game
game_over = False
enemies.clear()
bullets.clearO
score = 0
elif event.key == pygame.K_SPACE and not game_over:
# Shoot a bullet from the player's position
bullet_pos = [player_pos[0] + player_size // 2, player_pos[l]]
bullets. append(bullet_pos)
elif event.key == pygame.K_p and not game_over:
# Toggle pause
pause = not pause
keys = pygame.key.get_pressed()
if not pause and not game_over: # Check if the game is not paused and not game over
if keys[pygame.K_LEFT] and player_pos[0] > 0:
player_pos[0] -= player_speed
if keys[pygame.K_RIGHT] and player_pos[0] < WIDTH - player_size:
player_pos[0] + = player_speed
if random.randint(0,100) < 5:
enemy_pos = [random.randint(0, WIDTH - enemy_size), 0]
enemies. append(enemy_pos)
# Draw
screen.fill(WHITE)
pygame.draw.rect(screen, player_color,
(player_pos[0], player_pos[l], player_size, player_size))
if game_over:
screen.blit(restart_message, restart_message_rect)
elif pause:
screen.blit(pause_message, pause_message_rect)
pygame.display.flipO
clock.tick(FPS)
system - specific parameters and functions, and random for generating random numbers .
Python Code
# Initialize Pygame
pygame . init ()
• Pygame is initialized to set up the gaming environment.
Python Code
# Constants
WIDTH, HEIGHT = 800,600
FPS = 60
WHITE =(255,255,255 )
RED =( 255,0,0)
BLUE =(0,128,255 )
YELLOW =( 255,255,0)
• Constants are defined, including the game window dimensions (WIDTH and HEIGHT ), frames
Python Code
# Set up the game window
screen = pygame . display. set_mode (( WIDTH, HEIGHT ))
pygame . display. set_caption (" Tower Defense Game ")
clock = pygame . time . Clock ()
• The game window is initialized using Pygame . A caption is set, and a clock object is created to control
Python Code
# Towers
tower_size = 30
tower_color = ( 0, 255,0 )
towers = []
• Tower - related variables are defined, including size, color, and an empty list ( towers ) to store tower
positions .
Python Code
# Bullets
bullet_size =10
bullet_color = YELLOW
bullets = []
bullet_speed = 8
• Bullet - related variables are defined, including size, color, an empty list ( bullets ) to store bullet
Python Code
# Enemies
enemy_size = 30
enemy_color = RED
enemy_speed = 3
enemies = []
• Enemy - related variables are defined, including size, color, speed, and an empty list ( enemies ) to
Python Code
# Score
score = 0
high_score = 0
font = pygame . font. Font ( None, 36)
• Score - related variables are defined, including the current score, high score, and a font object for
rendering text.
Python Code
# Game state
game_over = False
restart_message = font. render (" Game Over ! Restart Please Press R", True, RED )
restart_message_rect = restart_message . get_rect ( center =( WIDTH // 2, HEIGHT //
2))
• The game state is initialized, starting with game_OVer set to False . A message for restarting after
game over is created, and its position is set at the center of the screen .
Python Code
# Pause state
pause = False
pause_message = font. render (" Game Paused . Press P to Resume ", True, BLUE )
pause_message_rect = pause_message . get_rect ( center =( WIDTH // 2, HEIGHT // 2 ))
• The pause state is initialized, starting with pause set to False . A message for pausing is created, and
Python Code
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_r and game_over :
# Reset the game
game_over = False
enemies . clear ()
bullets. clear ()
score = 0
elif event. key == pygame . K_SPACE and not game_over :
# Shoot a bullet from the player's position
bullet_pos = [ player_pos [ 0 ] + player_size // 2, player_pos [ 1 ]]
bullets . append (bullet_pos )
elif event. key = = pygame . K_p and not game_over :
# Toggle pause
pause = not pause
• The event loop checks for user input, including quitting the game, restarting the game after it's over,
shooting bullets with the space key, and toggling pause with the 'p' key .
Python Code
keys = pygame . key. get_pressed ()
if not pause and not game_over :
if keys [ pygame . K_LEFT ] and player_pos [ 0 ] > 0 :
player_pos [ 0 ] - = player_speed
if keys [ pygame . K_RIGHT ] and player_pos [ 0 ] < WIDTH - player_size :
player_pos [ 0 ] + = player_speed
• Checks for continuous key presses ( arrow keys ) to move the player left or right, considering the game
Python Code
if not game_over and not pause :
for enemy in enemies :
enemy [ 1 ] + = enemy_speed
• If the game is not over and not paused, the enemies move downward .
Python Code
bullets = [[ bullet [ 0 ], bullet [ 1 ] - bullet_speed ] for bullet in bullets ]
bullets = [ bullet for bullet in bullets if 0 < bullet [ 1 ] < HEIGHT ]
• Bullets move upward, and any bullets outside the screen are removed .
Python Code
for bullet in bullets [:]:
for enemy in enemies [:]:
if(
enemy [ 0 ] < bullet [ 0 ] < enemy [ 0 ] + enemy_size
and enemy [ 1 ] < bullet [ 1 ] < enemy [ 1 ] + enemy_size
):
bullets . remove (bullet)
enemies . remove ( enemy)
score += 10
break
• Checks for collisions between bullets and enemies . If a collision occurs, the bullet and enemy are
Python Code
for enemy in enemies :
if(
player_pos [ 0 ] < enemy [ 0 ] + enemy_size
and player_pos [ 0 ] + player_size > enemy [ 0 ]
and player_pos [ 1 ] < enemy [ 1 ] + enemy_size
and player_pos [ 1 ] + player_size > enemy [ 1 ]
):
game_over = True
if score > high_score :
high_score = score
break
• Checks for collisions between the player and enemies . If a collision occurs, the game is set to over, and if
Python Code
if random . randint ( 0,100 ) < 5 :
enemy_pos = [ random . randint ( 0, WIDTH - enemy_size ), 0 ]
enemies . append ( enemy_pos )
• Randomly generates enemies at the top of the screen with a probability of 5 %.
Python Code
enemies = [ enemy for enemy in enemies if enemy [ 1 ] < HEIGHT ]
Removes enemies that have gone beyond the bottom of the screen .
Python Code
# Draw
screen . fill ( WHITE )
• Fills the screen with a white background .
Python Code
pygame . draw. rect ( screen, player_color,
(player_pos [ 0 ], player_pos [ 1 ], player_size, player_size ))
• Draws the player on the screen .
Python Code
for tower in towers :
pygame . draw. rect ( screen, tower_color,
(tower [ 0 ], tower [ 1 ], tower_size, tower_size ))
• Draws towers on the screen .
Python Code
for bullet in bullets :
pygame . draw. circle ( screen, bullet_color, (int (
bullet [ 0 ]), int (bullet [ 1 ])), bullet_size )
• Draws bullets on the screen .
Python Code
for enemy in enemies :
pygame . draw. rect ( screen, enemy_color,
( enemy [ 0 ], enemy [ 1 ], enemy_size, enemy_size ))
• Draws enemies on the screen .
Python Code
score_text = font. render ( f " Score : {score}", True, ( 0,0, 0 ))
screen . blit ( score_text, ( 10,10 ))
• Renders and displays the current score .
Python Code
high_score_text = font. render ( f " High Score : {high_score}", True, ( 0,0,0 ))
screen . blit (high_score_text, ( 10, 50 ))
• Renders and displays the high score .
Python Code
if game_over:
screen . blit ( restart_message, restart_message_rect)
elif pause :
screen . blit ( pause_message, pause_message_rect)
• Displays game over or pause messages on the screen, depending on the game state .
Python Code
pygame . display. flip ()
clock . tick ( FPS )
• Updates the display and controls the frame rate .
2. Controls:
• Use the left and right arrow keys to move the player left and right across the bottom of
the screen .
* Press the spacebar to shoot bullets upward and destroy incoming enemies .
3. Towers:
o There is a tower element in the game, but its functionality is not fully implemented in the
provided code . However, you can extend the code to include tower placement and use
4. Gameplay:
° Enemies will spawn randomly at the top of the screen and move downwards .
<• Your goal is to shoot bullets to destroy the enemies before they reach your position at the
5. Scoring:
o You earn points for each enemy you successfully eliminate with your bullets .
• The score is displayed on the screen, and there is also a high score that represents your
best performance in a single game .
6. Game Over:
’ The game ends if an enemy collides with your player . In this case, the game over
” You can restart the game by pressing the 'R* key after a game over . This clears the
7. Pause:
o You can pause the game by pressing the 'P' key . The pause message will be displayed, and
8. Tips:
• Try to eliminate enemies efficiently to maximize your score .
• Pay attention to the position of enemies and time your shots strategically .
° Keep an eye on your high score and aim to beat it in each session .
9. Customization ( Optional):
o You can modify the code to include additional features, such as tower placement and
upgrades, more enemy types, and power - ups .
Remember, this game is a basic implementation, and you can enhance it by adding new
features and improving the gameplay based on your preferences . Have fun playing and
experimenting with the code !
22. SokubanGame
/ Sokoban Game
□ X
class SokobanGame:
def__ init_ (self, master):
self.master = master
self.master.title("SokobanGame")
self.load_high_score()
self.levels = [
{
'width1: 5,
•height1: 5,
•player_pos': [2, 2],
'target-pos1: [4,4],
‘box-pos1: [3, 3],
},
# Add more levels as needed
{
’width1: 5,
•height1: 5,
'player_pos': [1,1],
*target_pos': [3, 3],
'box.pos': [2, 2],
self.create_widgets()
def create_widgets(self):
self.canvas = tk.Canvas(self.master, width=400, height=400, bg="white")
self.canvas.grid(row=0, column=0, rowspan=5)
self.restart_button = tk.Button(
self.master, text="Restart Game", command=self.restart_game)
self.restart_button.grid(row=0, column=l, sticky="nsew")
self.hint_button = tk.Button(
self.master, text="Hint", command=self.show_hint)
self.hint_button.grid(row=l, column=l, sticky="nsew")
self.high_score_label = tk.Label(
self.master, text=f'High Score: {self.high_score}")
self.high_score_label.grid(row=2, column=l, sticky="nsew"
self.load_level()
self.draw_board()
def load_level(self):
level_info = selfJevels[self.current_level]
self, width = level_info['width']
self.height = level_info['height']
self.player_pos = level-infot'player-pos'J.copyO
self.target_pos = level_info['target_pos'].copy()
self.box_pos = level-infoI'boX-pos'J.copyO
def draw_board(self):
self.canvas.deleteC'all")
if not (0 <= new_pos[0] < self.height and 0 < = new_pos[l] < self, width):
return
ifnew.pos == self.box_pos:
new_box_pos = [self.box_pos[0] + dy, self.box_pos[l] + dx]
if not (0 <= new_box_pos[0] < self.height and 0 < = new_box_pos[l] < self, width):
return
self.box_pos = new_box_pos
self.score += 10 # Increase score when moving the box
self.player_pos = new_pos
self.score -= 1 # Decrease score for each move
self.draw_board()
if self.check_stuck():
messagebox.showinfo(
"Game Over”, "You are stuck! Cannot push the box.")
self.restart_game()
if self.check_win():
self.score += 50 # Bonus score for completing the level
messagebox.showinfo("Congratulations",
f'You win!\nYour score: {self.score}")
self.update_high_score()
self.next_level()
def check_win(self):
return self.box_pos == self.target_pos
def check_stuck(self):
# Check if the box is stuck in the corners
corners = [
[0, 0], [0, self.width -1], # Top-left, Top-right corners
# Bottom-left, Bottom-right corners
[self.height -1,0], [self.height -1, self.width -1]
]
def next_level(self):
self.currentjevel + = 1
if self.current_level < len(self.levels):
self.load_level()
self.draw_board()
else:
messagebox.showinfo(
"Game Over", f All levels completed’AnFinal score: {self.score}")
self.restart_game()
def restart_game(self):
self.currentjevel = 0
self.score = 0
self.load_level()
self.draw_board()
def show_hint(self):
if self.hints > 0:
messagebox.showinfo(
"Hint", "Try to push the box onto the green target!")
self.hints -= 1
else:
messagebox.showinfo(
"Out of Hints", "You've used all available hints.")
def load_high_score(self):
try:
with open("high_score.json", "r") as file:
data = json.load(file)
self.high_score = data.get("high_score", 0)
except FileNotFoundError:
self.high_score = 0
def update_high_score(self):
if self.score > self.high_score:
self.high_score = self.score
with open("high_score.json", "w") as file:
json.dump({"high_score": self.high_score}, file)
self.high_score_label.config(text=f'High Score: {self.high_score}")
'width': 5,
'height': 5,
'player_pos': [ 2, 2 ],
'target_pos': [ 4,4 ],
'box_pos': [ 3, 3 ],
},
# Add more levels as needed
'width': 5,
'height': 5,
'player_pos': [ 1,1 ],
'target_pos': [ 3, 3 ],
'box_pos': [ 2, 2 ],
},
# ... Add 8 more levels
]
A list of levels is defined . Each level is represented by a dictionary containing the width,
height, player position, target position, and box position .
Python Code
self. current_level = 0
self, score = 0
self. hints = 3
self. create_widgets ()
Game - related variables are initialized, including the current level, score, and hints . The
create_widgets method is then called to set up the graphical user interface .
Python Code
def create_widgets ( self):
self. canvas = tk . Canvas ( self. master, width = 400, height = 400, bg =" white ")
self. canvas . grid (row = 0, column = 0, rowspan = 5 )
A canvas is created to draw the game board, and it is added to the main window using the
grid layout.
Python Code
self, master. bind (" <Up> ", lambda event: self, move (- 1,0))
self, master. bind (" <Down> ", lambda event: self, move ( 1,0))
self. master. bind (" <Left> ", lambda event: self. move (0, - 1 ))
self. master. bind (" < Right> ", lambda event: self. move ( 0,1 ))
Key bindings are set up to handle arrow key presses, connecting them to the move method
with specific direction arguments .
Python Code
self. restart_button = tk . Button (
self, master, text =" Restart Game ", command = self. restart_game )
self. restart_button . grid (row = 0, column = 1, sticky =" nsew ")
A button for restarting the game is created and added to the layout. Its command is set to
the restart_game method.
Python Code
self. hint_button = tk . Button (
self, master, text =" Hint", command = self. show_hint)
self. hint_button . grid (row = 1, column = 1, sticky =" nsew ")
A button for showing hints is created and added to the layout. Its command is set to the
show_hint method.
Python Code
self. high_score_label = tk . Label (
self. master, text = f " High Score : {self. high_score}")
self. high_score_label. grid (row = 2, column = 1, sticky =" nsew ")
A label to display the high score is created and added to the layout.
Python Code
self. load_level ()
self. draw_board ()
The load level method is called to initialize the current level, and the draw board method
is called to display the game board .
The code continues with additional methods and functionalities for handling game logic,
level progression, and UI interactions . If you have specific questions or if you'd like me to
continue explaining a particular part, feel free to ask !
2. Controls:
° Use the arrow keys ( Up, Down, Left, Right ) to move the blue player character around
the warehouse .
3. Game Elements:
Blue Player ( You ): Represented by a blue rectangle . This is the character you control.
•> Orange Boxes : Represented by orange rectangles . These are the boxes you need to
move .
•> Green Targets : Represented by green rectangles . Boxes must be pushed onto these
4. Rules:
• The player can only push one box at a time .
• > The player loses if a box gets stuck in a corner where there is no green target.
5. Scoring:
o Your score is initially set to 0 .
’ You earn points for pushing boxes ( + 10 points for each push ).
° You lose points for each move (- 1 point for each move ).
6. Buttons:
o Restart Game Z Resets the game to the first level, clearing the current score .
o Hint: Provides a hint on how to solve the level. You start with three hints, and once they
7. High Score:
” The high score is displayed on the GUI.
° The high score is updated when you complete a level with a higher score .
8. Game Over:
• The game ends when all levels are completed, and a final score is displayed .
<• The player can choose to restart the game after completion .
9. Level Progression:
» Successfully pushing all boxes onto the green targets advances you to the next level.
» Completing the last level shows a message indicating that all levels are completed .
• You start with three hints, and the hint count decreases each time you use one .
Remember, Sokoban is a logic puzzle, so take your time to plan your moves and consider the
consequences of each action . Good luck and enjoy playing Sokoban !
23. Breakout Game
V# Breakout Game — □ X
Score: 10 Level: 1
import pygame
import sys
import random
# Initialize Pygame
pygame.initO
# Constants
WIDTH, HEIGHT = 600, 400
PADDLE WIDTH, PADDLE HEIGHT = 100, 10
BALL_RADIUS = 10
BRICK WIDTH, BRICK HEIGHT = 60, 20
PADDLE_SPEED = 5
BALL_SPEED = 5
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Sound effects
pygame.mixer.initO
hit_sound = pygame.mixer.SoundChit.wav")
brick_break_sound = pygame.mixer.Sound("brick_break.wav’'
powerup.sound = pygame.mixer.SoundCpowerup.wav")
# Create bricks
num.bricks.x = 8
num.bricks.y = 4
brick,width = 60
brick.height = 20
bricks = []
for i in range(num.bricks.x):
for j in range(num.bricks.y):
brick = pygame.Rect(i * (brick.width + 5), 50 +
j * (brick.height + 5), brick.width, brick.height)
bricks.append(brick)
# Game variables
score = 0
level = 1
game_over = False
# Power-up variables
powerup_active = False
powerup_rect = pygame.Rect(O, 0, 20, 20)
powerup.speed = 3
powerup_duration = 5000 # in milliseconds
powerup-Start.time = 0
# Reset bricks
bricks = []
for i in range(num.bricks.x):
for j in range(num.bricks.y):
brick = pygame.Rect(
i * (brick.width + 5), 50 + j * (brick.height + 5), brick.width, brick.height)
bricks.append(brick)
if not game.over:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and paddle.left > 0:
paddle.move_ip(-PADDLE_SPEED, 0)
if keys[pygame.K_RIGHT] and paddle.right < WIDTH:
paddle.move_ip(PADDLE_SPEED, 0)
# Ensure the sound and level increase only if there were bricks remaining
if not any(bricks):
brick_break_sound.stop() # Stop the sound if it's playing
level + = 1
# Draw everything
screen.fill(BLACK)
# Draw power-up
if powerup.active:
pygame.draw.rect(screen, (255, 0, 0), powerup_rect)
# Draw paddle
pygame.draw.rect(screen, WHITE, paddle)
# Draw ball
pygame.draw.ellipse(screen, WHITE, ball)
# Draw bricks
for brick in bricks:
pygame.draw.rect(screen, WHITE, brick)
Python Code
# Initialize Pygame
pygame . init ()
2. Initialize Pygame to set up the gaming environment.
Python Code
# Constants
WIDTH, HEIGHT = 600,400
PADDLE WIDTH, PADDLE HEIGHT = 100,10
BALL-RADIUS = 10
BRICK WIDTH, BRICK HEIGHT = 60, 20
PADDLE_SPEED = 5
BALL_SPEED = 5
WHITE =( 255,255, 255 )
BLACK = ( 0, 0, 0 )
3. Define constants for various aspects of the game, such as window dimensions, paddle and ball sizes,
brick dimensions, speeds, and color codes .
Python Code
# Sound effects
pygame . mixer. init ()
hit_sound = pygame . mixer. Sound (" hit. wav")
brick_break_sound = pygame . mixer. Sound (" brick_break . wav")
powerup_sound = pygame . mixer. Sound (" powerup . wav ")
4. Initialize Pygame's sound mixer and load sound effects for collisions and power - ups .
Python Code
# Create the screen
screen = pygame . display. set_mode (( WIDTH, HEIGHT ))
pygame . display. set_caption (" Breakout Game ")
5. Set up the game window with the specified dimensions and title .
Python Code
# Create the paddle
paddle = pygame. Rect (WIDTH 11 2 - PADDLE.WIDTH // 2, HEIGHT - 20,
PADDLE_WIDTH, PADDLE_HEIGHT)
6. Initialize the paddle's position and dimensions using the pygame . Rect class.
Python Code
# Initialize paddle speed and acceleration
paddle_speed = 0
7. Set the initial paddle speed .
Python Code
# Create the ball
ball = pygame . Rect (WIDTH // 2 - BALL_RADIUS, HEIGHT 11 2 - BALL_RADIUS,
BALL_RADIUS * 2, BALL_RADIUS * 2 )
ball_speed = [ random . choice ([-1,1])* BALL_SPEED, - BALL_SPEED ]
8. Initialize the ball's position, dimensions, and initial speed .
Python Code
# Create bricks
num_bricks_x = 8
num_bricks_y = 4
bricks = L
Python Code
# Game variables
score = 0
level = 1
game_over = False
10. Initialize game variables, including score, level, and game - over status .
Python Code
# Power - up variables
powerup_active = False
powerup_rect = pygame . Rect ( 0,0, 20, 20 )
powerup_speed = 3
powerup_duration = 5000 # in milliseconds
powerup_start_time = 0
11. Initialize power - up - related variables, including its status, position, speed, duration, and start time .
Python Code
# Paddle skin options
PADDLE_SKINS = [ pygame . Rect ( 0, 0, 100,10 ), pygame . Rect ( 0, 0, 150,10 )]
paddle_skin_index = 0
12. Define different paddle skins using pygame . Rect and set the initial index .
Python Code
# Initialize remaining bricks count
bricks_remaining = num_bricks_x * num_bricks_y
13. Calculate and initialize the total number of remaining bricks .
Python Code
# Main game loop
while True :
for event in pygame . event. get ():
if event. type = = pygame . QUIT :
pygame . quit ()
sys. exit ()
elif event. type == pygame . KEYDOWN and event. key == pygame . K_SPACE and
game_over:
# Reset the game if the user presses space after the game is over
game_over = False
score = 0
level = 1
ball = pygame. Rect (WIDTH // 2 - BALL.RADIUS, HEIGHT // 2 -
BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2 )
ball_speed = [ random . choice ([-1,1])* BALL-SPEED, - BALL-SPEED ]
# Reset bricks
bricks = []
for i in range (num_bricks_x):
for j in range ( num_bricks_y):
brick = pygame . Rect (
i * (brick_width + 5),50 + j * ( brick_height + 5 ), brick_width,
brick_height)
bricks . append (brick)
Python Code
# Update ball position
ball. move_ip (ball_speed [ 0 ], ball_speed [ 1 ])
18. Update the ball's position based on its current speed .
Python Code
# Ball collisions with walls
if ball. left < = 0 or ball. right > = WIDTH :
ball_speed [ 0 ] = - ball_speed [ 0 ]
if ball. top < = 0 :
ball_speed [ 1 ] = - ball_speed [ 1 ]
19. Check for collisions with the walls and update the ball's speed accordingly .
Python Code
# Ball collision with paddle
if ball. colliderect (paddle ) and ball_speed [ 1 ] > 0 :
ball_speed [ 1 ] = - ball_speed [ 1 ]
hit_sound. play ()
20. Check for collisions with the paddle and update the ball's speed while playing a sound effect.
Python Code
# Ball collisions with bricks
for brick in list (bricks ):
if ball. colliderect (brick):
bricks . remove (brick )
bricks_remaining -= 1 # Update remaining bricks count
ball_speed [ 1 ] = - ball_speed [ 1 ]
score + = 10
brick_break_sound. play ()
bricks count. If there are remaining bricks, stop the brick breaking sound .
Python Code
# Check for level completion
if bricks_remaining == 0 and not any (bricks ):
level += 1
ball = pygame. Rect (WIDTH // 2 - BALL.RADIUS, HEIGHT // 2 -
BALL_RADIUS, BALL_RADIUS * 2, BALL.RADIUS * 2 )
ball_speed = [ random . choice ([-1,1])* BALL-SPEED, - BALL-SPEED ]
bricks = []
for i in range ( num_bricks_x):
for j in range ( num_bricks_y):
brick = pygame . Rect (
i * (brick_width + 5 ), 50 + j * (brick_height + 5 ), brick_width,
brick_height)
bricks . append (brick)
powerup_active = False # Reset power - up status
bricks_remaining = num_bricks_x * num_bricks_y # Reset remaining bricks
count
# Ensure the sound and level increase only if there were bricks remaining
if not any (bricks ):
brick_break_sound . stop () # Stop the sound if it's playing
level += 1
effect, and modifying the paddle's size . Check if the power - up's duration has expired and reset the
paddle size accordingly . Also, check if the power - up goes out of bounds .
Python Code
# Draw everything
screen . fill ( BLACK )
29. Fill the screen with a black background .
Python Code
# Draw power - up
if powerup_active :
pygame . draw. rect ( screen, ( 255, 0, 0 ), powerup_rect)
30. If a power - up is active, draw it as a red rectangle on the screen .
Python Code
# Draw paddle
pygame . draw. rect ( screen, WHITE, paddle )
31. Draw the paddle on the screen .
Python Code
# Draw ball
pygame . draw. ellipse ( screen, WHITE, ball)
32. Draw the ball on the screen as a white ellipse .
Python Code
# Draw bricks
for brick in bricks :
pygame . draw. rect ( screen, WHITE, brick)
33. Draw each brick on the screen as a white rectangle .
Python Code
# Draw score and level
font = pygame . font. Font ( None, 36 )
score_text = font. render ( f " Score : {score}", True, WHITE )
level_text = font. render (f " Level: {level}", True, WHITE )
34. Create a font object and render the score and level texts in white .
Python Code
# Draw background rectangles
pygame . draw. rect ( screen, BLACK, ( 0,0, WIDTH, score_text. get_height () + 5 ))
pygame . draw. rect ( screen, BLACK, ( WIDTH - level_text. get_width () - 5,0, WIDTH,
level_text. get_height () + 5 ))
35. Draw black rectangles as backgrounds for the score and level texts .
Python Code
# Draw score and level messages
screen . blit ( score_text, ( 10, 5 ))
screen . blit (level_text, ( WIDTH - level_text. get_width () - 10, 5 ))
36. Blit the rendered score and level texts onto the screen .
Python Code
# Draw game over screen
if game_over:
game_over_text = font. render (" Game Over ! Press SPACE to restart, True,
WHITE)
screen . blit ( game_over_text, ( WIDTH 111- game_over_text. get_width () // 2,
HEIGHT // 2 ))
37. If the game is over, render and display a game - over message in the center of the screen .
Python Code
# Update the display
pygame . display. flip ()
38. Update the display to reflect all the drawing changes .
Python Code
# Control the game speed
pygame . time . Clock (). tick ( 60 )
39. Control the game's speed by setting the frame rate to 60 frames per second .
This concludes the line - by - line walkthrough of the Breakout game code .
«> The game window will appear with the title " Breakout Game
2. Game Controls:
o Use the left and right arrow keys on your keyboard to move the paddle horizontally .
•> The objective is to bounce the ball off the paddle to hit and break the bricks .
3. Breaking Bricks:
o The screen initially contains a grid of bricks at the top .
o When the ball collides with a brick, the brick disappears, and you earn points .
4. Power - Ups :
’ Occasionally, hitting a brick may release a power - up .
«» Move the paddle to catch the power - up, and it will activate a special ability ( e . g . ,
5. Level Completion:
Your goal is to break all the bricks in the current level.
•> When all bricks are broken, you advance to the next level with a new set of bricks .
6. Game Over:
° If the ball falls below the paddle and touches the bottom of the screen, the game is over .
” You can restart the game by pressing the " SPACE " key after a game over .
• The game will reset, and you can continue playing from the first level.
8. Paddle Skins:
o The game offers different paddle skins that change the appearance of the paddle .
• To switch between paddle skins, you can modify the paddle_skin_index variable in
the code.
Reset Game
self
def resetga
if self.
resu
if __ name__ == ”
root = tk.Tk
gui = SimCit
root.mainloo
224 OUTPUT
s\ms-python.debu
0 jwrnwwRwsMwwnnr
import pygame
import sys
import tkinter as tk
from tkinter import messagebox
from threading import Thread
# Constants
SCREEN-WIDTH = 800
SCREEN-HEIGHT = 600
TILE_SIZE = 32
GRID-WIDTH = SCREEN-WIDTH // TILE.SIZE
GRID-HEIGHT = SCREEN-HEIGHT // TILE.SIZE
# Colors
WHITE = (255, 255, 255)
GREEN = (0,255,0)
RESIDENTIAL-COLOR = (0, 0, 255)
# Zone types
EMPTY = 0
Services
NO_SERVICE = 0
SCHOOL = 1
HOSPITAL = 2
POLICE STATION = 3
r,... *........
PARK = 4
class SimCity:
def__ init_ (self, master):
self.master = master
self.master.titleC'SimCity Clone")
def reset_game_state(self):
# Reset all game-related variables to their initial values
self.grid = [[EMPTY for _ in range(GRID_WIDTH)]
for _ in range(GRID_HEIGHT)]
self.population = 0
self.employment = 0
self.money = 10000
self.services = [[NO_SERVICE for _ in range(
GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
self.pollution = [[0 for _ in range(GRID_WIDTH)]
for _ in range(GRID_HEIGHT)]
self.crime = [[0 for _ in range(GRID_WIDTH)]
for _ in range(GRID_HEIGHT)]
self.happiness =100
def run(self):
self.running = True
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
self.master.destroyO
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
self.handle_mouse_click(event.pos)
self.updateO
self.drawQ
pygame.display.flipO
self.clock.tick(60)
self.money-= 1000
# Additional rules for commercial and industrial zones can be added here
def on_close(self):
self.running = False
self.master.destroyO
def update(self):
# Update logic here
pass
def draw(self):
self.screen.fill(WHITE)
for row in range(GRID_HEIGHT):
for col in range(GRID_WIDTH):
x = col * TILE_SIZE
y = row * TILE_SIZE
zone_color = WHITE if self.grid[row][col] == EMPTY else GREEN
pygame.draw.rect(self.screen, zone_color,
(x, y, TILE_SIZE, TILE.SIZE), 0)
# Display statistics
font = pygame.font.Font(pygame.font.get_default_font(), 36)
text = font.render(
f'Population: {self.population} Money: ${self.money}", True, GREEN)
self.screen.blit(text, (10,10))
ass SimCityGUI:
def__ init_ (self, master):
self.master = master
self.master.title("SimCity GUI")
self.start_button = tk.Button(
master, text="Start SimCity", command=self.start_simcity)
self.start-button.packQ
self.reset_button = tk.Button(
master, text="Reset Game", command=self.reset_game)
self.reset_button.pack()
self.game = None
def start_simcity(self):
if self.game is None:
self.game = SimCity(self.master)
Thread(target=self.game.run).start()
def reset_game(self):
if self.game is not None:
result = messagebox.askquestion(
"Reset Game", "Are you sure you want to reset the game?")
if result == 'yes':
self.game.reset_game_state() # Use the new method to reset the game state
messagebox.showinfo("Game Reset", "SimCity has been reset.")
7. Colors:
- WHITE , GREEN , RESIDENTIAL-COLOR : RGB tuples representing colors .
8. Zone types:
■> EMPTY = 0 : Constant representing an empty zone on the grid .
9. Services:
. NO SERVICE = 0, SCHOOL = 1 , HOSPITAL = 2 , POLICE STATION
= 3 , PARK = 4 : Constants representing different services that can be provided in
the city.
• run : The main game loop that handles events, updates the game state, and draws the screen .
• handle_H10USe_click : Handles mouse clicks to toggle zone types on the grid .
• update and draw : Placeholder methods for game logic update and screen drawing .
<> Atkinter GUI window will appear with " Start SimCity " and " Reset Game " buttons.
2. Start SimCity:
o Click the " Start SimCity " button .
” This will create a new Pygame window where you can interact with the game .
3. Zoning:
< > In the Pygame window, you'll see an empty grid . Each cell represents a tile .
5. Reset Game:
•> If you want to start over, go back to the tkinter GUI window .
• A confirmation dialog will appear . Click " Yes " to reset the game .
■ Add commercial and industrial zones with different costs and effects .
■ Implement services such as schools, hospitals, and police stations .
■ Introduce pollution and crime factors affecting happiness and population
growth .
Remember that this is a basic starting point, and you can enhance and customize the game
according to your preferences by modifying the code in the SimCity class .
25. Simon Says Game
/ Simon Says Game — □ X
Start Game
Score: 0
Level: 2
import tkinter as tk
import random
import time
import winsound # For playing sound effects (Windows only)
class SimonSaysGame:
def__init_ (self, master):
self.master = master
self.master.titlef'Simon Says Game")
self.colors = ["red", "blue", "green", "yellow"]
self.sequence = []
self.user.sequence = []
self.round = 1
self.speed= 1000 # Initial speed in milliseconds
self.game_running = False
self.create_widgets()
self.new_game()
def create_widgets(self):
self, start-button = tk.Button(
self.master, text="Start Game", command=self.start_game)
self.start_button.pack(pady= 10)
def new_game(self):
self.round = 1
self.speed = 1000
self.game_running = False
self.sequence = []
self.user_sequence = []
self.start_button.configure(state=tk.NORMAL)
self.update_score_label()
self.update_level_label()
def start_game(self):
self.new_game()
self.play_sequence()
def play_sequence(self):
self.game_running = True
self.start_button.configure(state=tk.DISABLED)
for _ in range(self.round):
new_color = random.choice(self.colors)
self.sequence.append(new_color)
self.highlight_color(new_color)
time.sleep(self.speed / 1000)
self.reset_colors()
self.prompt_user()
def reset_colors(self):
self.master.configure(bg="white")
self.master.updateO
def prompt_user(self):
self.user_sequence = []
def display_correct_feedback(self):
self.master.configure(bg="green")
self.master.after(500, self.reset_colors)
def end_game(self):
self.master.configure(bg="red")
self.start_button.configure(state=tk.NORMAL)
self.game_running = False
self.play_sound("wrong")
def update_score_label(self):
self.score_label.config(text=f Score: {max(0, len(self.sequence) -1)}")
def update_level_label(self):
self.level_label.config(text=f'Level: {self.round}")
if __name_ == "_main_":
root = tk.Tk()
game = SimonSaysGame(root)
root.mainloopO
self. colors = [" red", " blue ", " green", " yellow"]
self. sequence = []
self. user_sequence = []
self. round = 1
self, speed = 1000 # Initial speed in milliseconds
self. game_running = False
self. create_widgets ()
self. new_game ()
• This defines a class SimonSaysGame , which is the main class for the Simon Says game .
• The __ init_ method initializes the game by setting up the main window ( master ) ,
defining color options, initializing various game - related variables, and calling two methods :
label, level label, and colored buttons for the game . Each colored button has a command associated with
the check_Sequence method, which is passed the color of the button .
Python Code
defnew_game (self):
self. round = 1
self, speed = 1000
self. game_running = False
self. sequence = []
self. user_sequence = []
self. start_button . configure ( state = tk . NORMAL)
self. update_score_label ()
self. update_level_label ()
• The new_game method resets various game - related variables, configures the fi
Start Game ii
Python Code
defstart_game (self):
self. new_game ()
self. play_sequence ()
• The Start_game method initializes a new game and starts playing the sequence .
Python Code
def play_sequence ( self):
self. game_running = True
self. start_button . configure ( state = tk . DISABLED )
disables the " Start Game " button during this process .
Python Code
def highlight_color ( self, color):
self. master. configure (bg = color)
self. master. update ()
self. play_sound ( color)
time . sleep ( self, speed / 2000 )
self. master. update ()
• The highlight_color method changes the background color of the main window, plays a sound
associated with the color, introduces a delay, and then resets the background color .
Python Code
def reset_colors ( self):
self. master. configure (bg =" white ")
self. master. update ()
• The reset_colors method resets the background color to white .
Python Code
def prompt_user (self):
self. user_sequence = []
• The prompt_USer method resets the user's sequence .
Python Code
def check_sequence ( self, color):
if self. game_running :
self. user_sequence . append ( color)
self. highlight_color ( color)
self, master. after ( 500, self. reset_colors )
if self. user_sequence == self, sequence :
if len ( self. user_sequence ) = = len ( self, sequence ):
self, master. after ( 500, self. display_correct_feedback)
self. round + = 1
self, speed -= 20 # Increase speed for the next round
self. update_score_label ()
self. update_level_label ()
self, master. after ( 1000, self. play_sequence )
else:
self. end_game ()
• The check_sequence method is called when a colored button is pressed . It adds the color to the
user's sequence, highlights the color, resets the color, and checks if the user's sequence matches the
generated sequence . If it matches, it updates the score, level, and continues to the next round . If it
doesn't match, the game ends .
Python Code
def display_correct_feedback ( self):
self, master. configure (bg =" green ")
self, master. after ( 500, self. reset_colors )
• The display_COrrect_feedback method briefly changes the background color to green to provide
feedback when the user correctly matches the sequence .
Python Code
def end_game ( self):
self. master. configure (bg =" red ")
self. start_button . configure ( state = tk . NORMAL)
self. game_running = False
self. play_sound (" wrong ")
• The end_game method changes the background color to red, enables the " Start Game " button, sets
the game status to not running, and plays a " wrong " sound .
Python Code
def update_score_label ( self):
self. score_label. config (text = f " Score : {max ( 0, len ( self. sequence ) - 1 )}")
The update_SCOre_label method updates the score label based on the length of the sequence .
Python Code
def update_level_label ( self):
self. level_label. config (text = f " Level: {self. round}")
• The update_level_label method updates the level label based on the current round .
Python Code
def play_sound ( self, color):
# Play sound effects based on the color (Windows only)
if color == " red
winsound . PlaySound (" SystemExclamation ", winsound . SND_ASYNC )
elif color =="blue":
winsound . PlaySound (" SystemAsterisk ", winsound . SND_ASYNC )
elif color == " green
winsound . PlaySound (" SystemQuestion ", winsound . SND_ASYNC )
elif color == " yellow
winsound . PlaySound (" SystemHand ", winsound . SND_ASYNC )
elif color == " wrong
winsound . PlaySound (" SystemExit", winsound . SND_ASYNC )
• The play_SOUnd method plays sound effects based on the color using the winsound module .
Python Code
if_ name_ == "_ main_
root = tk . Tk ()
game = SimonSaysGame ( root)
root. mainloop ()
• Finally, this block creates an instance of the SimonSaysGame class and starts the main loop using
o Ensure that you are running the code on a Windows system, as it uses the winsound
module for sound effects, which is specific to Windows .
2. Game Interface:
° After running the code, a window titled " Simon Says Game " will appear .
° Click on the colored buttons in the same order as they were highlighted in the sequence .
” The program will provide visual and auditory feedback for each correct button press .
7. Speed Increase:
o As you progress through levels, the speed of the sequence display will increase, making
the game more challenging .
8. End of Game:
o If you make a mistake and press a button out of sequence, the game will end .
• The background color will turn red, and a 11 wrong " sound effect will be played .
Please note that the code assumes you are using a Windows system for sound effects . If
you are on a different operating system, you may need to modify the play_sound function
to use a cross - platform sound library .
26. LudoGame
import tkinter as tk
import random
import time
class LudoGame:
def_ init_ (self, root):
self.root = root
self.root.title("Ludo Game")
self.root.attributes('-fullscreen', True)
self.create_board()
self.create_players()
def create_board(self):
# Draw the Ludo board
for i in range(l, 6):
for j in range(l, 6):
xl,yl = i*100,j*100
x2,y2 = xl + 100, yl + 100
self.canvas.create_rectangle(
xl, yl, x2, y2, outline="black", fill="lightgreen")
def create_players(self):
self.players = [
{"color": "red", "piece": {"position": (300, 300)}},
{"color": "green", "piece": {"position": (400, 400)}},
{"color": "blue", "piece": {"position": (400, 300)}},
{"color": "yellow", "piece": {"position": (300, 400)}}
]
def roll_dice(self):
# Simulate a dice animation
for _ in range(lO):
value = random.randint(l, 6)
self.roll_button.config(text=value)
self.root.updateO
time.sleep(O.l)
def play_turn(self):
steps = self.roll_dice()
def highlight_current_player(self):
# Reset background color for all players
for player in self.players:
self.roll_button.config(
bg="SystemButtonFace") # Reset button color
# Highlight the background of the current player's roll dice button
current_player = self.players[self.current_player_index]
color = current_player["color"]
self.roll_button.config(bg=color)
def reset_game(self):
# Clear all pieces from the canvas
self.canvas.deletef'piece")
def check_win_condition(self):
# Check if a player has reached a certain position (e.g., the center of the board)
center_position = (300, 300)
for player in self.players:
if playerppiece'H'position'] == center_position:
return True
return False
# Main program
root = tk.Tk()
ludo_game = LudoGame(root)
root.mainloopO
let's go through the code line by line to understand its functionality :
Python Code
import tkinter as tk
import random
import time
This part of the code imports the necessary modules for creating a graphical user interface
( GUI) using the Tkinter library. The random module is used for simulating dice rolls,
and time is used for adding a delay in the dice animation .
Python Code
class LudoGame :
def__init._ ( self, root):
Here, a class LudoGame is defined, which will represent the Ludo game . The _ init_
method is a special method called when an object of the class is created. It initializes the
game with the given root ( Tkinter root window).
Python Code
self. root = root
self. root. title (" Ludo Game ")
self, root. attributes (' - fullscreen', True )
These lines store the root window, set its title to " Ludo Game," and make it fullscreen .
Python Code
button_frame = tk . Frame ( root, bg =" lightgray")
button_frame . pack ( side = tk . BOTTOM, fill = tk . BOTH, expand = True )
This creates a frame (button_frame ) at the bottom of the root window with a light gray
background . The frame is set to expand in both horizontal and vertical directions .
Python Code
self. canvas = tk . Canvas (root, width = 600, height = 600, bg =" white ")
self. canvas . pack ( side = tk . LEFT, padx = 10 )
This creates a canvas within the root window with a white background, representing the
game board . The canvas is set to a fixed size of 600x600 and is packed to the left of the root
window with some padding .
Python Code
self. create_board ()
self. create_players ()
These lines call methods to create the Ludo board (create_board) and initialize player
positions (create_players).
Python Code
self. roll_button = tk . Button (
button_frame, text =" Roll Dice ", command = self. play_turn)
self. roll_button . pack ( side = tk . LEFT, padx =10, pady = 10 )
This creates a button labeled " Roll Dice " inside the button_frame . Clicking this button
triggers the play_turn method .
Python Code
self. close_button = tk . Button (
button_frame, text =" Close ", command = root. destroy)
self. close_button . pack ( side = tk . RIGHT, padx =10, pady = 10 )
This creates a " Close " button within the button frame that, when clicked, closes the
Tkinter window.
Python Code
self. reset_button - tk . Button (
button_frame, text =" Reset Game ", command = self. reset_game )
self. reset_button. pack ( side = tk . RIGHT, padx =10, pady = 10)
This creates a " Reset Game " button within the button_frame that, when clicked, triggers
the reset_game method.
Python Code
self. player_info_label = tk . Label (
root, text ="", font =(" Helvetica ", 16 ))
self. player_info_label. pack ( side = tk . TOP, pady =10)
This creates a label at the top of the root window to display player information . The initial
text is empty, and the font is set to " Helvetica" with a size of 16 .
Python Code
self. current_player_index = 0
self. highlight_current_player ()
These lines initialize the variable for the current player index and call a method to highlight
the current player's turn .
Python Code
def create_board ( self):
for i in range (1,6):
for j in range (1,6):
xl,yl = i * 100,j * 100
x2,y2 = xl + 100, yl + 100
self. canvas . create_rectangle (
xl, yl, x2, y2, outline =" black ", fill =" lightgreen ")
The create_board method draws the Ludo board on the canvas using nested loops . It
creates a 5x5 grid of rectangles with black outlines and light green fill.
Python Code
def create_players ( self):
self. players = [
{" color " red", " piece " position ( 300, 300 )}},
{" color " green ", " piece " position ( 400,400 )}},
{" color " blue ", " piece " position( 400, 300 )}},
{" color " yellow ", " piece " position ( 300,400 )}}
]
for player in self. players :
self. draw_piece ( player [" piece "][" position"], player [" color"])
The create_players method initializes a list of players, each represented by a dictionary
with a color and initial piece position . It then calls the draw_piece method to draw each
player's piece on the canvas .
Python Code
def draw_piece ( self, position, color):
x, y = position
self. canvas . create_oval (
x - 20, y - 20, x + 20, y + 20, outline =" black ", fill = color, tags =" piece ")
The draw_piece method is responsible for drawing a player's piece on the canvas . It uses
the oval shape to represent the piece, given its position and color . The tags parameter is
used to tag the created object as a " piece
Python Code
def roll_dice ( self):
for _ in range ( 10 ):
value = random . randint (1,6)
self. roll_button . config (text = value )
self. root. update ()
time . sleep (0.1)
self. highlight_current_player ()
The move_piece method handles moving the player's piece based on the steps rolled . It
calculates the new position, checks its validity, clears the previous position, updates the
player's position, redraws the piece, checks for a win condition, and highlights the next
player's turn.
Python Code
def calculate_new_position ( self, current_position, steps ):
x, y = current_position
x += steps * 20
return x, y
The calculate_new_position method computes the new position based on the current
position and the number of steps rolled .
Python Code
def is_valid_position ( self, position):
x, y = position
return 0 < x < 600 and 0 < y < 600
The is_valid_position method checks if a given position is within the boundaries of the
canvas .
Python Code
def clear_position ( self, position):
x, y = position
overlapping_items = self. canvas . find_overlapping (
x - 20, y - 20, x + 20, y + 20)
for item in overlapping_items :
tags = self. canvas . gettags (item)
if" piece " in tags :
self. canvas . delete (item)
The clear_position method deletes any items (pieces ) present at a given position on the
canvas .
Python Code
def play_turn ( self):
steps = self. roll_dice ()
self. current_player_index + = 1
if self. current_player_index > = len ( self, players ):
self. current_player_index = 0
The play_turn method initiates a player's turn by rolling the dice, updating the player
information label, moving the piece, and advancing to the next player .
Python Code
def highlight_current_player (self):
for player in self. players :
self. roll_button . config (
bg =" SystemButtonFace ") # Reset button color
current_player = self. players [ self. current_player_index ]
color = current_player [" color "]
self. roll_button . config (bg = color)
The highlight_current_player method resets the background color of all players' buttons
and highlights the background of the current player's button .
Python Code
def reset_game ( self):
self. canvas . delete (" piece ")
self. current_player_index = 0
self. highlight_current_player ()
The reset_game method clears all pieces from the canvas, resets player positions, updates
the player information label, resets the current player index, and highlights the first player's
turn.
Python Code
def get_start_position ( self, color):
if color == " red
return ( 300, 300 )
elif color == " green
return ( 400,400 )
elif color =="blue":
return ( 400, 300 )
elif color == " yellow
return ( 300, 400 )
The get_start_position method returns the starting position for a given player color .
Python Code
def check_win_condition ( self):
center_position = ( 300, 300 )
for player in self. players :
if player [ 'piece' ][ 'position' ] == center_position :
return True
return False
The check_win_condition method checks if any player has reached the center position,
indicating a win condition .
Python Code
root = tk . Tk ()
ludo_game = LudoGame ( root)
root. mainloop ()
Finally, the main program creates a Tkinter root window, instantiates the LudoGame class
with the root window, and starts the Tkinter event loop with root. mainloop (). This loop
keeps the GUI application running until the user closes the window .
2. Game Interface:
o After running the script, a graphical window will appear with the Ludo board and game
controls .
rolled number.
4. Player Turn:
• The player with the current turn is highlighted, and their color is displayed on the " Roll
Dice " button .
«» If a player's piece reaches the center, the game declares that player as the winner .
7. Reset Game:
’ You can click the " Reset Game " button to start a new game . This will reset the pieces
Remember that this code provides a basic framework for a Ludo game, and you can
customize and extend it according to your preferences . You can add more features, such as
player names, sound effects, or additional game logic, to enhance the gaming experience .