0% found this document useful (0 votes)
7 views

Karthiks_python_program-1

The document provides an overview of 'Flappy Tom', a Python-based game inspired by 'Flappy Bird', utilizing the Pygame library for graphics and sound. It outlines the game's components, coding structure, advantages and disadvantages of using Python for game development, and suggests future enhancements to improve gameplay. The conclusion emphasizes the educational benefits of developing the game while encouraging continuous improvement based on player feedback.

Uploaded by

garikinakushal01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Karthiks_python_program-1

The document provides an overview of 'Flappy Tom', a Python-based game inspired by 'Flappy Bird', utilizing the Pygame library for graphics and sound. It outlines the game's components, coding structure, advantages and disadvantages of using Python for game development, and suggests future enhancements to improve gameplay. The conclusion emphasizes the educational benefits of developing the game while encouraging continuous improvement based on player feedback.

Uploaded by

garikinakushal01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

INTRODUCTION

"Flappy Tom" is a fun and engaging game designed using Python.


Inspired by the popular "Flappy Bird" game, "Flappy Tom" typically
involves guiding a character (Tom) through a series of obstacles by
tapping or clicking to make him fly.

The game leverages the Pygame library, which is a set of Python


modules designed for writing video games. Pygame provides
functionalities like creating windows, handling events, drawing
shapes, and playing sounds, making it perfect for developing 2D
games like "Flappy Tom."

Here are some key components often found in such a game:

 Game Loop: The core of the game that keeps it running and
updates the game state.
 Graphics and Sprites: Images representing the character and
obstacles, often stored in PNG format.
 Collision Detection: Logic to detect when Tom hits an obstacle
or the ground, which usually ends the game.
 Score Keeping: A system to track the player's progress, often
displayed on the screen during gameplay.
 User Input: Handling keyboard or mouse input to control
Tom's movements.
A Brief Introduction About Modules
Used In Program

 random:
This module is used to generate random numbers, which can be useful
for various game mechanics such as spawning obstacles at random
intervals or positions.

 sys:
This module provides access to some variables used or maintained by
the Python interpreter and to functions that interact strongly with the
interpreter. In game development, it’s often used to handle system-
level operations like exiting the game.

 pygame:
This is the main module required to create games with the pygame
library. pygame provides functionalities for rendering graphics,
playing sounds, and handling user inputs.
REQUIREMENTS:
HARDWARE REQUIREMENT:-
Minimum requirement of 5 mb RAM

SOFTWARE REQUIREMENT:-
PYTHON 3.12(works on any version of python 3)
OS: WINDOW 10 or Above
SYSTEM DESIGN
Flow chart
Steps involved
1. Install the latest version of Python.
 Import random module
 Import sys
2. Now go to command prompt and type the
given lines:-
 Pip install pygame

Here are the packages used in the code:


random: This is a built-in Python module used for generating random
numbers. In this code, it is used to generate random positions for the pipes.

sys: This is another built-in Python module that provides access to some
variables used or maintained by the interpreter. In this code, it is used to exit
the program.

pygame: This is the main library used for creating the game. It provides
functionalities for graphics, sound, and handling user input.
Coding
import random # For generating random numbers
import sys # We will use sys.exit to exit the program
import pygame
from pygame.locals import * # Basic pygame imports

# Global Variables for the game


FPS = 38
SCREENWIDTH = 338
SCREENHEIGHT = 548
SCREEN = pygame.display.set_mode((SCREENWIDTH,
SCREENHEIGHT))
GROUNDY = SCREENHEIGHT * 0.87
GAME_SPRITES = {}
GAME_SOUNDS = {}
PLAYER = 'gallery/sprites/tom.png'
BACKGROUND = 'gallery/sprites/background.png'
PIPE = 'gallery/sprites/pipe.png'

def welcomeScreen():
"""
Shows welcome images on the screen
"""

playerx = int(SCREENWIDTH/5)
playery = int((SCREENHEIGHT -
GAME_SPRITES['player'].get_height())/2)
messagex = int((SCREENWIDTH -
GAME_SPRITES['message'].get_width())/2)
messagey = int(SCREENHEIGHT*0.13)
basex = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type==KEYDOWN and
event.key == K_ESCAPE):
pygame.quit()
sys.exit()

# If the user presses space or up key, start the game for them
elif event.type==KEYDOWN and (event.key==K_SPACE or
event.key == K_UP):
return
else:
SCREEN.blit(GAME_SPRITES['background'], (0, 0))
SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
SCREEN.blit(GAME_SPRITES['message'],
(messagex,messagey ))
SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))
pygame.display.update()
FPSCLOCK.tick(FPS)

def mainGame():
score = 0
playerx = int(SCREENWIDTH/5)
playery = int(SCREENWIDTH/2)
basex = 0
# Create 2 pipes for blitting on the screen
newPipe1 = getRandomPipe()
newPipe2 = getRandomPipe()

# my List of upper pipes


upperPipes = [
{'x': SCREENWIDTH+200, 'y':newPipe1[0]['y']},
{'x': SCREENWIDTH+200+(SCREENWIDTH/2),
'y':newPipe2[0]['y']},
]
# my List of lower pipes
lowerPipes = [
{'x': SCREENWIDTH+200, 'y':newPipe1[1]['y']},
{'x': SCREENWIDTH+200+(SCREENWIDTH/2),
'y':newPipe2[1]['y']},
]

pipeVelX = -4

playerVelY = -9
playerMaxVelY = 10
playerMinVelY = -8
playerAccY = 1

playerFlapAccv = -8 # velocity while flapping


playerFlapped = False # It is true only when the bird is flapping

while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and
event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or
event.key == K_UP):
if playery > 0:
playerVelY = playerFlapAccv
playerFlapped = True
GAME_SOUNDS['wing'].play()

crashTest = isCollide(playerx, playery, upperPipes, lowerPipes) #


This function will return true if the player is crashed
if crashTest:
return

#check for score


playerMidPos = playerx + GAME_SPRITES['player'].get_width()/2
for pipe in upperPipes:
pipeMidPos = pipe['x'] +
GAME_SPRITES['pipe'][0].get_width()/2
if pipeMidPos<= playerMidPos < pipeMidPos +4:
score +=1
print(f"Your score is {score}")
GAME_SOUNDS['point'].play()

if playerVelY <playerMaxVelY and not playerFlapped:


playerVelY += playerAccY
if playerFlapped:
playerFlapped = False
playerHeight = GAME_SPRITES['player'].get_height()
playery = playery + min(playerVelY, GROUNDY - playery -
playerHeight)

# move pipes to the left


for upperPipe , lowerPipe in zip(upperPipes, lowerPipes):
upperPipe['x'] += pipeVelX
lowerPipe['x'] += pipeVelX

# Add a new pipe when the first is about to cross the leftmost
part of the screen
if 0<upperPipes[0]['x']<5:
newpipe = getRandomPipe()
upperPipes.append(newpipe[0])
lowerPipes.append(newpipe[1])

# if the pipe is out of the screen, remove it


if upperPipes[0]['x'] < -GAME_SPRITES['pipe'][0].get_width():
upperPipes.pop(0)
lowerPipes.pop(0)

SCREEN.blit(GAME_SPRITES['background'], (0, 0))


for upperPipe, lowerPipe in zip(upperPipes, lowerPipes):
SCREEN.blit(GAME_SPRITES['pipe'][0], (upperPipe['x'],
upperPipe['y']))
SCREEN.blit(GAME_SPRITES['pipe'][1], (lowerPipe['x'],
lowerPipe['y']))

SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))


SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
myDigits = [int(x) for x in list(str(score))]
width = 0
for digit in myDigits:
width += GAME_SPRITES['numbers'][digit].get_width()
Xoffset = (SCREENWIDTH - width)/2

for digit in myDigits:


SCREEN.blit(GAME_SPRITES['numbers'][digit], (Xoffset,
SCREENHEIGHT*0.12))
Xoffset += GAME_SPRITES['numbers'][digit].get_width()
pygame.display.update()
FPSCLOCK.tick(FPS)

def isCollide(playerx, playery, upperPipes, lowerPipes):


if playery> GROUNDY - 45 or playery<0:
GAME_SOUNDS['hit'].play()
return True

for pipe in upperPipes:


pipeHeight = GAME_SPRITES['pipe'][0].get_height()
if(playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) <
GAME_SPRITES['pipe'][0].get_width()):
GAME_SOUNDS['hit'].play()
return True

for pipe in lowerPipes:


if (playery + GAME_SPRITES['player'].get_height() > pipe['y']) and
abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width():
GAME_SOUNDS['hit'].play()
return True
return False

def getRandomPipe():
"""
Generate positions of two pipes(one bottom straight and one top
rotated ) for blitting on the screen
"""
pipeHeight = GAME_SPRITES['pipe'][0].get_height()
offset = SCREENHEIGHT/3
y2 = offset + random.randrange(0, int(SCREENHEIGHT -
GAME_SPRITES['base'].get_height() - 1.2 *offset))
pipeX = SCREENWIDTH + 10
y1 = pipeHeight - y2 + offset
pipe = [
{'x': pipeX, 'y': -y1}, #upper Pipe
{'x': pipeX, 'y': y2} #lower Pipe
]
return pipe

if __name__ == "__main__":
# This will be the main point from where our game will start
pygame.init() # Initialize all pygame's modules
FPSCLOCK = pygame.time.Clock()
pygame.display.set_caption('Flappy Tom by KUSHAL ROCK ')
GAME_SPRITES['numbers'] = (
pygame.image.load('gallery/sprites/0.png').convert_alpha(),
pygame.image.load('gallery/sprites/1.png').convert_alpha(),
pygame.image.load('gallery/sprites/2.png').convert_alpha(),
pygame.image.load('gallery/sprites/3.png').convert_alpha(),
pygame.image.load('gallery/sprites/4.png').convert_alpha(),
pygame.image.load('gallery/sprites/5.png').convert_alpha(),
pygame.image.load('gallery/sprites/6.png').convert_alpha(),
pygame.image.load('gallery/sprites/7.png').convert_alpha(),
pygame.image.load('gallery/sprites/8.png').convert_alpha(),
pygame.image.load('gallery/sprites/9.png').convert_alpha(),
)

GAME_SPRITES['message']
=pygame.image.load('gallery/sprites/message.png').convert_alpha()
GAME_SPRITES['base']
=pygame.image.load('gallery/sprites/base.png').convert_alpha()
GAME_SPRITES['pipe']
=(pygame.transform.rotate(pygame.image.load(
PIPE).convert_alpha(), 180),
pygame.image.load(PIPE).convert_alpha()
)

# Game sounds
GAME_SOUNDS['die'] =
pygame.mixer.Sound('gallery/audio/die.wav')
GAME_SOUNDS['hit'] =
pygame.mixer.Sound('gallery/audio/hit.wav')
GAME_SOUNDS['point'] =
pygame.mixer.Sound('gallery/audio/point.wav')
GAME_SOUNDS['swoosh'] =
pygame.mixer.Sound('gallery/audio/swoosh.wav')
GAME_SOUNDS['wing'] =
pygame.mixer.Sound('gallery/audio/wing.wav')

GAME_SPRITES['background'] =
pygame.image.load(BACKGROUND).convert()
GAME_SPRITES['player'] =
pygame.image.load(PLAYER).convert_alpha()

while True:
welcomeScreen() # Shows welcome screen to the user until he
presses a button
mainGame() # This is the main game function
print("GameOver”)
print("Tap to play again")

-------------------------------------***--------------------------------------
OUTPUTS
ADVANTAGES:
1. Learning Python: Building a game is a fun and engaging way to deepen your
understanding of Python programming. You'll get hands-on experience with
important concepts such as loops, conditionals, and functions.

2. Problem-Solving Skills: Game development involves solving many small and large
problems, such as collision detection, scoring systems, and game physics. This
enhances your problem-solving skills and logical thinking.
3. Creativity and Innovation: Developing a game allows you to express your
creativity. You can design characters, levels, and gameplay mechanics, making the
game unique and interesting.

4. Community and Collaboration: Game development often involves working with


others, sharing ideas, and getting feedback. This can help you build communication
skills and network with other developers

DISADVANTAGES:
1. Performance Issues: Python, being an interpreted language, might not be as
fast as compiled languages like C++ or Java. This could lead to performance issues,
especially in more complex games with heavy graphics or processing requirements

2. earning Curve: Although Python is considered beginner-friendly, learning to


develop games involves understanding concepts such as game loops, physics, and
user input handling. This might be challenging for beginners .

3. Limited Graphics Capabilities: While Pygame is a great library for 2D games, it


might not be sufficient for more advanced graphics. For more sophisticated 3D
games, you might need to use other languages and libraries.

4. Resource Management: Managing resources like images, sounds, and


animations can become cumbersome, especially as the game grows in complexity.
Python's memory management might also pose some challenges in handling these
resources efficiently
FUTURE ENHANCEMENT

Enhancing the "Flappy Tom" game in Python opens a world of exciting


possibilities. To make the game more engaging, you could add new levels with
increasing difficulty and introduce different obstacles, keeping players
challenged. Implementing power-ups and bonuses, such as invincibility or
bonus points, could add a dynamic element to the gameplay. Character
customization options, like different skins and outfits for Tom, would allow
players to personalize their experience. A multiplayer mode could bring a
competitive edge, enabling players to compete in real-time. Achievements and
online leaderboards would encourage players to achieve high scores and
complete specific challenges. Improving graphics and adding smooth
animations could enhance the visual appeal, while more sound effects and
background music could create an immersive experience. A story mode with a
narrative unfolding as players progress through levels would add depth, and
interactive tutorials could guide new players, making the game more
accessible. Regular updates with new content and features based on player
feedback would keep the game fresh and maintain player interest over time.
With these enhancements, "Flappy Tom" could become a more captivating and
enjoyable game for all players.
CONCLUSION
In conclusion, developing the "Flappy Tom" game in Python offers an exciting
opportunity to enhance your programming skills, creativity, and problem-
solving abilities. While there may be some challenges, such as performance
issues and the learning curve associated with game development, the benefits
far outweigh them. Creating new levels, implementing power-ups, customizing
characters, adding multiplayer modes, and improving graphics and sound are
just a few ways to make the game more engaging and enjoyable. Additionally,
building a project like "Flappy Tom" can be a valuable addition to your
portfolio, showcasing your abilities to potential employers and collaborators.
By continuously updating and refining the game based on feedback, you can
ensure that "Flappy Tom" remains fresh, fun, and captivating for players.
Embrace the journey of game development, and you'll find it both rewarding
and fulfilling.
BIBLIOGRAPHY
SITES REFFERED:
Stackoverflow
Scribed
youtube

You might also like