I am writing a little game with Pygame
for the first time. I was previously playing around with Python Turtle
, but they appear to be quite different when it gets to making objects to bounce. I have a squirrel running horizontally (only) at the bottom of the screen at a certain height
(h). I placed another object (cat
) at the same height to also run only horizontally. How do I make squirrel to bounce off in random xy
direction when collided with cat?
My squirrel is running only to the right but I need it to turn 180 degrees and run to the left. Same for the cat.
I assume that I somehow have to "check the borders"
like in Turtle
my attempts to do so failed.
(I removed some of the objects and things like score, health etc to keep it cleaner for you to look at)
Here is my game:
import math
import random
import pygame
import pygame, sys
import time
pygame.init()
#************************************ CONSTANT******************
## set up the screen
w = 1000
h = 600
screen = pygame.display.set_mode((w,h))
pygame.display.set_caption("Marchello" + "'" + "s" + " Kitchen")
bg = pygame.image.load("kitchen.png")
RED = (255, 0, 0)
## set Clock
clock = pygame.time.Clock()
#***************************************GAME**************************
## create Cat character
catImg = pygame.image.load('cat.png')
def cat(xa, ya):
screen.blit(catImg,(xa, ya))
## create Squirrel character
sqrlImg = pygame.image.load('crazySquirrel1.gif')
def sqrls(xb, yb):
screen.blit(sqrlImg,(xb, yb))
## main game loop event
def game():
xa = (w * 0.45) ## xy of a cat
ya = (h * 0.82)
sqrls_startx = 200 #squirrel's starting point
sqrls_starty = 505
sqrls_speed = 5 # squirrel's speed
x_change = 0
endGame = False
while not endGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(bg, (0, 0))
cat(xa,ya)
## move squirrel
sqrls_startx +=sqrls_speed
sqrls(sqrls_startx, sqrls_starty)
if sqrls_startx > w:
sqrls_startx = random.randrange(0, w)
## squirrel collision with cat
if sqrls_startx == xa:
## 'x crossover' where the squirrel has to bounce off
pygame.display.update()
clock.tick(60)
game()
pygame.quit()
quit()
Thank you for your suggestions!