Double moving images collision [duplicate] - python

This question already has an answer here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Closed 2 years ago.
In this game I am creating one image is controlled by the players using arrows (racecar) and two images (banana) which move in a defined direction and speed (which is slowed down for now so I could see better what was happening) but their starting point is random. The goal would be for the car to avoid these blocks and to reach the finish line, only when going forward it is then impossible to pass these bananas without the crash segment to start even when there is clearly no contact. It is quit tricky because things move on the X axis. please help me.
Here is the code segment for collision between the two images:
if x + car_width >= banX:
print('ycollision')
if y + car_width >= banX and y + car_width <= banX + ban_height or ybottom + car_width >= banX and ybottom + car_width <= banX + ban_height:
print('xcollision')
crash()
Here is the whole code:
import pygame
import random
import time
pygame.init()
#Colors
black = (0,0,0)
white = (255,255,255)
grey = (96,96,96)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
#Setting and variables
display_width = 1570
display_height = 450
car_width = 98
car_height = 66
clock = pygame.time.Clock()
wn = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('My own game')
#racecar
carImg = pygame.image.load('myOwnRGame.png')
Xchange = 0
Ychange = 0
y = 192
x = 10
def car(x,y):
wn.blit(carImg, (x,y))
#finish line
finish_line = pygame.image.load('myOwnFinishreal.png')
Xfin = 1480
Yfin = 0
def finish():
wn.blit(finish_line, (Xfin, Yfin))
#Crashing and wining
def textObjects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def displayMessage(text):
textFont1 = pygame.font.Font('freesansbold.ttf', 32)
textSurf, textRect = textObjects(text, textFont1)
textRect.center = ((display_width/2),(display_height/2))
while True:
wn.blit(textSurf, textRect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.display.quit()
pygame.quit()
if event.key == pygame.K_SPACE:
gameLoop()
pygame.display.update()
def crash():
displayMessage('You crashed!Press X to quit, _SPACE_ to restart!')
def win():
displayMessage('Bravo! You are the best car runner! Press X to quit and _SPACE_ to restart.')
#Banana widht48 height26
banImg = pygame.image.load('myOwnBanana.png')
ban_width = 48
ban_height = 26
def banana(banX, banY):
wn.blit(banImg, (banX, banY))
def banana2(banX, banY2):
wn.blit(banImg, (banX, banY2))
#Game loop
def gameLoop():
y = 192
x = 10
Xchange = 0
Ychange = 0
banX = 1600
banY = random.randrange(-5, (display_height - 21))
banY2 = random.randrange(-5, (display_height - 21))
ban_change = -3
alive = True
losing = True
while alive and losing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.display.quit()
pygame.quit()
if event.key == pygame.K_UP:
Xchange = 0
Ychange = 0
Xchange = 2.5
elif event.key == pygame.K_LEFT:
Xchange = 0
Ychange = 0
Ychange = -3
elif event.key == pygame.K_RIGHT:
Xchange = 0
Ychange = 0
Ychange = 3
elif event.key == pygame.K_DOWN:
Xchange = 0
Ychange = 0
Xchange = -3
#Borders
if y <= -15 or y >= display_height - 15:
Xchange = 0
Ychange = 0
ban_change = 2.5
crash()
if x >= display_width:
Xchange = 0
Ychange = 0
ban_change = 2.5
win()
if x <= 0:
x = 10
#Banana spon
if banX <= 0:
banY = random.randrange(-5, (display_height - 21))
banY2 = random.randrange(-5, (display_height - 21))
banX = 1540
x += Xchange
y += Ychange
ybottom = y + car_height
#Banana collision
if x + car_width >= banX:
print('ycollision')
if y + car_width >= banX and y + car_width <= banX + ban_height or ybottom + car_width >= banX and ybottom + car_width <= banX + ban_height:
print('xcollision')
crash()
wn.fill(grey)
finish()
car(x, y)
banana(banX, banY)
banana2(banX, banY2)
banX += ban_change
pygame.display.update()
clock.tick(60)
pygame.display.quit()
pygame.quit()
gameLoop()
Question summary: How could I make the bananas and car collide but still be able to dodge the collision by moving the car?

I recommend to draw the objects before invoking crash, to show the actual position of the objects when crashing. Note the objects have been moved, but not redrawn before the crash
wn.fill(grey)
finish()
car(x, y)
banana(banX, banY)
banana2(banX, banY2)
if # collision test
crash()
To evaluate if to rectangles (x1, y1, w1, h1) and _(x2, y2, w2, h2) are intersecting, you a have to evaluate if the rectangles are overlapping in both dimensions:
collide = x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1
For your code that ma look as follows:
if x < banX + ban_width and banX < x + car_width:
if y < banY + ban_height and banY < y + car_height:
crash()
Anyway I recommend to pygame.Rect and colliderect() for the collision test. Get the rectangles form the pygame.Surface objects carImg and banImg by get_rect(). FOr instance:
car_rect = carImg.get_rect(topleft = (x, y))
ban_rect = banImg.get_rect(topleft = (banX, banY))
ban2_rect = banImg.get_rect(topleft = (banX, banY2))
if car_rect.colliderect(ban_rect) or car_rect.colliderect(ban2_rect):
crash()

Related

Python Snake doesn't grow [duplicate]

This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 1 year ago.
I'm new to python and only now the basics, I'm trying to make a snake game but I can't seem to figure out how to make my snake grow 1 extra square each time it eats an apple. My reasoning is that I keep a list of all the old positions but only show the last one on the screen, and each time the snakes eats another apple it shows 1 extra old positions making the snake 1 square longer.
This is my code:
import pygame
from random import randint
WIDTH = 400
HEIGHT = 300
dis = pygame.display.set_mode((WIDTH,HEIGHT))
white = (255,255,255)
BACKGROUND = white
blue = [0,0,255]
red = [255,0,0]
class Snake:
def __init__(self):
self.image = pygame.image.load("snake.bmp")
self.rect = self.image.get_rect()
self.position = (10,10)
self.direction = [0,0]
self.positionslist = [self.position]
self.length = 1
pygame.display.set_caption('Snake ')
def draw_snake(self,screen):
screen.blit(self.image, self.position)
def update(self):
self.position = (self.position[0] + self.direction[0],self.position[1] + self.direction[1])
self.rect = (self.position[0],self.position[1],5, 5 )
self.positionslist.append(self.position)
if self.position[0]< 0 :
self.position = (WIDTH,self.position[1])
elif self.position[0] > WIDTH:
self.position = (0,self.position[1])
elif self.position[1] > HEIGHT:
self.position = (self.position[0],0)
elif self.position[1] < 0 :
self.position = (self.position[0],HEIGHT)
class Food:
def __init__(self):
self.image = pygame.image.load("appel.png")
self.rect = self.image.get_rect()
apple_width = -self.image.get_width()
apple_height = -self.image.get_height()
self.position = (randint(0,WIDTH+apple_width-50),randint(0,HEIGHT+apple_height-50))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
def draw_appel(self,screen):
screen.blit(self.image, self.position)
def eat_appel (self, snake):
if self.rect.colliderect(snake.rect) == True:
self.position = (randint(0,WIDTH),randint(0,HEIGHT))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
snake.length += 1
def main():
game_over = False
while not game_over:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
snake = Snake()
food = Food()
while True:
screen.fill(BACKGROUND)
font = pygame.font.Font('freesansbold.ttf', 12)
text = font.render(str(snake.length), True, red, white)
textRect = text.get_rect()
textRect.center = (387, 292)
screen.blit(text,textRect)
snake.update()
#snake.update_list()
snake.draw_snake(screen)
food.draw_appel(screen)
food.eat_appel(snake)
pygame.display.flip()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
snake.direction = [0,1]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.direction = [1,0]
if event.key == pygame.K_LEFT:
snake.direction = [-1,0]
if event.key == pygame.K_UP:
snake.direction = [0,-1]
if event.key == pygame.K_DOWN:
snake.direction = [0,1]
if __name__ == "__main__":
main()
This can have multiple reasons. Firstly, I saw you tried to increase the length of the snake by typing snake.length += 1, which may work (probably won't because the module pygame allows the snake to hover around, but not like the loop or conditional statements). One of my tips would be, to increase the length of the snake by using the idea of adding the score with your present snake.length every time (because once your score is 1 by eating an apple, your snake.length would be 2. And it increases with the score). This is my code (a few modifications might be needed):
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 165, 0)
width, height = 600, 400
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Mania")
clock = pygame.time.Clock()
snake_size = 10
snake_speed = 15
message_font = pygame.font.SysFont('ubuntu', 30)
score_font = pygame.font.SysFont('ubuntu', 25)
def print_score(score):
text = score_font.render("Score: " + str(score), True, orange)
game_display.blit(text, [0,0])
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])
def run_game():
game_over = False
game_close = False
x = width / 2
y = height / 2
x_speed = 0
y_speed = 0
snake_pixels = []
snake_length = 1
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
while not game_over:
while game_close:
game_display.fill(black)
game_over_message = message_font.render("Game Over!", True, red)
game_display.blit(game_over_message, [width / 3, height / 3])
print_score(snake_length - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
game_over = True
game_close = False
if event.key == pygame.K_2:
run_game()
if event.type == pygame.QUIT:
game_over = True
game_close = False
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_speed = -snake_size
y_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
if event.key == pygame.K_UP:
x_speed = 0
y_speed = -snake_size
if event.key == pygame.K_DOWN:
x_speed = 0
y_speed = snake_size
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
y += y_speed
game_display.fill(black)
pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])
snake_pixels.append([x, y])
if len(snake_pixels) > snake_length:
del snake_pixels[0]
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
draw_snake(snake_size, snake_pixels)
print_score(snake_length - 1)
pygame.display.update()
if x == target_x and y == target_y:
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
run_game()

If I have two rectangles of different sizes(10 by 10 and 20 by 20) in Pygame, how can I figure out when the two rectangles collide?

I am unable to detect when two rectangles of different sizes collide.
I've tried, "if x == obj_x and y == obj_y:" where x is one rectangle's x-value, obj_x is the other rectangle's x value, and the same for the y-values.
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
display_width = 500
display_height = 500
screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Avoid')
x_change = 0
y_change = 0
FPS = 30
block_size = 10
font = pygame.font.SysFont(None, 25)
smallfont = pygame.font.SysFont("comicsansms",25)
def showLives(lives):
text = smallfont.render("Lives: "+str(lives), True, white)
screen.blit(text, [0,0])
def message_to_screen(msg,color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [100,250])
clock = pygame.time.Clock()
def gameLoop():
gameExit = False
gameOver = False
x = 250
y = 425
x_change = 0
y_change = 0
obj_speed = 5
obj_y = 0
obj_x = 0
obj2_y = 0
obj2_x = 0
obj2_speed = 3
lives = 3
while not gameExit:
while gameOver == True:
screen.fill(white)
message_to_screen("Game Over, Press C to play again or Q to quit", red)
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()
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 = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
x_change = 0
y_change = 0
if x > 500-block_size:
x-=block_size
if x < 0+block_size:
x+=block_size
# if x >= display_width-block_size-block_size or x < 0:
# gameOver = True
obj_y = obj_y + obj_speed
if obj_y > display_height:
obj_x = random.randrange(0, display_width-block_size)
obj_y = -25
obj2_y = obj2_y + obj2_speed
if obj2_y > display_height:
obj2_x = random.randrange(1, display_width-block_size)
obj2_y = -27
x += x_change
y += y_change
screen.fill(black)
pygame.draw.rect(screen,white, [obj_x,obj_y,20,20])
pygame.draw.rect(screen,white, [obj2_x,obj2_y,20,20])
pygame.draw.rect(screen, red, [x,y,block_size,block_size])
showLives(lives)
pygame.display.update()
if x == obj_x and y == obj_y:
lives -= 1
if lives == 0:
gameOver = True
clock.tick(FPS)
pygame.quit()
quit()
gameLoop()
I want the program to detect when any part of the rectangles collide instead of just detecting when one point on each of the rectangles collide.
PyGame has class pygame.Rect() to keep rectangle's position and size. It uses it to draw images/sprites and check collision between sprites.
x = 250
y = 425
obj_y = 0
obj_x = 0
rect_1 = pygame.Rect(x, y, 10, 10)
rect_2 = pygame.Rect(obj_x, obj_y, 20, 20)
and then you can check collision
rect_1.colliderect(rect_2)
You can also use it to draw rectangle on screen
pygame.draw.rect(screen, white, rect_2)
pygame.draw.rect(screen, red, rect_1)
You can also use it to check collision between rectangle and point - ie. to check if button was clicked by mouse
button_rect.collidepoint(event.pos)
To change values in rectangle you have rect_1.x, rect_1.y, rect_1.width, rect_1.height but also
x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h
Some of them takes tuple with (x, y)
for example: center rectangle on screen
rect_1.center = (display_width//2, display_height//2)
or event using screen
rect_1.center = screen.get_rect().center
OR center text on screen
screen_text_rect = screen_text.get_rect()
screen_text_rect.center = screen.get_rect().center
screen.blit(screen_text, screen_text_rect)

Python helicopter game does not update score

as part of my Pygame learning course I have to create simple helicopter game, similar to flappy bird.
It also should have a score count - so everytime you pass gap between blocks with helicopter the score should add 1.
Game logic and everything else works fine, except everytime helicopter pases thru the blocks the score is not added, so all the time score shows 0.
Below is the code, can anyone please help
import pygame
import time
from random import randint
black = (0,0,0)
white = (255,255,255)
pygame.init()
surfaceWidth = 1280
surfaceHeight = 720
imageHeight = 30
imageWidth = 60
surface = pygame.display.set_mode((surfaceWidth,surfaceHeight))
pygame.display.set_caption('EVGENY GAME')
#clock = frames per second
clock = pygame.time.Clock()
img = pygame.image.load('Helicopter.jpg')
def score(count):
font = pygame.font.Font('freesansbold.ttf', 20)
text = font.render("Score: "+str(count), True, white)
surface.blit(text, [0,0])
def blocks(x_block, y_block, block_width, block_height, gap):
pygame.draw.rect(surface, white, [x_block, y_block, block_width, block_height])
pygame.draw.rect(surface, white, [x_block, y_block+block_height+gap, block_width, surfaceHeight])
def replay_or_quit():
for event in pygame.event.get([pygame.KEYDOWN, pygame.KEYUP, pygame.QUIT]):
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
continue
return event.key
return None
def makeTextObjs(text, font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def msgSurface(text):
smallText = pygame.font.Font('freesansbold.ttf', 20)
largeText = pygame.font.Font('freesansbold.ttf', 150)
titleTextSurf, titleTextRect = makeTextObjs(text, largeText)
titleTextRect.center = surfaceWidth / 2, surfaceHeight / 2
surface.blit(titleTextSurf, titleTextRect)
typTextSurf, typTextRect = makeTextObjs('Press any key to continue', smallText)
typTextRect.center = surfaceWidth / 2, ((surfaceHeight / 2) + 100)
surface.blit(typTextSurf, typTextRect)
pygame.display.update()
time.sleep(1)
while replay_or_quit() == None:
clock.tick()
main()
def gameover():
msgSurface('GAME OVER')
def helicopter(x, y, image):
surface.blit(img, (x,y,))
# first constance = game over, while not true we are playing game
def main():
x = 50
y = 100
y_move = 0
x_block = surfaceWidth
y_block = 0
block_width = 100
block_height = randint(0, surfaceHeight/2)
gap = imageHeight * 8
block_move = 3
current_score = 0
game_over = False
while not game_over:#this will keep running until it hits pygame.quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_move = -10
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
y_move = 5
y += y_move
surface.fill(black)
helicopter(x,y,img)
score(current_score)
blocks(x_block, y_block, block_width, block_height, gap)
x_block -= block_move
if y > surfaceHeight-40 or y < 0:
gameover()
if x_block < (-1*block_width):
x_block = surfaceWidth
block_height = randint(0, surfaceHeight/2)
if x + imageWidth > x_block:
if x < x_block + block_width:
if y < block_height:
if x - imageWidth < block_width + x_block:
gameover()
if x + imageWidth > x_block:
if y + imageHeight > block_height+gap:
gameover()
if x < x_block and x > x_block-block_move:
current_score += 1
pygame.display.update()#update, updates specific area on display, flip - updates whole display
clock.tick(100)#100 frames per second
main()
pygame.quit()
quit() enter code here
Your score counter never updates because your score counter condition is never reached. Change
if x < x_block and x > x_block-block_move:
to
if x_block >= x > x_block-block_move:

Pygame: dealing with circular collisions with imported images [duplicate]

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

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