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()
Related
This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?
(1 answer)
How do I detect collision in pygame?
(5 answers)
Closed 2 years ago.
I want to make it kind of like a life system so that if it collides with the enemy 3 times it will quit
pygame.init()
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
time = pygame.time.Clock()
bg_color1 = (135, 142, 142) # MAIN BG COLOR
bg_color2 = (255, 0, 0) # red
bg_color3 = (255, 255, 0) # yellow
UFO = pygame.image.load('ufo.png')
bg_pic = pygame.image.load('Letsgo.jpg')
clock = pygame.time.Clock()
playerImg = pygame.image.load('enemy.png')
playerX = random.randrange(0, screen_width)
playerY = -50
playerX_change = 0
player_speed = 5
def player(x, y):
window.blit(playerImg, (playerX, playerY))
crashed = False
rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)
menu = True
playerY = playerY + player_speed
if playerY > screen_height:
playerX = random.randrange(0, screen_width)
playerY = -25
def ufo(x, y):
window.blit(UFO, (x, y))
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu = False
window.fill((0, 0, 0))
time.tick(30)
window.blit(bg_pic, (0, 0))
pygame.display.update()
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0
while not crashed:
x += x_change
if x < 0:
x = 0
elif x > screen_width - UFO.get_width():
x = screen_width - UFO.get_width()
y += y_change
if y < 0:
y = 0
elif y > screen_height - UFO.get_height():
y = screen_height - UFO.get_height()
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
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
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
if playerY > screen_height:
playerX = random.randrange(0, screen_width)
playerY = 0
playerY += 10
##
window.fill(bg_color1)
ufo(x, y)
player(playerX, playerY)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
im thinking of using a collide.rect but cant figure it out any help is appreciated
I want the "playerImg" to be the enemy ...................................................................................
Create a variable that stores the number of lives. Create pygme.Rect objects of the player and the UFO with the method get_rect. Set the location of the rectangles by keyword arguments. Use colliderect to test the collision and decrease the number of lives when a collision is detected and create a new random starting position:
lives = 3
while not crashed:
# [...]
player_rect = playerImg.get_rect(topleft = (playerX, playerY))
ufo_rect = UFO.get_rect(topleft = (x, y))
if player_rect.colliderect(ufo_rect):
lives -= 1
print(lives)
playerX = random.randrange(0, screen_width)
playerY = 0
if lives == 0:
crashed = True
# [...]
This question already has answers here:
Not letting the character move out of the window
(2 answers)
I made a border in this pong game, but the paddles can cross it. How do I stop that?
(2 answers)
Closed 2 years ago.
I have tried many sites but still cannot come up with anything. All online tutorials are not helpful. I have just started learning python and every time I try to move it goes out of the border. I have tried basically all online guide and came across an error...........................
pygame.init()
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
bg_color1 = (135,142,142) #MAIN BG COLOR
bg_color2 = (255,0,0) #red
bg_color3 = (255,255,0) #yellow
clock = pygame.time.Clock()
crashed = False
UFO = pygame.image.load('ufo.png')
rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)
def car(x, y):
window.blit(UFO, (x, y))
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
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
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
##
x += x_change
y += y_change
##
window.fill(bg_color1)
car(x, y)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
Check that the coordinate is less than 0 or greater than the width or height of the screen. Limit the coordinate if it is out of bounds:
while not crashed:
# [...]
x += x_change
if x < 0:
x = 0
elif x > screen_width - UFO.get_width():
x = screen_width - UFO.get_width()
y += y_change
if y < 0:
y = 0
elif y > screen_height - UFO.get_height():
y = screen_height - UFO.get_height()
You can simplify the code using the min and max functions:
while not crashed:
# [...]
x = max(0, min(screen_width - UFO.get_width(), x + x_change))
y = max(0, min(screen_height - UFO.get_height(), y + y_change))
Another option is to use pygame.Rect objects and clamp_ip. See clamp_ip:
moves the rectangle inside another, in place
while not crashed:
# [...]
x += x_change
y += y_change
border_rect = window.get_rect()
ufo_rect = UFO.get_rect(topleft = (x, y))
ufo_rect.clamp_ip(border_rect)
x, y = ufo_rect.topleft
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()
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()
I'm new to Pygame, and still learning Python. I'm using Python 3.4.
I followed this amazing game creation tutorial: http://pythonprogramming.net/pygame-python-3-part-1-intro/. After completing the lessons I decided to change the game slightly, and have succeeded in adding some more movement and fixed some bugs. However now I'm trying to figure out how to change the sprite when I press an arrow key, as to make it appear like it is tilting.
I have a file called racecar.png (which is the plane) and move_right.png (which looks like it is tilted). My end goal is to have it when I press the right arrow, move_right.png is displayed until I release the key, in which case it returns to racecar.png. I have looked up how to use sprite sheets, which failed, how to animate, watched YouTube, Googled my problem but I can't find anyone else who has this problem. Most of what I found talked about moving the sprite around the screen.
Here is the code:
import pygame
import random
import time
pygame.init()
car_width = 100
car_height = 100
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A Macross Simumater')
black = (0,0,0)
white = (255, 255, 255)
red = (255, 0,0)
green = (0,255,0)
greent = (0, 150, 0)
blue = (0,0, 200)
dark_blue = (0, 0, 50)
clock = pygame.time.Clock()
carImp = pygame.image.load('racecar.png')
gameIcon = pygame.image.load('caricon.png')
#background = pygame.image.load('background.png')
pygame.display.set_icon(gameIcon)
def quitgame():
pygame.quit()
quit()
def unpause():
global pause
pause = False
def paused():
largeText = pygame.font.SysFont("comicsansms",115)
TextSurf, TextRect = text_objects("Paused", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Continue",150,450,100,50,green,black,unpause)
button("Quit",550,450,100,50,red,black,quitgame)
pygame.display.update()
clock.tick(15)
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, black)
gameDisplay.blit(text, (0,0))
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def car(x, y):
gameDisplay.blit(carImp, (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', 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 crash():
largeText = pygame.font.SysFont("comicsansms",115, (0, 0, 0))
TextSurf, TextRect = text_objects("You Crashed", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play Again",150,450,100,50,green,black,game_loop)
button("Quit",550,450,100,50,red,black,quitgame)
pygame.display.update()
clock.tick(15)
def button(msg,x,y,w,h,ic,ac, action = None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac,(x, y, w, h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay, ic, (x, y, w, h))
smallText = pygame.font.Font('freesansbold.ttf', 21)
textSurf, textRect = text_objects("GO!", smallText)
textRect.center = ((150+(100/2)), (450+(50/2)))
gameDisplay.blit(textSurf, textRect)
textSurf, textRect = text_objects("QUIT!", smallText)
textRect.center = ((550+(100/2)), (450+(50/2)))
gameDisplay.blit(textSurf, textRect)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects('Macross',largeText)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
mouse = pygame.mouse.get_pos()
button("GO!", 150, 450, 100, 50, green, black, game_loop)
button("Quit", 550,450,100,50, red, black, quitgame)
pygame.display.update()
clock.tick(15)
def game_loop():
global pause
pygame.mixer.music.load('Macross Plus - Voices HQ MV Karaoke Instrumental Japanese.mp3')
pygame.mixer.music.play(-1)
x = (display_width * 0.45)
y = (display_height * 0.8)
global x_change
global y_change
x_change = 0
y_change = 0
pause = False
dodged = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 4
thing_width = 50
thing_height = 50
thingt_startx = random.randrange(0, display_width)
thingt_starty = -600
thingt_speed = 7
thingt_width = 100
thingt_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_RIGHT:
x_change = 8
elif event.key == pygame.K_LEFT:
x_change = -8
elif event.key == pygame.K_p:
pause = True
paused()
elif event.key == pygame.K_UP:
y_change = -8
elif event.key == pygame.K_DOWN:
y_change = 8
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
x_change = 0
y_change = 0
x += x_change
y += y_change
gameDisplay.fill(dark_blue)
things(thing_startx, thing_starty, thing_width, thing_height, greent)
thing_starty += thing_speed
things(thingt_startx, thingt_starty, thingt_width, thingt_height, greent)
thingt_starty += thingt_speed
car(x, y)
if x > display_width - car_width or x < 0:
crash()
if y > display_width - car_width or y < 0:
y_change = 0
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0, display_width)
dodged += 1
thing_speed += 1
thing_width += (dodged * 1.2)
thing_height += (dodged * 2)
thingt_starty = 0 - thing_height
thingt_startx = random.randrange(0, display_width)
dodged += 1
thingt_speed += 1
thingt_width += (dodged * 1.2)
thingt_height += (dodged * 2)
if thing_starty < y:
if y < thing_starty+thing_height:
if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx + thing_width:
crash()
elif thing_starty > y:
print('passed')
if thingt_starty < y:
if y < thingt_starty+thingt_height:
if x > thingt_startx and x < thingt_startx + thingt_width or x + car_width > thingt_startx and x + car_width < thingt_startx + thingt_width:
crash()
elif thingt_starty > y:
print('PASSED')
things_dodged(dodged)
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
At each frame, you display the image in the global variable called carImp in this function:
def car(x, y):
gameDisplay.blit(carImp, (x, y))
SO, what you have to do is to change the contents of this variable to point to the desired image before the display.
You should first read all the images for your car – you can read them all into a dictionary to avoid polluting your namespace (even more than it is polluted) with a variable name for each sprite:
So, in the beginning, some code like:
car_image_names = ["racecar", "move_right", "move_left"]
car_sprites = dict(((img_name, pygame.image.load(img_name + ".png"))
for img_name in car_image_names)
carImp = car_sprites["racecar"]
(Here I've used a shortcut called "generator expression" to avoid having to write a "pygame.image.load" for each car image.)
And then, in your main loop, after you've read the keyboard, and detected
whether the car is moving right or left (which you reflect in x_change) – just change carImp accordingly:
if x_change == 0:
carImp = car_sprites["racecar"]
elif x_change > 0:
carImp = car_sprites["move_right"]
elif x_change < 0:
carImp = car_sprites["move_left"]