0% found this document useful (0 votes)
22 views18 pages

Explanation

Uploaded by

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

Explanation

Uploaded by

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

Project

This code is a basic level editor for a 2D game built using Pygame, a popular
library for creating games in Python. The editor allows the user to create levels
by placing different types of tiles on a grid, save the created level data, and
load saved levels for editing. Below is an explanation of each part of the code
and how it works.
Imports and Initialization
python
Copy code
import pygame
import pickle
from os import path

pygame.init()
The code starts by importing the necessary modules: pygame for game
development, pickle for saving/loading level data, and path to check if level files
exist. The pygame.init() call initializes all Pygame modules.
Screen and Variables Setup
python
Copy code
clock = pygame.time.Clock()
fps = 60
tile_size = 30
cols = 20
margin = 100
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Level Editor')
A clock is set up to control the frame rate (fps = 60). The dimensions for the
screen and grid are defined, with each tile being 30x30 pixels, and a margin of
100 pixels at the bottom for UI elements. Then, the Pygame display window is
created with a caption "Level Editor".
Loading Images
python
Copy code
sun_img = pygame.image.load('image/sun.png')
sun_img = pygame.transform.scale(sun_img, (tile_size, tile_size))
bg_img = pygame.image.load('image/sky.png')
bg_img = pygame.transform.scale(bg_img, (screen_width, screen_height -
margin))
# Similar code for dirt, grass, blob, platform, lava, coin, exit, save, and load
images
Various images for the background, tiles, and UI elements are loaded and
scaled to fit the grid size or screen.
Colors and Fonts
python
Copy code
white = (255, 255, 255)
green = (144, 201, 120)
font = pygame.font.SysFont('Futura', 24)
Colors and fonts are defined for rendering text and drawing grid lines.
World Data Initialization
python
Copy code
world_data = []
for row in range(20):
r = [0] * 20
world_data.append(r)
An empty 20x20 grid (world_data) is created, initially filled with zeros to
represent empty tiles. This array holds different integer values to represent
various tile types, such as dirt, grass, and objects like coins or lava.
Drawing Text, Grid, and World
draw_text Function
This function draws text on the screen at specified coordinates.
draw_grid Function
python
Copy code
def draw_grid():
for c in range(21):
pygame.draw.line(screen, white, (c * tile_size, 0), (c * tile_size,
screen_height - margin))
pygame.draw.line(screen, white, (0, c * tile_size), (screen_width, c *
tile_size))
This function draws a grid on the screen using white lines, creating a visual
structure for placing tiles.
draw_world Function
python
Copy code
def draw_world():
for row in range(20):
for col in range(20):
if world_data[row][col] > 0:
# Check tile type and blit the corresponding image to the
screen
The draw_world function iterates over each tile in world_data and renders the
appropriate tile image (dirt, grass, blob, etc.) based on the integer value stored
at each grid location.
Button Class
python
Copy code
class Button():
def __init__(self, x, y, image):
# Initialization of button properties like image and position
def draw(self):
# Checks for mouse click and returns action if clicked
The Button class creates buttons for saving and loading levels. The draw
method checks if the button is clicked and, if so, performs the associated
action. Two button instances are created for saving and loading levels:
python
Copy code
save_button = Button(screen_width // 2 - 120, screen_height - 500, save_img)
load_button = Button(screen_width // 2 + 50, screen_height - 505, load_img)
Main Game Loop
python
Copy code
run = True
while run:
clock.tick(fps)
screen.fill(green)
screen.blit(bg_img, (0, 0))
screen.blit(sun_img, (tile_size * 2, tile_size * 2))
The main game loop, controlled by the run variable, runs continuously until the
game is exited. Inside the loop, the frame rate is set to 60 FPS, and the
background is drawn.
Saving and Loading Levels
python
Copy code
if save_button.draw():
pickle_out = open(f'level{level}_data', 'wb')
pickle.dump(world_data, pickle_out)
pickle_out.close()
if load_button.draw():
if path.exists(f'level{level}_data'):
pickle_in = open(f'level{level}_data', 'rb')
world_data = pickle.load(pickle_in)
The level data in world_data is saved to or loaded from a file using the pickle
module when the respective button is clicked.
Drawing the Grid and World
python
Copy code
draw_grid()
draw_world()
The draw_grid and draw_world functions are called to display the grid and the
tiles on the screen.
Displaying Level Information
python
Copy code
draw_text(f'Level: {level}', font, white, tile_size, screen_height - 90)
draw_text('Press UP or DOWN to change level', font, white, tile_size,
screen_height - 60)
The current level number and instructions are displayed at the bottom of the
screen.
Event Handling
python
Copy code
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN and clicked == False:
# Placing or removing tiles
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
level += 1
elif event.key == pygame.K_DOWN and level > 1:
level -= 1
The event loop handles quitting the program, adding/removing tiles with mouse
clicks, and changing the level with the arrow keys. Left-clicking on a tile
increments its type, and right-clicking decrements it.
Exiting the Program
python
Copy code
pygame.quit()
When the main loop ends, pygame.quit() is called to close the game.

This code is structured to allow users to create and edit levels visually, with
buttons to save/load levels and a grid to place different tiles, creating a flexible
level editor for 2D games.

This program is a basic platform game built using Pygame, where the player
controls a character to jump over obstacles, collect coins, and reach an exit.
The program uses MySQL to store high scores, and Pygame for handling
graphics, events, and gameplay.
Here is a breakdown of each section of the code and its functionality:
1. Import Statements and Database Connection
python
Copy code
import pygame
from pygame.locals import *
import pickle
from os import path
import mysql.connector # type: ignore
import time
This imports essential libraries:
● Pygame is used for handling graphics and game logic.
● pickle allows loading and saving levels.
● mysql.connector is used to connect and interact with a MySQL
database where game scores are stored.
● time is for managing time-based events.
python
Copy code
mycon = mysql.connector.connect(host='localhost', user='root',
passwd='Guddu2467', database='game')
if mycon.is_connected():
print('connection successful')
else:
print('try again')

cursor = mycon.cursor()
This part establishes a connection to the MySQL database and checks if it was
successful.
2. Scoreboard Functions
python
Copy code
def insert_score(highest_score, current_score, elapsed_time):
try:
cursor.execute(
"INSERT INTO scoreboard (highest_score, current_score, elapsed_time)
VALUES (%s, %s, %s)",
(highest_score, current_score, elapsed_time)
)
mycon.commit()
except mysql.connector.Error as err:
print(f"Error: {err}")
● insert_score(): Inserts the highest score, current score, and elapsed
time into the database.
python
Copy code
def get_highest_score():
try:
cursor.execute("SELECT MAX(current_score) FROM scoreboard")
result = cursor.fetchone()
return result[0] if result[0] is not None else 0
except mysql.connector.Error as err:
print(f"Error: {err}")
return 0
● get_highest_score(): Retrieves the highest score from the database.
python
Copy code
def get_latest_score():
try:
id = cursor.execute("SELECT MAX(id) FROM SCOREBOARD")
cursor.execute("SELECT current_score, elapsed_time FROM scoreboard
where id=%s", id)
result = cursor.fetchone()
return result if result else (0, 0)
except mysql.connector.Error as err:
print(f"Error: {err}")
return (0, 0)
● get_latest_score(): Retrieves the latest score and elapsed time from
the database.
python
Copy code
def draw_scoreboard(score):
highest_score = get_highest_score()
draw_text(f"Highest Score: {highest_score}", font_score, black, 40, 50)
draw_text(f"Current Score: {score}", font_score, black, 40, 80)
draw_text(f"Time: {timer_elapsed}s", font_score, black, 40, 110)
● draw_scoreboard(): Draws the current and highest scores on the
screen.
3. Game Initialization
python
Copy code
pygame.init()
clock = pygame.time.Clock()
fps = 60
timer_elapsed = 0
timer_font = pygame.font.SysFont('Bouhaus 93', 30)
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, 1000)
● Initializes Pygame, sets the game frame rate (fps), and initializes a
timer event that increments every second.
python
Copy code
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('JUMP JAM')
font = pygame.font.SysFont('Bauhaus 93', 70)
font_score = pygame.font.SysFont('Bouhaus 93', 30)
● Sets screen dimensions and fonts for displaying text.
4. Game Assets and Colors
python
Copy code
white = (255, 255, 255)
blue = (0, 0, 255)
black = (0, 0, 0)

sun_img = pygame.image.load('image/sun.png')
bg_img = pygame.image.load('image/sky.png')
restart_img = pygame.image.load("image/restart_btn.png")
start_img = pygame.image.load('image/start_btn.png')
exit_img = pygame.image.load('image/exit_btn.png')
bg_img = pygame.transform.scale(bg_img, (screen_width, screen_height))
sun_img = pygame.transform.scale(sun_img, (60, 60))
exit_img_1 = pygame.transform.scale(exit_img, (200, 100))
start_img = pygame.transform.scale(start_img, (200, 100))
exit_img_2 = pygame.transform.scale(exit_img, (110, 40))
● Defines colors and loads images for the game’s background, buttons,
and other assets.
5. Helper Functions
python
Copy code
def draw_text(text, font, text_col, x, y):
img = font.render(text, True, text_col)
screen.blit(img, (x, y))
● draw_text(): Renders text on the screen.
python
Copy code
def reset_level(Level):
player.reset(100, screen_height - 130)
blob_group.empty()
platform_group.empty()
lava_group.empty()
exit_group.empty()

world_data = []
if path.exists(f'level{level}_data'):
pickle_in = open(f'level{level}_data', 'rb')
world_data = pickle.load(pickle_in)
world = World(world_data)
return world
● reset_level(): Resets all game elements for a new level.
6. Game Classes
Each class defines different elements of the game, such as the player, enemies,
platforms, and environment.
Button Class
python
Copy code
class Button():
# Handles button display and clicking.
Player Class
python
Copy code
class Player():
# Manages player movement, collisions, and game-over state.
World Class
python
Copy code
class World():
# Loads and manages tiles, platforms, and other elements of each level.
Enemy, Platform, Lava, Coin, and Exit Classes
Each of these classes manages a specific game element, controlling its
appearance, position, and movement.
7. Main Game Loop
python
Copy code
run = True
while run:
clock.tick(fps)
screen.blit(bg_img, (0, 0))
screen.blit(sun_img, (60, 60))
if main_menu == True:
# Handles main menu button interactions.
else:
# Runs the game and manages updates, rendering, and events.
if game_over == 1:
# Handle level completion
for event in pygame.event.get():
if event.type == timer_event:
timer_elapsed += 1
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
● Main Loop: This keeps the game running, handling events, drawing,
and updating gameplay elements until the user quits.
Each section of this code manages a unique aspect of the game, from
initializing graphics and handling inputs to updating game states and displaying
results. The program ties everything together in the main loop, which keeps the
game running until closed.

Sure, let's break down this game code step-by-step. This code is a 2D platform
game made using Pygame with a score-saving mechanism using MySQL. The
game is designed to let the player progress through multiple levels while
collecting coins, avoiding obstacles, and keeping track of scores and time
elapsed.
Here's a detailed explanation:
Import Libraries
python
Copy code
import pygame
from pygame.locals import *
import pickle
from os import path
import mysql.connector
import time
. pygame: Used to create the game, manage graphics, events, and
sounds.
. pickle: For saving and loading game level data.
. mysql.connector: For database interactions, where scores are saved.
. time: To manage timing functionalities.
Database Connection
python
Copy code
mycon = mysql.connector.connect(host='localhost', user='root',
passwd='Guddu2467', database='game')
if mycon.is_connected():
print('connection successful')
else:
print('try again')
cursor = mycon.cursor()
● Connects to a MySQL database named "game." If the connection is
successful, it prints "connection successful."
Scoreboard Functions
These functions interact with the database to handle scores.
insert_score Function
python
Copy code
def insert_score(highest_score, current_score, elapsed_time):
try:
cursor.execute(
"INSERT INTO scoreboard (highest_score, current_score, elapsed_time)
VALUES (%s, %s, %s)",
(highest_score, current_score, elapsed_time)
)
mycon.commit()
except mysql.connector.Error as err:
print(f"Error: {err}")
● Inserts scores into the scoreboard table.
get_highest_score Function
python
Copy code
def get_highest_score():
try:
cursor.execute("SELECT MAX(current_score) FROM scoreboard")
result = cursor.fetchone()
return result[0] if result[0] is not None else 0
except mysql.connector.Error as err:
print(f"Error: {err}")
return 0
● Fetches the highest score recorded in the database.
get_latest_score Function
python
Copy code
def get_latest_score():
try:
id=cursor.execute("SELECT MAX(id) FROM SCOREBOARD")
cursor.execute("SELECT current_score, elapsed_time FROM scoreboard
where id=%s",id)
result = cursor.fetchone()
return result if result else (0, 0)
except mysql.connector.Error as err:
print(f"Error: {err}")
return (0, 0)
● Fetches the latest score and elapsed time from the database.
draw_scoreboard Function
python
Copy code
def draw_scoreboard(score):
highest_score = get_highest_score()
draw_text(f"Highest Score: {highest_score}", font_score, black, 40, 50)
draw_text(f"Current Score: {score}", font_score, black, 40, 80)
draw_text(f"Time: {timer_elapsed}s", font_score, black, 40, 110)
● Displays the highest score, current score, and elapsed time on the
screen.
Game Initialization and Constants
python
Copy code
pygame.init()
clock = pygame.time.Clock()
fps = 60
timer_elapsed = 0
timer_font = pygame.font.SysFont('Bouhaus 93', 30)
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, 1000)
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('JUMP JAM')
font= pygame.font.SysFont('Bauhaus 93',70)
font_score = pygame.font.SysFont('Bouhaus 93', 30)
● Initializes Pygame and sets up the game window, framerate, and fonts.
● Defines a timer event (timer_event) that triggers every second.
Game Variables
python
Copy code
tile_size = 30
game_over = 0
main_menu = True
level =1
max_levels=4
score=0
● Initializes game-related variables:
○ tile_size: Size of tiles used in the level.
○ game_over: Tracks game status.
○ main_menu: Indicates whether the main menu is displayed.
○ level: Current level.
○ max_levels: Total levels in the game.
○ score: Player's score.

Colors and Image Assets


python
Copy code
white = (255, 255, 255)
blue = (0, 0, 255)
black = (0, 0, 0)
sun_img = pygame.image.load('image/sun.png')
bg_img = pygame.image.load('image/sky.png')
restart_img = pygame.image.load("image/restart_btn.png")
start_img = pygame.image.load('image/start_btn.png')
exit_img = pygame.image.load('image/exit_btn.png')
bg_img = pygame.transform.scale(bg_img, (screen_width, screen_height))
sun_img = pygame.transform.scale(sun_img, (60, 60))
exit_img_1 = pygame.transform.scale(exit_img, (200, 100))
start_img = pygame.transform.scale(start_img, (200, 100))
exit_img_2 = pygame.transform.scale(exit_img, (110, 40))
● Loads and scales game images, such as the background, sun, and
button images.
draw_text Function
python
Copy code
def draw_text(text, font, text_col, x, y):
img = font.render(text, True, text_col)
screen.blit(img, (x, y))
● Draws text onto the screen at specified coordinates.
reset_level Function
python
Copy code
def reset_level(level):
player.reset(100, screen_height - 130)
blob_group.empty()
platform_group.empty()
lava_group.empty()
exit_group.empty()
world_data=[]
if path.exists(f'level{level}_data'):
pickle_in = open(f'level{level}_data', 'rb')
world_data = pickle.load(pickle_in)
world = World(world_data)
return world
● Resets the level by clearing groups and reloading level data from a file.
Button Class
python
Copy code
class Button():
def __init__(self, x, y, image):
self.image = image
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def draw(self):
action = False
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
action = True
self.clicked = True
if pygame.mouse.get_pressed()[0] == 0:
self.clicked = False
screen.blit(self.image, self.rect)
return action
● Defines buttons for starting, exiting, and restarting.
Player Class
Defines and manages the player, including movement, collision, and update
functions.
World Class
Loads and manages level data, creating tiles, enemies, and platforms based on
the data.
Enemy, Platform, Lava, Coin, and Exit Classes
● Handle specific game elements, such as enemy behavior, moving
platforms, lava hazards, coins, and the exit door.
Main Game Loop
python
Copy code
run = True
while run:
clock.tick(fps)
screen.blit(bg_img, (0, 0))
screen.blit(sun_img, (60, 60))

# Main menu
if main_menu == True:
if exit_button_1.draw():
run = False
if start_button.draw():
main_menu = False
timer_elapsed = 0
highest_score = get_highest_score()
else:
world.draw()
# Game logic and rendering
# ...
● This is the main loop, where each frame of the game is processed. It
displays the main menu, draws game objects, handles events, updates
the player, and manages level progression.
Game Over and Level Completion Logic
Handles conditions when the player loses or completes the level. If the level is
completed, it increments the level, or ends the game if all levels are completed.
Event Handling
python
Copy code
for event in pygame.event.get():
if event.type == timer_event:
timer_elapsed += 1
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
● Processes events, including the timer event and quit event.
This is a high-level breakdown; each class and function has its own purpose,
and the logic connects all elements of the game, enabling it to run smoothly.

This code is a complete Python game written using the Pygame library, where
the player controls a character who jumps across platforms, collects coins,
avoids enemies, and completes levels. The code includes functions to save and
retrieve scores from a MySQL database, basic game mechanics, and UI
elements such as buttons and score displays.
I’ll walk through the code line-by-line, breaking down each section’s purpose
and functionality.
Imports and Database Setup
python
Copy code
import pygame
from pygame.locals import *
import pickle
from os import path
import mysql.connector
import time
● pygame is used to create the game's window, handle input, render
graphics, etc.
● pickle is for loading saved levels.
● path from os handles file paths.
● mysql.connector connects to the MySQL database to store and
retrieve scores.
● time library is imported but not used in this code, so it could be
removed to clean up the code.
Database Connection
python
Copy code
mycon = mysql.connector.connect(host='localhost', user='root',
passwd='Guddu2467', database='game')
if mycon.is_connected():
print('connection successful')
else:
print('try again')

cursor = mycon.cursor()
This establishes a connection to a MySQL database called game. If the
connection is successful, it prints a confirmation message. cursor is used for
executing SQL commands.
Scoreboard Functions
python
Copy code
def insert_score(highest_score, current_score, elapsed_time):
...
def get_highest_score():
...
def get_latest_score():
...
. insert_score: This function inserts a new score record into the
.
database, including the highest score, current score, and elapsed
time.
. get_highest_score: Retrieves the highest score from the scoreboard
table.
. get_latest_score: Fetches the most recent score entry's
current_score and elapsed_time.
Pygame Initialization and Timer Setup
python
Copy code
pygame.init()

clock = pygame.time.Clock()
fps = 60

timer_elapsed = 0
timer_font = pygame.font.SysFont('Bouhaus 93', 30)
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, 1000)
. pygame.init(): Initializes all imported Pygame modules.
. clock and fps: clock is used to control the game’s frame rate, set to
60 frames per second.
. timer_elapsed and timer_event: timer_elapsed tracks time in
seconds, while timer_event triggers every 1 second, updating the
game’s timer.
Screen and Font Setup
python
Copy code
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width,
screen_height))
pygame.display.set_caption('JUMP JAM')
Sets up a game window of size 600x600 pixels with the title "JUMP JAM".
Game Variables and Colors
python
Copy code
tile_size = 30
game_over = 0
main_menu = True
level = 1
max_levels = 4
score = 0
white = (255, 255, 255)
blue = (0, 0, 255)
black = (0, 0, 0)
Defines key game variables such as tile_size for grid-based positioning,
game_over status, level, max_levels, and score. Colors are defined in RGB
format.
Loading Images and Scaling
python
Copy code
sun_img = pygame.image.load('image/sun.png')
bg_img = pygame.image.load('image/sky.png')
restart_img = pygame.image.load("image/restart_btn.png")
...
bg_img = pygame.transform.scale(bg_img, (screen_width,
screen_height))
sun_img = pygame.transform.scale(sun_img, (60, 60))
Loads and scales various images used in the game, including background,
buttons, and objects like the sun.
draw_text and reset_level Functions
python
Copy code
def draw_text(text, font, text_col, x, y):
img = font.render(text, True, text_col)
screen.blit(img, (x, y))
● draw_text: Renders text to the screen at specified coordinates.
python
Copy code
def reset_level(Level):
player.reset(100, screen_height - 130)
blob_group.empty()
platform_group.empty()
lava_group.empty()
exit_group.empty()

world_data = []
if path.exists(f'level{level}_data'):
pickle_in = open(f'level{level}_data', 'rb')
world_data = pickle.load(pickle_in)
world = World(world_data)
return world
● reset_level: Resets the player position, clears game objects, and
loads level data from a saved file if available.
Class Definitions for UI and Game Elements
. Button: Represents buttons that players can click on.
. Player: Handles player movement, animation, jumping, and collision
with other game objects.
. World: Represents each level of the game, drawing tiles and creating
the game environment.
. Enemy, Platform, Lava, Coin, Exit: Define various game objects with
specific properties and behaviors.
Game Loop
The main game loop handles events, updates game objects, and draws
everything to the screen.
python
Copy code
run = True
while run:
...
if main_menu == True:
...
else:
world.draw()
if game_over == 0:
...
if game_over == -1:
...
if game_over == 1:
...
. main_menu: Displays the main menu where the player can start or exit
the game.
. Gameplay Logic: The world.draw() function draws the environment.
Depending on game_over, the player’s status is updated (playing,
game over, or level completed).
. Score Display and Updating: The draw_scoreboard function displays
the highest and current scores, and inserts data into the database
when necessary.
Event Handling and Timer Update
python
Copy code
for event in pygame.event.get():
if event.type == timer_event:
timer_elapsed += 1
if event.type == pygame.QUIT:
run = False
. Timer: Each second increments timer_elapsed.
. Quit Event: Exits the game when the window is closed.
Analysis
The code effectively integrates MySQL with Pygame to maintain a scoreboard
and allow multiple levels. However, a few improvements could be made:
. Exception Handling: Add error handling in file operations for level
loading.
. Database Optimization: Close the database connection once the
game ends to release resources.
. Code Structure: Modularize the code further by separating different
parts into modules.
. Gameplay Improvements: Add sound effects, more complex
animations, or power-ups for a better user experience.
This game is a solid foundation and could be expanded with additional levels,
features, or visual enhancements.

You might also like