Back to Home

Part 3 || Gaming in python || pygame

Mar 7, 2018 1 min read ... views
Python game tutorial
Advertisement








python game code:
# Import a library of functions called 'pygame'
import pygame
# Initialize the game engine

pygame.init()
display_width=800
display_height=600
img_width=100
black=(0,0,0)
white=(255,255,255)
red=(255,0,0)


gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Cool Game")
clock=pygame.time.Clock()


carImg= pygame.image.load('car.png')

def car(x,y):
gamedisplay.blit(carImg,(x,y))

def gamerender():
x=(display_width * 0.45)
y=(display_height * 0.65)
x_change=0
crashed=False
while not crashed:
for event in pygame.event.get():

if event.type == pygame.QUIT:
crashed= True
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
x_change=-5
if event.key==pygame.K_RIGHT:
x_change=5
if event.type==pygame.KEYUP:
if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT:
x_change=0

x+=x_change

gamedisplay.fill(red) #print(event)
car(x,y)
if x<0 or x>display_width-img_width:
crashed=True

pygame.display.update()
clock.tick(60)
gamerender()
pygame.quit()

quit()
Keywords:



how to make a game in python for beginners

python game car

python game programming tutorial

how to make a game in python with pygame

invent your own computer games with python

python games

python games code

python game programming

python games code

python game code copy and paste



Advertisement
P

Written by Puru

I am a software builder, developer, and technical writer. I design web products like JSON2Apex and the Python Visualizer. I write these guides to share actual, real-world development solutions and lifestyle strategies. No corporate fluff, just practical code and direct insights.

Need help? Ask our AI guide! 👋