You are on page 1of 6

Dino game

Saturday, November 25, 2023 3:16 PM

pythonCopy code
Importpygame
importos
importrandom pygame.init()
• These lines import the necessary modules (pygame, os, and random) and initialize the Pygame module. Pygame is a set of
Python modules designed for writing video games.

pythonCopy code
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 1100
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
• These lines set up the dimensions for the game window. SCREEN_WIDTH and SCREEN_HEIGHT define the size of the
window, and pygame.display.set_mode creates the game window using these dimensions.

pythonCopy code
RUNNING = [pygame.image.load(os.path.join("Assets/Dino", "DinoRun1.png")),
pygame.image.load(os.path.join("Assets/Dino", "DinoRun2.png"))]
JUMPING = pygame.image.load(os.path.join("Assets/Dino", "DinoJump.png")) DUCKING =
[pygame.image.load(os.path.join("Assets/Dino", "DinoDuck1.png")), pygame.image.load(os.path.join("Assets/Dino",
"DinoDuck2.png"))]
• These lines load images for the dinosaur character in different states. RUNNING has two images for a running animation,
JUMPING is for the jumping state, and DUCKING has two images for a ducking animation.

pythonCopy code
SMALL_CACTUS = [pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus1.png")),
pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus2.png")), pygame.image.load(os.path.join("Assets/Cactus",
"SmallCactus3.png"))] LARGE_CACTUS = [pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus1.png")),
pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus2.png")), pygame.image.load(os.path.join("Assets/Cactus",
"LargeCactus3.png"))]
• These lines load images for small and large cactus obstacles.

pythonCopy code
BIRD = [pygame.image.load(os.path.join("Assets/Bird", "Bird1.png")), pygame.image.load(os.path.join("Assets/Bird",
"Bird2.png"))]
• These lines load images for the bird obstacle.

pythonCopy code
CLOUD = pygame.image.load(os.path.join("Assets/Other", "Cloud.png"))
• This line loads an image for clouds.

pythonCopy code
BG = pygame.image.load(os.path.join("Assets/Other", "Track.png"))
• This line loads an image for the background.

pythonCopy code
classDinosaur: # ... (Class definition for the Dinosaur)
• This section defines a class named Dinosaur that represents the main character of the game. It includes attributes and
methods to handle the dinosaur's appearance, movement, and actions (running, jumping, ducking).

pythonCopy code
classCloud: # ... (Class definition for Cloud)
• This section defines a class named Cloud representing the cloud obstacle. It includes attributes and methods to handle the
cloud's appearance and movement.

pythonCopy code
classObstacle: # ... (Class definition for generic Obstacle)
• This section defines a generic class named Obstacle for all types of obstacles in the game. It includes attributes and methods
common to all obstacles, such as updating position and drawing on the screen.

New Section 2 Page 1


pythonCopy code
classSmallCactus(Obstacle): # ... (Class definition for Small Cactus, inheriting from Obstacle)
• This section defines a class named SmallCactus representing the small cactus obstacle. It inherits from the generic Obstacle
class, which means it has all the attributes and methods of Obstacle and can have additional specific features.

pythonCopy code
classLargeCactus(Obstacle): # ... (Class definition for Large Cactus, inheriting from Obstacle)
• This section defines a class named LargeCactus representing the large cactus obstacle. It also inherits from the generic
Obstacle class.

pythonCopy code
classBird(Obstacle): # ... (Class definition for Bird, inheriting from Obstacle)
• This section defines a class named Bird representing the bird obstacle. It inherits from the generic Obstacle class.

pythonCopy code
defmain(): # ... (Main game loop and logic)
• This function main contains the main game loop and logic. It initializes various game parameters, handles user input, updates
the game state, and checks for collisions with obstacles. This is where the core gameplay takes place.

pythonCopy code
defmenu(death_count): # ... (Menu screen logic)
• This function menu represents the game menu screen. It handles the display of text and options for starting or restarting the
game.

pythonCopy code
menu(death_count=0)
• This line calls the menu function to start the game, initializing the death count to 0.
To run this code, you need to have Python and Pygame installed on your machine. You also need the image assets in the
specified directory structure. Once everything is set up, you can run the script, and the game window should appear. Press
any key to start or restart the game, and use the UP and DOWN arrow keys to control the dinosaur. The goal is to avoid
obstacles and survive as long as possible while the score increases.

Sure, let’s go through this code line by line:


1. import pygame, os, random: This line imports the pygame library for game development, the os library for interacting with the
operating system, and the random library for generating random numbers.

2. pygame.init(): This initializes all the modules required for Pygame.

3. SCREEN_HEIGHT = 600 and SCREEN_WIDTH = 1100: These lines set the height and width of the game window.

4. SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)): This line creates the game window with the specified
height and width.

5. The next few lines load various images used in the game, such as the dinosaur’s running, jumping, and ducking images, the cactus
images, the bird images, the cloud image, and the background image. The os.path.join function is used to create the file paths.

6. class Dinosaur:: This line defines a class for the dinosaur character.

7. Inside the Dinosaur class, several variables are defined, such as X_POS, Y_POS, Y_POS_DUCK, and JUMP_VEL, which represent the
dinosaur’s x position, y position, y position when ducking, and jump velocity, respectively.

8. The __init__ method initializes the dinosaur’s state and loads the dinosaur’s images.

9. The update method updates the dinosaur’s state based on the user’s input.

10. The duck, run, and jump methods change the dinosaur’s image and position based on its current state.

11. The draw method draws the dinosaur on the screen.

12. class Cloud:: This line defines a class for the clouds in the background

New Section 2 Page 2


12. class Cloud:: This line defines a class for the clouds in the background
13. .
14. Inside the Cloud class, the __init__ method initializes the cloud’s position and image, the update method updates the cloud’s
position, and the draw method draws the cloud on the screen.

15. class Obstacle:: This line starts the definition of a class for the obstacles, but the code seems to be incomplete.
I hope this helps! If you have any more questions about this code, feel free to ask.

This code is a Python script that uses the Pygame library to create a simple game that involves a dinosaur character jumping over
obstacles. Let's go through it word by word:

import pygame
import os
impoirt random
pygame.init()

The Pygame library is imported, along with the "os" and "random" libraries. Pygame is initialized.

SCREEN_HEIGHT = 600
SCREEN_WIDTH = 1100
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

Constants for the height and width of the game screen are set, and the Pygame display window is created with these dimensions.

RUNNING = [pygame.image.load(os.path.join("Assets/Dino", "DinoRun1.png")),


pygame.image.load(os.path.join("Assets/Dino", "DinoRun2.png"))]
JUMPING = pygame.image.load(os.path.join("Assets/Dino", "DinoJump.png"))
DUCKING = [pygame.image.load(os.path.join("Assets/Dino", "DinoDuck1.png")),
pygame.image.load(os.path.join("Assets/Dino", "DinoDuck2.png"))]

SMALL_CACTUS = [pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus1.png")),


pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus2.png")),
pygame.image.load(os.path.join("Assets/Cactus", "SmallCactus3.png"))]
LARGE_CACTUS = [pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus1.png")),
pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus2.png")),
pygame.image.load(os.path.join("Assets/Cactus", "LargeCactus3.png"))]

BIRD = [pygame.image.load(os.path.join("Assets/Bird", "Bird1.png")),


pygame.image.load(os.path.join("Assets/Bird", "Bird2.png"))]

CLOUD = pygame.image.load(os.path.join("Assets/Other", "Cloud.png"))

BG = pygame.image.load(os.path.join("Assets/Other", "Track.png"))

images for the different game objects (dinosaur, cacti, bird, cloud, background) are loaded into the game using Pygame's image loading
functionality. They are stored in variables as Pygame Surface objects.

class Dinosaur:
X_POS = 80
Y_POS = 310
Y_POS_DUCK = 340
JUMP_VEL = 8.5

def __init__(self):
self.duck_img = DUCKING
self.run_img = RUNNING
self.jump_img = JUMPING

New Section 2 Page 3


self.dino_duck = False
self.dino_run = True
self.dino_jump = False

self.step_index = 0
self.jump_vel = self.JUMP_VEL
self.image = self.run_img[0]
self.dino_rect = self.image.get_rect()
self.dino_rect.x = self.X_POS
self.dino_rect.y = self.Y_POS

A Python class is defined for the dinosaur character. The class contains various properties of the dinosaur, such as its position on the
screen and its velocity when jumping. The __init__ method initializes the dinosaur's various states (ducking, running, jumping) and sets
its initial position on the screen.

def update(self, userInput):


if self.dino_duck:
self.duck()
if self.dino_run:
self.run()
if self.dino_jump:
self.jump()

if self.step_index >= 10:


self.step_index = 0

if userInput[pygame.K_UP] and not self.dino_jump:


self.dino_duck = False
self.dino_run = False
self.dino_jump = True
elif userInput[pygame.K_DOWN] and not self.dino_jump:
self.dino_duck = True
self.dino_run = False
self.dino_jump = False
elif not (self.dino_jump or userInput[pygame.K_DOWN]):
self.dino_duck = False
self.dino_run = True
self.dino_jump = False
The update method is called every frame of the game loop to update the dinosaur's state based on user input. If the dinosaur is ducking,
running, or jumping, the corresponding method is called. The step index is incremented and reset to 0 every 10 steps. Depending on the
user input, the dinosaur's state is updated accordingly.

def duck(self):
self.image = self.duck_img[self.step_index // 5]
self.dino_rect = self.image.get_rect()
self.dino_rect.x = self.X_POS
self.dino_rect.y = self.Y_POS_DUCK
self.step_index += 1

def run(self):
self.image = self.run_img[self.step_index // 5]
self.dino_rect = self.image.get_rect()
self.dino_rect.x = self.X_POS
self.dino_rect.y = self.Y_POS
self.step_index += 1

def jump(self):
self.image = self.jump_img

New Section 2 Page 4


self.image = self.jump_img
if self.dino_jump:
self.dino_rect.y -= self.jump_vel * 4
self.jump_vel -= 0.8
if self.jump_vel < - self.JUMP_VEL:
self.dino_jump = False
self.jump_vel = self.JUMP_VEL
Methods are defined for the different dinosaur states (ducking, running, jumping). These methods update the dinosaur's image and
position on the screen, as well as the dinosaur's velocity when jumping.

Overall, this code creates a simple game with a dinosaur character that can jump over obstacles. The dinosaur's state is controlled by
user input, and its image and position on the screen are updated every frame.

The draw method of the Dinosaur class is responsible for rendering the dinosaur character on the screen. It uses the blit function to
draw the dinosaur's image at the current position (self.dino_rect.x, self.dino_rect.y) on the game screen. [1]

The Cloud class represents the clouds in the game. It has an update method that updates the cloud's position based on the game_speed
variable. The draw method uses the blit function to draw the cloud's image at the current position (self.x, self.y) on the game screen. [3]

The Obstacle class represents various obstacles in the game, such as cacti and birds. It has an update method that updates the obstacle's
position based on the game_speed variable. The draw method uses the blit function to draw the obstacle's image at the current position
(self.rect.x, self.rect.y) on the game screen. [3]

The SmallCactus, LargeCactus, and Bird classes are subclasses of the Obstacle class. They override the __init__ method to set the
appropriate type and rect.y values for each specific obstacle. The draw method of the Bird class also animates the bird's image by
incrementing the index variable and using integer division to determine which frame of the animation to draw. [3]

The main function is the entry point of the game. It initializes various variables, including the game speed, background position, points,
font, and a list of obstacles. It also defines nested functions for scoring and rendering the game background. The main game loop
continuously updates and renders the game, handles user input, checks for collisions between the dinosaur and obstacles, and displays
the score. The game loop uses the blit function to draw various images on the game screen. [1][3]

The menu function is called when the game is over or when it starts for the first time. It displays a menu screen with text and an image. If
the player has died before, it also shows the score. The function waits for a key press event to start or restart the game. [3]

Overall, the code uses the blit function from the Pygame library to draw images on the game screen at specific positions. It also utilizes
various classes and methods to handle game objects, updates, rendering, collision detection, and game over conditions.

The given code is written in Python using the Pygame library. It defines several classes and functions to create a game. Here's a step-by-
step explanation of the code:

1. The `draw` method in the `Dinosaur` class is responsible for drawing the dinosaur on the game screen. It uses the `blit` function from
the Pygame library to display the dinosaur image at the specified coordinates [1].

2. The `Cloud` class represents a cloud object in the game. The `__init__` method initializes the cloud's position, image, and width. The
`update` method updates the cloud's position by subtracting the game speed from the x-coordinate. If the cloud goes off-screen, it is
randomly repositioned. The `draw` method is similar to the `draw` method in the `Dinosaur` class [1].

3. The `Obstacle` class represents an obstacle object in the game. The `__init__` method initializes the obstacle's image, type, and
rectangle. The `update` method updates the obstacle's position by subtracting the game speed from the x-coordinate. If the obstacle
goes off-screen, it is removed from the obstacles list. The `draw` method is similar to the `draw` method in the `Dinosaur` class [1].

4. The `SmallCactus`, `LargeCactus`, and `Bird` classes are subclasses of the `Obstacle` class. They have their own `__init__` methods that
set the type and y-coordinate of the obstacles, and they call the superclass's `__init__` method. The `Bird` class also overrides the `draw`
method to animate the bird's image [1].

New Section 2 Page 5


method to animate the bird's image [1].

5. The `main` function is the entry point of the game. It initializes various variables and objects, including the dinosaur, cloud, game
speed, background position, points, font, obstacles list, and death count. The function then enters a while loop that runs until the user
closes the game window.

6. Inside the while loop, the function handles user events, fills the screen with a white color, and gets the user's input. It then calls the
`draw` and `update` methods of the dinosaur object to draw and update its position. If there are no obstacles on the screen, a random
obstacle (small cactus, large cactus, or bird) is added to the obstacles list.

7. The function then iterates over the obstacles list, drawing and updating each obstacle's position. If the dinosaur collides with an
obstacle, a delay is added, the death count is incremented, and the `menu` function is called.

8. The function calls the `background` function to draw the scrolling background image. It also calls the `draw` and `update` methods of
the cloud object to draw and update its position.

9. The `score` function is called to update the points based on the game speed. It renders the points as text and displays it on the screen.

10. The function limits the frame rate to 30 frames per second using the `clock.tick` method, and updates the display using
`pygame.display.update` [1].

11. The `menu` function is called when the dinosaur collides with an obstacle. It displays a menu screen with the option to restart the
game. The menu screen is filled with a white color, and the text "Press any Key to Start" is rendered using a specified font [1].

That's a detailed explanation of the given code. It sets up the game environment, handles user input, updates game objects, and renders
them on the screen to create a simple game using the Pygame library.

Or

Sure, let's break down the code:

Sure, let’s break down the code:


1. def draw(self, SCREEN): SCREEN.blit(self.image, (self.dino_rect.x, self.dino_rect.y)): This is a method in the Dinosaur class that draws
the dinosaur on the screen. SCREEN.blit is a Pygame function that draws an image onto the screen. The image of the dinosaur is
drawn at the position specified by self.dino_rect.x and self.dino_rect.y.
2. class Cloud:: This line defines a new class called Cloud.
3. Inside the Cloud class:
○ __init__(self): This is the constructor method that is automatically called when a new object of the Cloud class is created. It
initializes the x and y coordinates of the cloud, loads the cloud image, and gets the width of the cloud image.
○ update(self): This method updates the x coordinate of the cloud to create a moving effect. If the cloud moves off the screen, it
resets the x coordinate to a random position off the right side of the screen and the y coordinate to a random height.
○ draw(self, SCREEN): This method draws the cloud on the screen at its current position.
4. class Obstacle:: This line defines a new class called Obstacle.
5. Inside the Obstacle class:
○ __init__(self, image, type): This is the constructor method. It initializes the image of the obstacle, its type, and its position.
○ update(self): This method updates the x coordinate of the obstacle to create a moving effect. If the obstacle moves off the
screen, it is removed from the list of obstacles.
○ draw(self, SCREEN): This method draws the obstacle on the screen at its current position.
6. class SmallCactus(Obstacle): and class LargeCactus(Obstacle):: These lines define new classes for small and large cacti. They inherit
from the Obstacle class and override the __init__ method to set a specific y coordinate and randomly choose a type of cactus.
7. class Bird(Obstacle):: This line defines a new class for birds. It also inherits from the Obstacle class and overrides the __init__ and
draw methods to animate the bird’s flight.
8. def main():: This function contains the main game loop, which updates the game state, handles user input, and redraws the game
screen.
9. def menu(death_count):: This function displays a start menu before the game begins and a game over menu when the player dies.
I hope this helps! If you have any more questions about this code, feel free to ask.

New Section 2 Page 6

You might also like