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()
Related
So when the game starts there will be boxes for the user to dodge, but currently, the hitbox of the objects is a bit off.. for example when you move the ship across a box it registers as a hit, ending in a game over.
This is for a Software Design and Development HSC Assessment task
I'm not quite sure what to do to fix this problem
Here's the code!
#This program was created by Tadiwa Mooyo
#more of the car game has been worked on, now there are boxes for the user to "dodge" and it will display the crash message when the boxes are hit
#This program was started on the 22/02/2019
import pygame
import time
import random
pygame.init()
display_width = 1200
display_height = 700
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
car_width = 100
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('The Great Space Escape!')
clock = pygame.time.Clock()
carImg = pygame.image.load('Ships_directory\\Green_black_ship.png')
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Score: "+str(count), True, white)
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(carImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, white)
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():
message_display("You Crashed")
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("A bit Racey", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
clock.tick(15)
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.5)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 4
thing_width = 200
thing_height = 200
dodged = 0
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 = -10
if event.key ==pygame.K_RIGHT:
x_change = 10
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(black)
#things(thingx, thingy, thingw, thingh, color)
things(thing_startx, thing_starty, thing_width, thing_height, white)
thing_starty += thing_speed
car(x,y)
things_dodged(dodged)
if x > display_width - car_width or x < 0:
crash()
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0,display_width)
dodged += 1
thing_speed += 0.5
thing_width += (dodged * 1.4)
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')
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Use pygame.Rect to simplify your code and implement the collision test by .colliderect():
e.g.
things_rect = pygame.Rect(thing_startx, thing_starty, thing_width, thing_height)
car_rect = pygame.Rect(x, y, *carImg.get_size())
if car_rect.colliderect(things_rect):
crash()
If you want to implement your "own" test, which checks if 2 rectangles are intersecting, the you've to check if the rectangles are "overlapping" in both dimensions.
2 ranges [x1, x1+w1] and [x2, x2+w2] are overlapping if x1 < x2+w2 and x2 < x1+w1.
So a intersection test for rectangles can be implmented as follows:
car_w, car_h = carImg.get_size()
if (thing_startx < x+car_w and x < thing_startx+thing_width and
thing_starty < y+car_h and y < thing_starty+thing_height):
crash()
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 keep getting the error "Font not initialized" after running my program. Here's the program. I know I'm initializing pygame. I've tried initializing pygame, pygame.font, and and both of them at the same time. I've done everything. I've tried using pygames default fonts as pygame.font.Font('freesansbold.ttf', 115). That didn't work either.
import pygame
import time
import random
pygame.init
pygame.font.init
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
car_width = 100
car_height = 100
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A Bit Racey')
clock = pygame.time.Clock()
carImg = pygame.image.load ('racecar.png')
gameOver = pygame.image.load ('gameover.png')
def gO (x,y):
gameDisplay.blit(gameOver, (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):
font = pygame.font.SysFont("C:\Windows\Fonts\Arial.ttf", 115)
TextSurf, TextRect = text_objects(text, font)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
time.sleep(2)
game_loop()
def crash ():
message_display('Game Over')
def car(x,y):
gameDisplay.blit(carImg,(x,y))
def game_loop():
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:
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)
#thingx, thingy, thinkw, thingh, color)
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
car (x,y)
if x > display_width - car_width or x < 0:
crash()
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+car_width > thing_startx and + car_width < thing_startx+thing_width:
print('x crossover')
gO (display_width/2 - 145.5, display_height/2-200)
time.sleep(2)
game_loop()
if gameExit == True:
pygame.quit()
quit()
pygame.display.update()
clock.tick(45)
game_loop()
pygame.quit ()
quit ()
You just didn't really run init function in your snippet.
# didn't run function
pygame.init
pygame.font.init
# instead
pygame.init()
pygame.font.init()
Your question is strange. Really strange. It even does not have any problem in it. You are not calling the function pygame.init(). You are evaluating it. You are checking for its existence. Python will raise an exception if the function does not exist BUT it will NOT do anything if it does. To call a function use <function_name>(<parameters>). This. Is. Not. Ruby.
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()
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"]