I can not get my collision to work in pygame - python

import pygame, time, random
pygame.init()
display_width = 800
display_height = 600
white = (255,255,255)
green = (0,255,0)
black = (0,0,0)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
boy = pygame.image.load("pig.png")
fence = pygame.image.load("fence.png")
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)
game_loop()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def crash():
message_display("Game Over")
def fence1(fencex, fencey, fencew, fenceh, color):
gameDisplay.blit(fence, (fencex, fencey, fencew, fenceh))
def collision():
pig_image = pygame.image.load("pig.png")
pig_rect = pig_image.get_rect()
fence_image = pygame.image.load("fence.png")
fence_rect = fence_image.get_rect()
if pig_rect.colliderect(fence_rect):
crash()
def game_loop():
fence_startx = 900
fence_starty = gameDisplay.get_height() * 0.8
fence_speed = 15
fence_width = 50
fence_height = 50
x = gameDisplay.get_width() * 0.1
y = gameDisplay.get_height() * 0.8
y_change = 0
on_ground = True
gravity = .9
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if on_ground:
y_change = -20
on_ground = False
y_change += gravity
y += y_change
if y >= 500:
y = 500
y_change = 0
on_ground = True
gameDisplay.fill(green)
gameDisplay.blit(boy, (x, y))
fence1(fence_startx, fence_starty, fence_width, fence_height, white)
fence_startx -= fence_speed
randomx = random.randint(1,3)
if fence_startx <= -50:
if randomx == 1:
fence_startx = 1000
if randomx == 2:
fence_startx = 800
if randomx == 3:
fence_startx = 1500
collision()
pygame.display.flip()
clock.tick(60)
game_loop()
pygame.quit()
quit()
For some reason when I run this code, it spams me "Game Over". Could someone please help me on this issue. I use a collision function in this code. Is using the pygame.rect code the best way to do collision in pygame? Everything works except for my collision in the game. I would greatly appreciate some help. Thanks.

In the collision function you create two rects but leave their coordinates at the default position (0, 0) so the rects overlap. You should add rects for the player and the fence in the main game_loop function, set their x and y (or the topleft) attributes to the desired coordinates and then update them every iteration of the while loop. To check if the rects collide, pass them to the collision function and do this:
def collision(boy_rect, fence_rect):
if boy_rect.colliderect(fence_rect):
# I'm just printing it to shorten the code example.
print('crash')
Here's a minimal, complete example:
import random
import pygame
pygame.init()
green = (0,255,0)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
boy = pygame.Surface((40, 60))
boy.fill((0, 40, 100))
fence = pygame.Surface((50, 50))
fence.fill((100, 60, 30))
def collision(boy_rect, fence_rect):
if boy_rect.colliderect(fence_rect):
# I'm just printing it to shorten the code example.
print('crash')
def game_loop():
fence_speed = 15
# Create a fence and a boy rect and set their x,y or topleft coordinates.
fence_rect = fence.get_rect()
fence_rect.x = 900
fence_rect.y = gameDisplay.get_height() * 0.8
x = gameDisplay.get_width() * 0.1
y = gameDisplay.get_height() * 0.8
boy_rect = boy.get_rect(topleft=(x, y))
y_change = 0
on_ground = True
gravity = .9
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if on_ground:
y_change = -20
on_ground = False
y_change += gravity
y += y_change
if y >= 500:
y = 500
y_change = 0
on_ground = True
boy_rect.y = y # Update the rect position.
gameDisplay.fill(green)
gameDisplay.blit(boy, boy_rect)
gameDisplay.blit(fence, fence_rect)
# Update the position of the fence rect.
fence_rect.x -= fence_speed
if fence_rect.x <= -50:
# You can use random.choice to pick one of these values.
fence_rect.x = random.choice((800, 1000, 1500))
# Pass the two rects and check if they collide.
collision(boy_rect, fence_rect)
pygame.display.flip()
clock.tick(60)
game_loop()
pygame.quit()

Related

How to fill in colour between the grid in my snake application

I am having this problem where I can draw a grid for my snake but I cant fill in the colour between it.It seems like the problem is that because the grid on the surface overrides the actual colour of the background but I dont know how to fix this, can anyone who knows more about pygame help.
See line 74 of my code and that is the colour it should be.
How could I optimise this simple python pygame code
import pygame
import time
import random
pygame.init()
display_width = 960
display_height = 540
display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Snake")
pureblue = (0,0,255)
purered = (255,0,0)
puregreen = (0,255,0)
green = (0,150,0)
white = (255,255,255)
black = (1,1,1)
grey = (75,75,75)
darkgrey = (50,50,50)
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 5
font_style = pygame.font.SysFont(None, 50)
def drawGrid(surf):
blockSize = snake_block
for x in range(display_width):
for y in range(display_height):
rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
pygame.draw.rect(surf, darkgrey, rect, 1)
grid_surf = pygame.Surface(display.get_size())
drawGrid(grid_surf)
def message(msg, colour):
text = font_style.render(msg, True, colour)
display.blit(text, [display_width/2, display_height/2])
def SnakeGameLoop():
game_over = False
X = display_width/2
Y = display_height/2
X_change = 0
Y_change = 0
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
X_change = -snake_block
Y_change = 0
elif event.key == pygame.K_RIGHT:
X_change = snake_block
Y_change = 0
elif event.key == pygame.K_UP:
X_change = 0
Y_change = -snake_block
elif event.key == pygame.K_DOWN:
X_change = 0
Y_change = snake_block
if X >= display_width or X < 0 or Y >= display_height or Y < 0:
game_over = True
X += X_change
Y += Y_change
display.fill(grey)
display.blit(grid_surf, (0,0))
pygame.draw.rect(display,puregreen,[X,Y,snake_block,snake_block])
pygame.display.update()
clock.tick(snake_speed)
message("You lost", purered)
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
SnakeGameLoop()
You need to fill the grid Surface with the background color:
def drawGrid(surf):
surf.fill(grey) # <--- ADD
blockSize = snake_block
for x in range(display_width):
for y in range(display_height):
rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
pygame.draw.rect(surf, darkgrey, rect, 1)
grid_surf = pygame.Surface(display.get_size())
drawGrid(grid_surf)
Since the grid Surface covers the entire display it is not necessary to clear the display in the application loop:
def SnakeGameLoop():
# [...]
while not game_over:
# [...]
# display.fill(grey) <--- DELETE
display.blit(grid_surf, (0,0))
pygame.draw.rect(display,puregreen,[X,Y,snake_block,snake_block])
pygame.display.update()
# [...]

How to fix collisions in pygame

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

how can I reflect the screen in pygame

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:

What syntax am I not seeing or entering correctly via python?

I've been learning Python the easy (for me) way: simple video game example tutorials from sentdex on youtube. The concepts which I had not already known are made much clearer in the context of something for which I see value like a simple game. Anyway, I have come to an issue; for some reason, I cannot get a menu page to blit. I originally followed the tutorial very closely, with an eye for punctuation, capitalization and proper indentation as I see that seems to be the n00bs most consistent pitfall. However, the tutorial did not work for that section, and the program goes right into the game loop, even when game over. I have tried other methods prescribed throughout here, google, and youtube, but nothing seems to be working! I get a non-descriptive "syntax error", but as far as I can tell, the vital bits are wired up right. I'm sure I'm just being a blind noob, but some simple analysis would be much appreciated on this code!
NOTE: I know I have some danglers like how I imported Pickle but haven't used it yet, those are all just reminders for the next steps, soon to be fleshed out as soon as this menu problem is resolved.
Running python (with pygame) 2.7, since I cant get pygame to work on python 3.
I have both Eric5 and pycharm, I am running Debian Jessie with a backported Cinnamon (And I believe the kernel to, but I might be wrong)
#!/urs/bin/python2.7
import random
import pygame
import time
##import pickle
pygame.init()
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Zoomin' Zigs")
#Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
#asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
menuactive = True
#FUNCTIONS
##def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
##def leftclick():
##
## if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
## mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades (smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
time.sleep(3)
menuscreen()
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
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)
def button(x, y, w, h,):
if x+w > mousecoords[0] > x and y+h > mousecoords[1] >y:
pygame.quit()
quit()
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, blue)
gamedisplay.blit(text, (30,100))
################################MENU###################################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
else:
time.sleep(3)
game_loop()
gamedisplay.blit(menuimage (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP###############################################
def game_loop():
#CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
#SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
while not menuactive:
for event in pygame.event.get():
# GAME QUIT EVENT
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades (smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
#OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
#DODGE COUNT
dodged += 1
#CRASHESloop
if y <= smbar_starty+smbar_height and y >= smbar_starty+smbar_height and x <= smbar_startx+car_width and x >= smbar_startx-car_width:
crash()
menuactive = True
pygame.display.update()
clock.tick(60)
########################################################################################
menuscreen()
game_loop()
pygame.quit()
quit()
Hey I saw your code and did necessary changes And Its Working now next time kindly provide us the whole details.
#!/urs/bin/python2.7
import random
import pygame
import time
# import pickle
menuactive = True
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Zoomin' Zigs")
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
# asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
# FUNCTIONS
# def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
# def leftclick():
##
# if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades(smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
# menuscreen()
# def button(x, y, w, h,):
# mousecoords = pygame.mouse.get_pos()
# if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
# pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
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)
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x + w > mousecoords[0] > x and y + h > mousecoords[1] > y:
# pygame.quit()
# quit()
global menuactive
menuactive = False
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, blue)
gamedisplay.blit(text, (30, 100))
################################MENU######################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
global menuactive
while menuactive:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
menuactive = False
else:
# time.sleep(3)
game_loop()
gamedisplay.blit(menuimage, (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP#################################
def game_loop():
# CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
# SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
global menuactive
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# pygame.quit()
menuactive = False
# CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades(smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
# OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
# DODGE COUNT
dodged += 1
# CRASHESloop
if y <= smbar_starty + smbar_height and y >= smbar_starty + smbar_height and x <= smbar_startx + car_width and x >= smbar_startx - car_width:
crash()
menuactive = False
pygame.display.update()
clock.tick(60)
##########################################################################
if __name__ == '__main__':
pygame.init()
menuscreen()
# game_loop()
pygame.quit()
quit()

How to tell if a sprite is touching another sprite in pygame

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()

Categories

Resources