I am trying to make a game in pygame, but i am getting two bugs.
Bug 1
My score increases abruptly in the game , where my condition is to increase only 1 point at a time.
My code to increase score is:
if thing_starty >display_height:
thing_stary = 0-thing_height
thing_startx= random.randrange(0,display_width)
dodged += 1
thing_speed += 1
thing_width += (dodged * 1.2)
Here dodged is my score , it should increase by one every time the block goes off the screen.
Bug 2
In my game there is a black rectangle following from top, but the thing is once it goes off the screen, it does not come back.Also after the block passes outside the screen , the game ends even if there is no collision.
The code for the block to come back is:
if thing_starty >display_height: #Check if block is there in the screen or not
thing_stary = 0 - thing_height
thing_startx= random.randrange(0,display_width)
dodged += 1
thing_speed += 1
thing_width += (dodged * 1.2)
Full code:
import pygame
import time
import random
pygame.init()
#Colours
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
#Game Display
display_width = 1080
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Eat It! ~ Snapnel Productions')
#Clock
clock = pygame.time.Clock()
FPS = 60
#Font Size
exsmallfont = pygame.font.SysFont("comicsansms", 17)
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)
#Car
def car(x,y):
gameDisplay.blit(carimg,(x,y))
global x, y, x_change
carimg=pygame.image.load('food.png')
#With of the car( i.e food image)
car_width=10
#Things
def things(thingx,thingy,thingw,thingh,color):
pygame.draw.rect(gameDisplay,color,[thingx,thingy,thingw,thingh])
#Things doged
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, red)
gameDisplay.blit(text,(0,0))
#Starting Of the game
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key ==pygame.K_c:
intro = False
if event.key ==pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(black)
#Game Initial display message
message_to_screen("Dodge It!",
red,
-200,
size="large")
message_to_screen("Press 'C' to play the game or 'Q' to quit.",
white,
150,
size="small")
pygame.display.update()
clock.tick(15)
#Text Size
def text_objects(text,color, size):
if size=="small":
textSurface=smallfont.render(text, True ,color)
elif size=="medium":
textSurface=medfont.render(text, True ,color)
elif size=="large":
textSurface=largefont.render(text, True ,color)
return textSurface,textSurface.get_rect()
#Message to screen
def message_to_screen(msg,color,y_displace=0,size="small"):
textSurf,textRect=text_objects(msg,color,size)
textRect.center = (display_width / 2),(display_height / 2)+y_displace
gameDisplay.blit(textSurf,textRect)
#The Game run up
def runGame():
#global x,y, x_change
gameExit = False
gameOver = False
x=(display_width*0.45)
y=(display_height*0.48)
x_change =0
#To count score
thingCount=1
dodged=0
#Block Initial Size
thing_startx = random.randrange(0,display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
while not gameExit:
while gameOver == True:
#Game Over message
gameDisplay.fill(white)
message_to_screen("Game over",
red,
y_displace=-50,
size="large")
message_to_screen("Press C to play again or Q to quit.",
red,
y_displace=50,
size="medium")
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
#Game Controls
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif 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(white)
things(thing_startx,thing_starty,thing_width,thing_height,black)
thing_starty+=thing_speed
car(x,y)
things_dodged(dodged)
if x>display_width-car_width or x<0:
gameOver = True
#Check if block is in the screen
if thing_starty >display_height:
thing_stary = 0 - thing_height
thing_startx= random.randrange(0,display_width)
dodged += 1
thing_speed += 1
thing_width += (dodged * 1.2)
#Check Collision with block
if y < thing_starty+thing_height:
print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x+car_width > thing_startx and x + car_width < thing_startx+thing_width:
print('x crossover')
gameOver = True
pygame.display.update()
#The game run up
def gameLoop():
clock.tick(FPS)
runGame()
pygame.quit()
quit()
game_intro()
gameLoop()
is the food image.
Thanks in advance fellows , really , thanks to pay attention to this bug.
You have a typo in your variable name, it should likely be:
thing_starty
instead of:
thing_stary
Related
I'm attempting to detect a collision between two objects (both images).
I have rect's for both the objects, but cannot get the collision to be detected.
I've attempted to use rect's, comparing x and y positions.
import sys
import pygame
from pygame.locals import *
#init pygame
pygame.init()
window_width = 840
window_height = 650
size = (window_width, window_height)
screen = pygame.display.set_mode(size)
bg_img = pygame.image.load("img.png").convert_alpha()
crash = False
bot1x = 150
bot1y = 100
x = (window_width * 0.45)
y = (450)
clock = pygame.time.Clock()
fr = clock.tick(30)
x_speed = 0
car_img = pygame.image.load("car.png").convert_alpha()
car_img = pygame.transform.scale(car_img, (125, 175))
bot_img = pygame.image.load("bot.png").convert_alpha()
bot_img = pygame.transform.scale(bot_img, (175, 200))
def car(x, y):
screen.blit(car_img, (x,y))
def bot(x, y):
screen.blit(bot_img, (x,y))
car_rect = pygame.Rect(x, y, 125, 175)
bot_rect = pygame.Rect(bot1x, bot1y, 175, 200)
#game loop
while(crash==False):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_LEFT:
x_speed = -.9
print("Moving Left")
if event.key == K_RIGHT:
x_speed = .9
print("Moving Right")
if event.type == pygame.KEYUP:
if event.key == K_LEFT:
x_speed = 0
if event.key == K_RIGHT:
x_speed= 0
if event.type == pygame.QUIT:
crash = True
bot1y += .5
# Move car
x += x_speed
if car_rect.colliderect(bot_rect):
print("collision deceted")
#blit images to screen
screen.blit(bg_img, [0, 0])
#spawn car
car(x,y)
bot(bot1x, bot1y)
#flip game display
pygame.display.flip()
#end game
pygame.quit()
quit()
I expect the game to output "Collision detected" when the two objects touch eachother.
Thanks,
Lachlan
This question already has answers here:
How do I detect collision in pygame?
(5 answers)
Pygame how to let balls collide
(2 answers)
pygame Get the balls to bounce off each other
(1 answer)
Closed 2 years ago.
ltcImgI am making a simple game where a car dodges some objects, all of which I am importing using pictures from the internet. What would be the best way to configure circular hitboxes that would work well when running into the square box of my car?
CarImg
Right now I have them put into length and width parameters, since that is all I really know how to do. For some reason, my hitboxes are ending the game good on the left side of my "ltc" circle, but when I cross the boundaries of the circle on the right side, even though I do not actually "hit" the circle, it is causing me to crash and ending the game.
I have tried adjusting my ltcw and ltch to see if it makes it better, but I can only seem to make it worse overall. I couldn't find anything online referencing specifically circular hitboxes when using imported pictures when running into square hitboxes.
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
car_width = 60
car_height = 113
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('TRX: FuD Racer')
clock = pygame.time.Clock()
carImg = pygame.image.load('RaceCar2.png')
ltcImg = pygame.image.load('LtcLogo.png')
xlmImg = pygame.image.load('Stell_Logo.png')
def car(x, y):
gameDisplay.blit(carImg, (x, y))
def ltc(x, y):
gameDisplay.blit(ltcImg, (x, y))
def stell(x, y):
gameDisplay.blit(xlmImg, (x, y))
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return (textSurface, textSurface.get_rect())
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 75)
(textSurf, textRect) = text_objects(text, largeText)
textRect.center = (display_width / 2, display_height / 2)
gameDisplay.blit(textSurf, textRect)
pygame.display.update()
time.sleep(3)
game_loop()
def crash():
message_display('You Sold Your Tron!')
def game_loop():
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
y_change = 0
# I should adjust each coins speed in game in accordance with their transaction speeds
ltc_startx = random.randrange(0, display_width)
ltc_starty = -300
ltc_speed = 2
ltcw = 222
ltch = 200
stell_startx = random.randrange(0, display_width)
stell_starty = -600
stell_speed = 6
stellw = 300
stellh = 450
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -6
elif event.key == pygame.K_RIGHT:
x_change = 6
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -6
elif event.key == pygame.K_DOWN:
y_change = 6
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key \
== pygame.K_DOWN:
y_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key \
== pygame.K_RIGHT:
x_change = 0
x += x_change
y += y_change
gameDisplay.fill(WHITE)
ltc(ltc_startx, ltc_starty)
ltc_starty += ltc_speed
car(x, y)
stell(stell_startx, stell_starty)
stell_starty += stell_speed
car(x, y)
if x > display_width - car_width or x < -15:
crash()
if ltc_starty > display_height:
ltc_starty = 0 - ltch
ltc_startx = random.randrange(0, display_width - ltcw)
if stell_starty > display_height:
stell_starty = 0 - stellh
stell_startx = random.randrange(0, display_width - stellw)
if y < 0:
crash()
if y < ltc_starty + ltch:
print 'y crossover'
if x > ltc_startx and x < ltc_startx + ltcw or x \
+ car_width > ltc_startx and x + car_width < ltc_startx \
+ ltcw:
print 'x crossover'
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
I want to make rectangles out from the right edge
How can I make these rectangles move horizontally?
I tried to understand it from this tutorial but I couldn't here
so any ideas about this
my little character ghost
btata.png
import pygame
from pygame.locals import *
import sys
import time
import random
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('FullMarx')
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
crashed = False
ghostImg = pygame.image.load('btata.png')
clock = pygame.time.Clock()
def ghost(x,y):
gameDisplay.blit(ghostImg, (x,y))
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',20)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
def gameOver():
message_display('Game Over')
def rect():
pygame.draw.rect(screen, color, (x,y,width,height), thickness)
def event():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
def game():
ghost_width = 50
x = 20
y = 180
isJump = False
jumpCount = 9
#x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -300
thing_speed = 7
thing_width = 30
thing_height = 30
while True:
event()
gameDisplay.fill(white)
ghost(x,y)
#____Ghost_Motion___________#
keys = pygame.key.get_pressed()
if not(isJump):
if keys[pygame.K_UP] or keys[pygame.K_SPACE] or keys[pygame.K_w]:
isJump = True
walkCount = 0
else:
if jumpCount >= -9:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 9
clock.tick(50)
#____Ghost_Motion___________#
# things(thingx, thingy, thingw, thingh, color)
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
ghost(x,y)
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0,display_width)
if y < thing_starty+thing_height:
print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x+ghost_width > thing_startx and x + ghost_width < thing_startx+thing_width:
print('x crossover')
gameOver()
pygame.display.update()
#clock.tick(60)
game()
pygame.quit()
quit()
You move a rect (and therefore a player/an image) by modifying its x and y coordinates.
Here's a rudimentary and commented example to help you visualize:
import pygame
from pygame.locals import *
# Initialize a screen
SCREEN = pygame.display.set_mode((700, 500))
# Fill it with black
SCREEN.fill((0, 0, 0))
# Create a rect that'll represent our player
# Arguments: x, y, width, height
player = pygame.rect.Rect(100, 100, 20, 50)
# Keep track of which direction
# the player is moving in
moving_left = False
moving_right = False
moving_up = False
moving_down = False
# Loop
while True:
for event in pygame.event.get():
# Go through every event that pygame
# records, the 'event queue' and
# react accordingly
# User closed the window
if event.type == QUIT:
pygame.quit()
# If the user presses any key, a
# KEYDOWN event is placed into the
# event queue, and we detect it here
if event.type == KEYDOWN:
# The pressed key is 'd'
if event.key == K_d:
moving_right = True
# The pressed key is 'a'
if event.key == K_a:
moving_left = True
# The pressed key is 'w'
if event.key == K_w:
moving_up = True
# The pressed key is 's'
if event.key == K_s:
moving_down = True
# However, if the user lifts stops
# pressing the keyboard,
# a KEYUP event will be placed into
# the event queue
if event.type == KEYUP:
# The unpressed key is 'd'
if event.key == K_d:
moving_right = False
# The unpressed key is 'a'
if event.key == K_a:
moving_left = False
# The unpressed key is 'w'
if event.key == K_w:
moving_up = False
# The unpressed key is 's'
if event.key == K_s:
moving_down = False
# Increment/decrement the players
# coordinates, its 'position'
# this is akin to movement
if moving_left:
player.x -= 2
if moving_right:
player.x += 2
if moving_up:
player.y -= 2
if moving_down:
player.y += 2
# Repaint our screen black,
SCREEN.fill((0, 0, 0))
# draw our player (the rect)
# onto the SCREEN, at its coordinates
# in white.
# You'd simply use SCREEN.blit
# here in order to place an image
pygame.draw.rect(
SCREEN, (255, 255, 255),
player
)
# refresh the screen to show our changes
pygame.display.update()
You've got to conceptualize movement on a 2D surface like so:
This question already has answers here:
Add scrolling to a platformer in pygame
(4 answers)
Closed 5 years ago.
I'm a beginner at python and pygame. What would be a good condensed way to have a camera move with the play? (With the player being in the middle of the screen always) I've tried multiple things but they just don't work the way I want them to. Again I'm new so if it's a dumb question, let me know. Thanks in advance to anyone who bothers answering at all.
import pygame
import random
import time
pygame.init()
display_width = 1200
display_height = 1000
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
player_width = 24
player_height = 42
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Random RPG')
clock = pygame.time.Clock()
PMF = ("PlayerModel_Forward.png")
playerSprt = pygame.image.load(PMF)
def player(x,y):
gameDisplay.blit(playerSprt,(x,y))
def enemy1(enemy1x, enemy1y, enemy1w, enemy1h, color):
pygame.draw.rect(gameDisplay, color, [enemy1x, enemy1y, enemy1w, enemy1h])
def death():
message_display('Game Over')
def text_objects(text, font):
textSurface = font.render(text,
True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
pygame.display.update()
game_loop()
def frames(fps):
font = pygame.font.SysFont(None, 25)
text = font.render(str(fps), True, black)
gameDisplay.blit(text,(0,0))
def xcoord(x_coord):
font = pygame.font.SysFont(None, 25)
text = font.render((str(x_coord)), True, black)
gameDisplay.blit(text,(display_width/2,0))
def ycoord(y_coord):
font = pygame.font.SysFont(None, 25)
text = font.render((str(y_coord)), True, black)
gameDisplay.blit(text,(display_width/2,25))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_loop():
x = (display_width/2)
y = (display_height/2)
x_change = 0
y_change = 0
enemy1_startx = random.randrange(0, display_width)
enemy1_starty = random.randrange (0, display_height)
enemy1_x_change = random.randrange (-5,5)
enemy1_y_change = random.randrange (-5,5)
enemy1_width = 100
enemy1_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif 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
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
y_change = 5
elif event.key == pygame.K_UP:
y_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0
x+= x_change
y+= y_change
Fps = 30
#Logic
if gameExit == True:
pygame.quit()
quit()
if x > display_width - player_width or x < 0:
death()
if y > enemy1_starty and y < enemy1_starty + enemy1_width or y+player_width > enemy1_starty and y + player_width < enemy1_starty + enemy1_width:
if x > enemy1_startx and x < enemy1_startx + enemy1_width or x+player_width > enemy1_startx and x + player_width < enemy1_startx + enemy1_width:
death()
time.sleep(2)
game_loop()
if enemy1_starty > display_height or enemy1_starty < 0 or enemy1_startx > display_width or enemy1_startx < 0:
enemy1_starty = random.randrange (0, display_height)
enemy1_startx = random.randrange(0, display_width)
enemy1_x_change = random.randrange (-5,5)
enemy1_y_change = random.randrange (-5,5)
#Drawing:
gameDisplay.fill(black)
player(x,y)
enemy1 (enemy1_startx, enemy1_starty, enemy1_width, enemy1_height, red)
enemy1_starty += enemy1_y_change
enemy1_startx += enemy1_x_change
frames((Fps))
xcoord (x)
ycoord (y)
pygame.display.update()
clock.tick(Fps)
game_loop()
pygame.quit()
quit()
You're doing really well! I think you may have taken the wrong approach, because instead of an actual camera moving ( which is insanely difficult to implement), the same effect can be reached, by moving every other element on the screen. So when the user presses right, instead of the player moving right, move the enemy left!: relevant code:
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
enemy1_startx = enemy1_startx+10
elif event.key == pygame.K_RIGHT:
enemy1_startx = enemy1_startx-10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
enemy1_starty = enemy1_starty - 10
elif event.key == pygame.K_UP:
enemy1_starty = enemy1_starty + 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0
I know people already asked this but my code is very different and their solution does not apply to my problem.
I am trying to make a game where the objective is to "catch" the fruit. However, whenever my basket touches the fruit, the fruit goes right past the basket. Here is my code:
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
car_width = 64
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Avoid The Falling Objects')
clock = pygame.time.Clock()
carImg = pygame.image.load('basket.png')
appleImg = pygame.image.load('apple.png')
score = 0
def things(thingx, thingy):
#pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])\
gameDisplay.blit(appleImg, (thingx,thingy))
def car(x,y):
gameDisplay.blit(carImg, (x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',40)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display(('You dropped a fruit! Your score was: {}').format(score))
def game_loop():
score = 0
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif 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(white)
things(thing_startx, thing_starty)
thing_starty += thing_speed
car(x,y)
if x > display_width - car_width or x < 0 - car_width:
crash()
if thing_starty > display_height:
crash()
if y < thing_starty+thing_height:
print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx:
score += 1
thing_starty = -100
thing_startx = random.randrange(0, display_width)
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
You could use pygame.Rect() and colliderect() to check collision.
import pygame
import random
# --- constants --- (UPPER_CASE names)
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
CAR_WITDH = 64
# --- functions --- (lower_case names)
def text_objects(text, font):
text_image = font.render(text, True, BLACK)
return text_image, text_image.get_rect()
def message_display(text):
large_font = pygame.font.Font('freesansbold.ttf',40)
text_image, text_rect = text_objects(text, large_font)
text_rect.center = screen_rect.center
screen.blit(text_image, text_rect)
pygame.display.update()
pygame.time.delay(2000)
def crash(score):
message_display(('You dropped a fruit! Your score was: {}').format(score))
def reset_positions():
car_rect.x = DISPLAY_WIDTH * 0.45
car_rect.y = DISPLAY_HEIGHT * 0.8
apple_rect.x = random.randrange(0, DISPLAY_WIDTH)
apple_rect.y = -600
def game_loop():
score = 0
x_change = 0
apple_speed = 7
reset_positions()
clock = pygame.time.Clock()
while True:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
x_change = 0
# --- updates (without draws) ---
car_rect.x += x_change
apple_rect.y += apple_speed
if car_rect.right > DISPLAY_WIDTH or car_rect.left < 0:
crash(score)
reset_positions()
score = 0
if apple_rect.bottom > DISPLAY_HEIGHT:
crash(score)
reset_positions()
score = 0
if car_rect.colliderect(apple_rect):
score += 1
car_rect.y -= 10
apple_rect.x = random.randrange(0, DISPLAY_WIDTH-apple_rect.width)
apple_rect.y = -600
# --- draws (without updates) ---
screen.fill(WHITE)
screen.blit(apple_image, apple_rect)
screen.blit(car_image, car_rect)
pygame.display.update()
# --- FPS ---
clock.tick(60)
# --- main --- (lower_case names)
# - init -
pygame.init()
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
screen_rect = screen.get_rect()
pygame.display.set_caption('Avoid The Falling Objects')
# - objects -
car_image = pygame.image.load('basket.png')
car_rect = car_image.get_rect()
apple_image = pygame.image.load('apple.png')
apple_rect = apple_image.get_rect()
# - mainloop -
game_loop()