How do you make images in pygame and make them move? - python

I have been working on a game for a school project and I have these blocks come down the screen and you need to dodge them. I need to turn the blank drawn rectangles coming down the screen into a picture of a car I have.
This is my code so far:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
#^^NEED TO CHANGE TO AN IMAGE CALLED TAXI.PNG CAN SOMEONE PLEASE FIX FOR ME
def man(x,y):
gameDisplay.blit(manImg,(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():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
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, ic,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def game_intro():
pygame.mixer.music.play(-1)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
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 = -5
if 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)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
objects(object_startx, object_starty, object_width, object_height, cyan)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
if x > display_width - man_width or x < 0:
crash()
if object_starty > display_height:
object_starty = 0 - object_height
object_startx = random.randrange(0, display_width)
dodged += 1
object_speed += 0.7
object_width += (dodged * 1)
if y < object_starty+object_height:
print('y crossover')
if x > object_startx and x < object_startx + object_width or x+man_width > object_startx and x + man_width < object_startx+object_width:
print('x crossover')
crash()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
If someone could fix it so it displays taxi.png instead of the rectangles as objects it would be greatly appreciated.

To draw the picture of the car instead of a rectangle, just do the same thing that you are doing with the man.
Under the line that is manImg = pygame.image.load('skater1.png'), put this line: carImg= pygame.image.load('taxi.png') This will load the picture of the car and it will be called carImg.
Now, you need to draw that picture onto the screen. Replace your objects function:
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
with a function to draw a car.
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
Notice how it is very similar to the man function, the only difference is the image that is drawn.
The last thing you need to do is actually call that drawCar function. Replace this line
objects(object_startx, object_starty, object_width, object_height, cyan)
with this one: drawCar(object_startx,object_starty)
I would recommend doing these changes yourself, it will help you learn. But if you're in a hurry, the final code, with all of these changes made, should be:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
carImg= pygame.image.load('taxi.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
def man(x,y):
gameDisplay.blit(manImg,(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():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
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, ic,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def game_intro():
pygame.mixer.music.play(-1)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
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 = -5
if 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)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
drawCar(object_startx,object_starty)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
When you follow tutorials online, don't just copy and paste the code. Make sure that you understand what is happening so that in the future, you can do it yourself.

Related

How do I change the hitbox of one of my sprites?

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

PyGame Y Axis Collision Detection

Quite some time ago I created this very basic game using pygame. The aim of the game is to dodge the rectangles falling at you. First I wanted to add the ability to go up and down and not only strafe side to side. So I added the button presses, y changes, etc.. This all works great but there is one problem. If I go above an obstacle that is below me it still counts as a collision (or crash as I have named it in my code) even though I was no where near it. I believe that the problem is inside the game_loop function as that is where the collision logic happens.
Here is the code (No error codes appear):
import pygame
import time
import random
import base64
import io
import webbrowser
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
cyan = (0, 80, 200)
green = (0, 200, 0)
grey = (200, 200, 200)
pepe_width = 70
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('The Best Game')
clock = pygame.time.Clock()
photo = 'R0lGODlhRgBGAPZUAAAAAAAAMwAAzAArAAArMwArzAAr/wBVmQBVzABV/zMAADMAMzMrADMrMzMrmTMrzDMr/zNVADNVMzNVZjNVmTNVzDNV/zOAADOAMzOAZjOA/zOqM2YAM2YrAGYrM2ZVAGZVM2ZVZmZVmWZVzGZV/2aAAGaAM2aAZmaAmWaAzGaA/2aqAGaqM2aqZmaqmWaqzJkrAJkrM5lVAJlVM5lVZplVmZmAAJmAM5mAZpmAmZmAzJmqZpmqmZmqzJmq/5nVmZnVzMxVAMxVM8xVZsyAAMyAM8yAZsyqZsyqmcyqzMyq/8zVmczVzMzV/8z/zMz////VzP/V////zP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAUAAFQALAAAAABGAEYAAAf/gFOCg4SFhoeIiYZMOScoKI45SUxJk4qXmJmJSSghKCI4OSInOT1JTT05TJqsrYhMPCETnpCQIjyVSbiuvK1NjJ2jIiE5KI0ouJQ8PVC9zohPusWOndU4o5+4SaWrz96CULAhnsU4n9Tlnqc9SElP389NP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yJtwHcDCiMot+otInEKL9xZhAUKgFoEQDSmFngaXwDaH9Xsxz9/MY+nPvVFnZInjoaQgg8egNoGQxQCPrAY/3hgRiRbFuyW12wSf+jCA3t+xQdsBW8C7JuAFLS0tJHDJXIYGDKo2tJF4nHlIJ7QhBGEeMT3fbAOgPCVHlQgBLUEVRiHXGH0aKqj5OGBdvkyAhITN8dNVQJfdACBCVjxoIMiF6D4palP8jNAv5TAE7vpY+Iy9b70hWgFKmjaBBRAohsmWEGpmbC6DOwvdMMABVLQg5MloQIh/i5iC5BfQlRguDGtwEzVi9BGA8qHnuolqGgqAftaYM1SKK2b6wtlNFfgxIdWLQIOoKS5HmeujU71eltnAAO82QcheeiTU0tf1Yb3BVGsgACIS+gCHMDKOtPQeDTEXLxM4AAIqHWrE/tw6bY2WLXgRYAFqDWFlwpa1CN+8wEcgAAKdLvbB6AABcId7nFz+wCHJrGD171pKMfUACnwShTm22kRfzfN9M23fYfrZBH729nuRuyZE/CA8XZT1s++9rvX/V12uzvN9m6wst1sgWR5t60QhXi/ax3xWWdcxBB3MIn7jdgH5JebU+jBxd+N2GUPt+VpbjnLF+7yZbe65iyX+c1H0APgCkLlBrAAs5ktbWYHXdpBN7oFin5aoTcdARAYutCnHtEERJ3qQo960xPA81MdwgcqsEDYVaABEpD97CnQgArITgK1l33sYy+72+NudrGfXe1inzveVVABFSQBYIgIBAA7'
output = io.BytesIO(base64.b64decode(photo))
pepeImg = pygame.image.load(output)
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, black)
gameDisplay.blit(text, (10, 10))
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def pepe(x, y):
gameDisplay.blit(pepeImg, (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', 70)
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('lel pal u ded')
def button(msg, x, y, w, h, a, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(gameDisplay, a, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
else:
pygame.draw.rect(gameDisplay, a, (350, 450, 100, 50))
smallText = pygame.font.Font("freesansbold.ttf", 20)
textSurf, TextRect = text_objects(msg, smallText)
TextRect.center = ((x + (w / 2)), y + (h / 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(cyan)
LargeText = pygame.font.Font('freesansbold.ttf', 70)
TextSurf, TextRect = text_objects("The Best Game", LargeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
button("Play", 350, 450, 100, 50, green, "play")
pygame.display.update()
clock.tick(15)
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
y_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 3.5
thing_width = 100
thing_height = 100
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 = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
elif 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_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(grey)
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
pepe(x, y)
things_dodged(dodged)
if x > display_width - pepe_width or x < 0:
crash()
if y > display_height - pepe_width or y < 0:
ctash()
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0, display_width)
dodged += 1
thing_speed += 0.1
if y < thing_starty + thing_height:
if x > thing_startx and x < thing_startx + thing_width or x + pepe_width > thing_startx and x + pepe_width < thing_startx + thing_width:
#webbrowser.open('https://youtu.be/dQw4w9WgXcQ')
crash()
pygame.display.update()
clock.tick(120)
game_intro()
game_loop()
pygame.quit()
quit()
EDIT: This is the final working code:
import pygame
import time
import random
import base64
import io
import webbrowser
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
cyan = (0, 80, 200)
green = (0, 200, 0)
grey = (200, 200, 200)
pepe_width = 70
pepe_height = 70
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('The Best Game')
clock = pygame.time.Clock()
photo = 'R0lGODlhRgBGAPZUAAAAAAAAMwAAzAArAAArMwArzAAr/wBVmQBVzABV/zMAADMAMzMrADMrMzMrmTMrzDMr/zNVADNVMzNVZjNVmTNVzDNV/zOAADOAMzOAZjOA/zOqM2YAM2YrAGYrM2ZVAGZVM2ZVZmZVmWZVzGZV/2aAAGaAM2aAZmaAmWaAzGaA/2aqAGaqM2aqZmaqmWaqzJkrAJkrM5lVAJlVM5lVZplVmZmAAJmAM5mAZpmAmZmAzJmqZpmqmZmqzJmq/5nVmZnVzMxVAMxVM8xVZsyAAMyAM8yAZsyqZsyqmcyqzMyq/8zVmczVzMzV/8z/zMz////VzP/V////zP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAUAAFQALAAAAABGAEYAAAf/gFOCg4SFhoeI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f1rWcv61dDdBaih8wBDD9GEFFQgpglIbVutKDMnmO+WJyRPibBKnxLZdqS07aySOBM6oe4grYN4aQEQi9oCUMAF20vCbNIEskuWiKQi9WtJgcokQ1lzB0yQXyGcoAMLEBe1BqhAD/jyAyJtwHcDCiMot+otInEKL9xZhAUKgFoEQDSmFngaXwDaH9Xsxz9/MY+nPvVFnZInjoaQgg8egNoGQxQCPrAY/3hgRiRbFuyW12wSf+jCA3t+xQdsBW8C7JuAFLS0tJHDJXIYGDKo2tJF4nHlIJ7QhBGEeMT3fbAOgPCVHlQgBLUEVRiHXGH0aKqj5OGBdvkyAhITN8dNVQJfdACBCVjxoIMiF6D4palP8jNAv5TAE7vpY+Iy9b70hWgFKmjaBBRAohsmWEGpmbC6DOwvdMMABVLQg5MloQIh/i5iC5BfQlRguDGtwEzVi9BGA8qHnuolqGgqAftaYM1SKK2b6wtlNFfgxIdWLQIOoKS5HmeujU71eltnAAO82QcheeiTU0tf1Yb3BVGsgACIS+gCHMDKOtPQeDTEXLxM4AAIqHWrE/tw6bY2WLXgRYAFqDWFlwpa1CN+8wEcgAAKdLvbB6AABcId7nFz+wCHJrGD171pKMfUACnwShTm22kRfzfN9M23fYfrZBH729nuRuyZE/CA8XZT1s++9rvX/V12uzvN9m6wst1sgWR5t60QhXi/ax3xWWdcxBB3MIn7jdgH5JebU+jBxd+N2GUPt+VpbjnLF+7yZbe65iyX+c1H0APgCkLlBrAAs5ktbWYHXdpBN7oFin5aoTcdARAYutCnHtEERJ3qQo960xPA81MdwgcqsEDYVaABEpD97CnQgArITgK1l33sYy+72+NudrGfXe1inzveVVABFSQBYIgIBAA7'
output = io.BytesIO(base64.b64decode(photo))
pepeImg = pygame.image.load(output)
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, black)
gameDisplay.blit(text, (10, 10))
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def pepe(x, y):
gameDisplay.blit(pepeImg, (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', 70)
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('lel pal u ded')
def button(msg, x, y, w, h, a, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(gameDisplay, a, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
else:
pygame.draw.rect(gameDisplay, a, (350, 450, 100, 50))
smallText = pygame.font.Font("freesansbold.ttf", 20)
textSurf, TextRect = text_objects(msg, smallText)
TextRect.center = ((x + (w / 2)), y + (h / 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(cyan)
LargeText = pygame.font.Font('freesansbold.ttf', 70)
TextSurf, TextRect = text_objects("The Best Game", LargeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
button("Play", 350, 450, 100, 50, green, "play")
pygame.display.update()
clock.tick(15)
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
y_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 3.5
thing_width = 100
thing_height = 100
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 = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
elif 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_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(grey)
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
pepe(x, y)
things_dodged(dodged)
if x > display_width - pepe_width or x < 0:
crash()
if y > display_height - pepe_width or y < 0:
crash()
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0, display_width)
dodged += 1
thing_speed += 0.1
if (x < thing_startx + thing_width and x + pepe_width > thing_startx and
y < thing_starty + thing_height and y + pepe_height > thing_starty):
crash()
webbrowser.open('https://youtu.be/dQw4w9WgXcQ')
pygame.display.update()
clock.tick(120)
game_intro()
game_loop()
pygame.quit()
quit()
Your collision detection is broken. This should work:
if (x < thing_startx + thing_width and x + pepe_width > thing_startx and
y < thing_starty + thing_height and y + pepe_height > thing_starty):
I highly recommend creating pygame.Rects for your objects, because they have reliable and fast collision detection methods.
player = pygame.Rect(100, 200, 70, 70)
enemy = pygame.Rect(150, 200, 100, 100)
# In the main loop.
if player.colliderect(enemy):
# do something.

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

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

Fatal Error when converting game in pygame to exe

This is the code I am using to create the build file:
import cx_Freeze
executables = [cx_Freeze.Executable("SpeedRacer.py")]
cx_Freeze.setup(
name="SpeedRacer",
options={"build_exe": {"packages": ["pygame"],"include_files": ["SpeedRacerDefaultCar.png"]}},
executables = executables
)
This is the error I get when launching .exe file for game:
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: cHRM chunk does not match sRGB
Fatal Python error: (pygame parachute) Segmentation Fault
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\pygame\pkgdata.py". line 67. in getResourc
e
return open(os.path.normpath(path), 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Jordan\\Desk
top\\Python Projects\\Game Ideas\\SpeedRacerGame\\build\\exe.win-amd64-3.4\\libr
ary.zip\\pygame\\freesansbold.ttf'
Game Code is as follows:
import pygame
import time
import random
pygame.init()
display_width = 1440
display_height = 900
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (50,126,31)
blue = (34,101,183)
bright_green = (72,185,45)
bright_red = (255,0,0)
block_color = green
car_width = 75 # Image width in Pixels.
gameDisplay = pygame.display.set_mode((1440, 900))
pygame.display.set_caption('SpeedRacer')
clock = pygame.time.Clock()
carImg = pygame.image.load('SpeedRacerDefaultCar.png')
def quitgame():
pygame.quit()
quit()
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, bright_red)
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, blue)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.SysFont(None,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 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.SysFont(None,20)
textSurf, textRect = text_objects(msg, smallText,)
textRect.center = ( (x+(w/2)), (y+(h/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(black)
largeText = pygame.font.SysFont(None,115)
TextSurf, TextRect = text_objects("SpeedRacer", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",550,575,100,50,green,bright_green,game_loop)
button("Quit",750,575,100,50,red,bright_red,quitgame)
pygame.display.update()
clock.tick(15)
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 = 4
thing_width = 100
thing_height = 100
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
elif 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, block_color)
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.4
thing_width += (Dodged * 0.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(120)
game_intro()
game_loop()
pygame.quit()
quit()
I converted to .exe using cx_Freeze.
Hi please try to see the following web pages, which explains how to resolve the problem, actually I had the same problem and I made the things that they suggested and now is working:
First I made:
Original line code
font = pygame.font.SysFont(None, 48)
Change line code by this
font = pygame.font.SysFont("Arial", 48)
Using pygame2exe and having font issue with sysfont/.ttf
Pygame not using specified font

how to change a sprite on the screen after pressing a key in pygame

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"]

Categories

Resources