in the game when you first start it there's the game start menu/intro, it has 2 buttons (Start Game) (Quit)
Now when you start the game and you're actually playing, when you press P (Paused) there're 2 buttons (Continue) (Main Menu) if you click continue it completes the game normally. However when you click main menu it closes the game instead of returning to the intro, same problem is present when you crash with the car you have (Try Again) and (Main Menu) and also if you click Main Menu it closes the game
Any ideas on what might be the problem ?(ignore the comments)
import pygame
import time
import random
pygame.init()
crash_sound = pygame.mixer.Sound("C:\Users\itzrb_000\Documents\Untitled.wav")
pygame.mixer.music.load("C:\Users\itzrb_000\Downloads\Cool_Ride.mp3")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
blue = (0,0,255)
bright_green = (0,255,0)
bright_red = (255,0,0)
car_width = 50
gameDisplay = pygame.display.set_mode((display_width,display_height))#game screen size
pygame.display.set_caption('What A Ride')
clock = pygame.time.Clock()
carImg = pygame.image.load('C:\Users\itzrb_000\Downloads\Car_Green_Front.png')
gameBackground = pygame.image.load('C:\WhatARide_Background.png')
icon = pygame.image.load('C:\Users\itzrb_000\Downloads\Car_Green_Front - Copy.png')
pygame.display.set_icon(icon)
pause = False
car1 = pygame.image.load('C:\Users\itzrb_000\Downloads\download (3).png')
car2 = pygame.image.load('C:\Users\itzrb_000\Downloads\download (2).png')
car3 = pygame.image.load('C:\Users\itzrb_000\Downloads\images.png')
rock = pygame.image.load('C:\Users\itzrb_000\Downloads\Rock.png')
def background():
gameDisplay.blit(gameBackground,(0,0))
'''def cars(ystart):
objects = [car1, car2, car3, rock]
num_of_objects = random.randint(1,4)
for x in range(num_of_objects):
y = random.choice(objects)
objectblit = random.randrange(130, 625) - (y.get_width())
gameDisplay.blit(y,(random.randrange(130, 625)))'''
def score(count):
font = pygame.font.SysFont(None,25)
text = font.render("Score: "+str(count),True, blue)
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*0.5),(display_height*0.5))
gameDisplay.blit(TextSurf, TextRect)#blit display object
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
pygame.mixer.music.stop()
pygame.mixer.Sound.play(crash_sound)
largeText = pygame.font.Font("freesansbold.ttf", 115)
TextSurf, TextRect = text_objects("You Crashed", largeText)
TextRect.center = ((display_width * 0.5), (display_height * 0.5))
gameDisplay.blit(TextSurf, TextRect) # blit display object
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Try Again!", 300, 400, 200, 50, green, bright_green, game_loop)
button("Main Menu!", 300, 470, 200, 50, red, bright_red, game_intro)
pygame.display.update()
clock.tick(20)
def button(msg,x,y,w,h,ic,ac,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, 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("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def quitgame():
pygame.quit()
quit()
def unpause():
global pause
pause = False
pygame.mixer.music.unpause()
def paused():
global pause
pause = True
pygame.mixer.music.pause()
largeText = pygame.font.Font("freesansbold.ttf", 115)
TextSurf, TextRect = text_objects("Paused", largeText)
TextRect.center = ((display_width * 0.5), (display_height * 0.5))
gameDisplay.blit(TextSurf, TextRect) # blit display object
while pause == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Continue!", 300, 400, 200, 50, green, bright_green,unpause)
button("Main Menu", 300, 470, 200, 50, red, bright_red,game_intro)
pygame.display.update()
clock.tick(20)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(blue)
largeText = pygame.font.SysFont("comicsansms", 115)
TextSurf, TextRect = text_objects("What A Ride", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
button("Start Game", 300, 400, 200, 50, green, bright_green,game_loop)
button("Quit", 300, 470, 200, 50, red, bright_red,quitgame)
pygame.display.update()
clock.tick(20)
def game_loop():
global pause
pygame.mixer.music.play(-1)
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_startx = random.randrange(130,625)
thing_starty = -600
thing_speed = 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
if event.key == pygame.K_p:
pause = True
paused()
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
background()
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
car(x,y)
score(dodged)
if x > 625 - car_width or x < 130:
crash()
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(130,625)
dodged += 1
thing_speed += 1
thing_width += (dodged*1.2)
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()
pygame.display.update()
clock.tick(51) #fps
game_intro()
game_loop()
pygame.quit()
quit()
Because you're not waiting for the mouse button to be released before you trigger your buttons.
When pause() starts, it brings up two buttons.
User moves mouse to Main Menu.
User clicks mouse.
As soon as the mouse button is depressed, game_intro() is called, which puts a Quit button in the same place.
The mouse button is still depressed, so the game quits.
Related
So I am a couple steps away from creating my first game but the syntax error incoming up for no reason and if there are any more errors instead of that please tell me!
I have tried everything but I can't make it work
I have read everything on this website and can't find anything that makes it work maybe its a more complex mistake I suppose so please help me I am struggling really badly
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
block_color = (53,115,255)
carImg_width = 73
carImg_height = 62
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
carImg = Actor("car.png")
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):
pygame.Surface(Actor), (int width , int height)
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():
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()
#if action =="play":
#game_loop()
#elif action == "quit":
#pygame.quit()
#quit()
else:
pygame.draw.rect(gameDisplay, ic, (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():
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("A bit Racey", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Go!",150,450,100,50,green,bright_green,game_loop)
button("Quit",550,450,100,50,red,bright_red,"Quit")
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
thingCount = 1
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)
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 += 1
thing_width += (dodged * 1.2)
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_intro()
game_loop()
pygame.quit()
quit()
There were 4 errors,
You used car_width instead of carImg_width in many places.
Your car() function was wrong
carImg = Actor("car.png") - Where is this function defined?
you forgot to use blit() to display your car image
A working version of your game
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
block_color = (53,115,255)
carImg_width = 73
carImg_height = 62
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
carImg = "car.png"
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():
#return pygame.Surface((int(carImg_width) ,int(carImg_height)),0, carImg )
return pygame.transform.scale(pygame.image.load(carImg).convert(), (carImg_width, carImg_height))
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():
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()
#if action =="play":
#game_loop()
#elif action == "quit":
#pygame.quit()
#quit()
else:
pygame.draw.rect(gameDisplay, ic, (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():
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("A bit Racey", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Go!",150,450,100,50,green,bright_green,game_loop)
button("Quit",550,450,100,50,red,bright_red,"Quit")
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
thingCount = 1
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)
things(thing_startx, thing_starty, thing_width, thing_height, block_color)
thing_starty += thing_speed
gameDisplay.blit(car(), ( x,y))
#car(x,y)
things_dodged(dodged)
if x > display_width - carImg_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 += 1
thing_width += (dodged * 1.2)
if y < thing_starty+thing_height:
print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x+carImg_width > thing_startx and x + carImg_width < thing_startx+thing_width:
print('x crossover')
crash()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
You car game screenshot:
I am just programming a small game with python and the pygame library.
The game's idea is to have a small charakter running around the floor avoiding to crash into a falling rectunglar.
It all works out from the game logic side.
But I still have problem when the game starts:
As I invert the player horizontally, depending on which direction it is heading to, I had to assign 2 images depending on the key pressed. Now, everytime I start the game and no key is pressed yet, there is only a "hidden/transparent" pygame.Surface()-object, because I needed it as a placeholder to assign the 2 images conditionally once a key(left or right) is pressed. Hence, the game starts and when not key is pressed no player shows up...
My question: How can I add a default (3rd) image before any key is actually pressed and not having the transparent Surface object hiding. I tried many things with the Surface.blit() or gameDisplay.blit() and thus loading another image, but it never showed up so far :(...
I guess it is a dumb thing to solve but I cannot figure it out on my own (+ google)..
Thanks in advance
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 = (200, 0,0 )
green = (0, 200, 0)
blue = (0,0, 255)
bright_red = (255, 0,0 )
bright_green = (0, 255, 0)
player_width = 100
player_height = 238
pause = False
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Gesi Run of her Life <3')
clock = pygame.time.Clock()
gesImg_left = pygame.image.load('yourimage.png')
gesImg_right = pygame.transform.flip(gesImg_left, True, False)
background = pygame.image.load('yourbackground.jpg')
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def ges(player_img, x,y):
gameDisplay.blit(player_img, (x,y))
def text_objects(text, font, col):
textSurface = font.render(text, True, col)
return textSurface, textSurface.get_rect()
def message_display(text, col):
largeText = pygame.font.Font('freesansbold.ttf', 50)
TextSurf, TextRect = text_objects(text, largeText, col)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
#gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf', 60)
TextSurf, TextRect = text_objects("A star was born!", largeText, black)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Nochmal", 150, 450, 100, 50, green, bright_green, "play")
button("quit", 550, 450, 100, 50, red, bright_red, "quit")
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()
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:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
elif action == "unpause":
global pause
pygame.mixer.music.unpause()
pause = False
else:
pygame.draw.rect(gameDisplay, ic, (x, y, w, h))
smallText = pygame.font.Font('freesansbold.ttf', 20)
TextSurf, TextRect = text_objects(msg, smallText, black)
TextRect.center = ((x+(w/2)),(y +(h/2)))
gameDisplay.blit(TextSurf, TextRect)
def paused():
pygame.mixer.music.pause()
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
#gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf', 60)
TextSurf, TextRect = text_objects("Paused", largeText, black)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Continue", 150, 450, 100, 50, green, bright_green, "unpause")
button("quit", 550, 450, 100, 50, red, bright_red, "quit")
pygame.display.update()
clock.tick(15)
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', 60)
TextSurf, TextRect = text_objects("Gesi Super F/Run Game", largeText, black)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("let's go", 150, 450, 100, 50, green, bright_green, "play")
button("quit", 550, 450, 100, 50, red, bright_red, "quit")
pygame.display.update()
clock.tick(15)
def game_loop():
global pause
x = (display_width * 0.45)
y = (display_height * 0.6)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 4
thing_width = 100
thing_height = 100
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
color = (r, g, b)
#player = pygame.Surface((x*0,y*0))
player = pygame.Surface((x,y), pygame.SRCALPHA, 32)
#player = pygame.Surface([x,y], pygame.SRCALPHA, 32)
player = player.convert_alpha()
#pygame.display.update()
gameExit = False
# game loop: the logic that happens if you not quit OR crash
while not gameExit:
for event in pygame.event.get(): # list of events per frame per secend (clicking etc.)
# ask if user asks to quit
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if bonus > 0:
x_change = -5*bonus
else:
x_change = -5
player = gesImg_left
if event.key == pygame.K_RIGHT:
if bonus > 0:
x_change = 5*bonus
else:
x_change = 5
player = gesImg_right
if event.key == pygame.K_p:
pause = True
paused()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
elif event.key == pygame.K_RIGHT:
x_change = 0
player = gesImg_right
#print(event) # see all the interaction on the screen printed out on the terminal console
x = x + x_change
player_img = player
gameDisplay.blit(background,(0,0))
if dodged == 10 or dodged == 20 or dodged == 30:
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
color = (r, g, b)
things(thing_startx, thing_starty, thing_width, thing_height, color)
thing_starty = thing_starty + thing_speed + random.randrange(-1,1)
ges(player_img, x,y)
things_dodged(dodged)
if x > display_width-player_width or x < 0:
crash()
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0, display_width)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
color = (r, g, b)
dodged = dodged + 1
# managing the speed
if dodged >= 17:
thing_speed += random.uniform(-0.8,0.2)
if dodged >= 27:
thing_speed += random.uniform(0.8,1)
if dodged >= 40:
thing_speed += random.uniform(0.4,1.5)
else:
thing_speed += random.uniform(-0.4,0.9)
# managing the width
if dodged >= 19:
thing_width += (dodged * random.uniform(-0.7,0))
if dodged >= 35:
thing_width += (dodged * random.uniform(0,1.1))
if dodged >= 45:
thing_width += (dodged * random.uniform(0,1.6))
else:
thing_width += (dodged * random.uniform(0.8,2))
#managing the level ups
if dodged == 10:
pygame.mixer.Sound.play(level_up)
bonus = 1.5
if dodged == 20:
pygame.mixer.Sound.play(level_up)
bonus = 2
if dodged == 30:
pygame.mixer.Sound.play(level_up)
bonus = 2.4
if dodged == 35:
pygame.mixer.Sound.play(level_up)
bonus = 2.8
# crash condition and calling the crash() function once the crash happened
if y + 38 < thing_starty + thing_height and (y + player_height)-15 > thing_starty + thing_height:
if x>thing_startx and x<thing_startx+thing_width or x+player_width>thing_startx and x+player_width<thing_startx+thing_width:
crash()
pygame.display.update()
#fps, running through the loop at a certain pace
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
Just assign one of the ges surfaces to player when the program starts instead of creating the transparent placeholder surface.
player = pygame.Surface((x,y), pygame.SRCALPHA, 32)
player = player.convert_alpha()
# Replace the lines above with this one.
player = gesImg_left
I'm trying to get a random car to appear from a list of cars saved in variables. The issue seems to be it chooses a random car from the list and doesn't change it while the game is being played. I'd like to change the car each time the previous car goes off screen.
Each time the game starts it chooses one car from the random list, but does not change the car each time the game loop runs.
I believe the problem lies in this bit of code
randomCars = [car1, car2, car3, car4, car5, car6, car7, car8]
enemy = random.choice(randomCars)
I have pasted the full code below:
import pygame
import time
import random
pygame.init()
#############
#############
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)
block_color = (53, 115, 255)
crash_sound = pygame.mixer.Sound("crash.mp3")
car_width = 55
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Super Racer')
clock = pygame.time.Clock()
gameIcon = pygame.image.load('carIcon.png')
backgroundImage = pygame.image.load("background.png")
backgroundImage = pygame.transform.scale(backgroundImage, (800, 600))
gameDisplay.blit(backgroundImage, (0, 0))
pygame.display.set_icon(gameIcon)
pause = False
# crash = True
def score(count):
font = pygame.font.SysFont("comicsansms", 25)
text = font.render("SCORE: " + str(count), True, red)
gameDisplay.blit(text, (0, 0))
def load_image(name_img):
car = pygame.image.load(name_img)
car = pygame.transform.scale(car, (60, 100)) # resize graphic
return car.convert_alpha() # remove whitespace from graphic
carImg = load_image('racecar.png')
enemies_list = ['diablo.png', 'aventador.png', 'nsx.png', 'bike.png', 'Mach6.png', 'speeder.png', 'Stingray.png', 'slr.png' ] # add all other cars
randomCars = [load_image(img) for img in enemies_list]
def things(enemy, thingx, thingy, thingw, thingh, color):
gameDisplay.blit(enemy, [thingx, thingy, thingw, thingh])
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 crash():
####################################
pygame.mixer.Sound.play(crash_sound)
pygame.mixer.music.stop()
####################################
largeText = pygame.font.SysFont("comicsansms", 115)
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, bright_green, game_loop)
button("Quit", 550, 450, 100, 50, red, bright_red, 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()
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("comicsansms", 20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
gameDisplay.blit(textSurf, textRect)
def quitgame():
pygame.quit()
quit()
def unpause():
global pause
pygame.mixer.music.unpause()
pause = False
def paused():
############
pygame.mixer.music.pause()
#############
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, bright_green, unpause)
button("Quit", 550, 450, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
def game_intro():
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.SysFont("comicsansms", 115)
TextSurf, TextRect = text_objects("Super Racer", largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
button("LEGGO!", 150, 450, 100, 50, green, bright_green, game_loop)
button("Quit", 550, 450, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
def game_loop():
global pause
enemy = random.choice(randomCars)
############
pygame.mixer.music.load('bgmusic.mp3')
pygame.mixer.music.play(-1)
############
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
enemy_speed = 4
thing_width = 55
thing_height = 95
enemy = random.choice(randomCars)
thingCount = 1
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.key == pygame.K_p:
pause = True
paused()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.blit(backgroundImage, (0, 0))
things(enemy, thing_startx, thing_starty, thing_width, thing_height, block_color)
thing_starty += enemy_speed
car(x, y)
score(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
#enemy_speed += .25
if dodged % 5 == 0:
enemy_speed += (dodged * 1)
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_intro()
game_loop()
pygame.quit()
quit()
Here's a minimal example. Just use random.choice to get a new car out of the list as soon as the current car leaves the screen.
import random
import pygame
pygame.init()
CAR_IMG1 = pygame.Surface((30, 50))
CAR_IMG1.fill((10, 150, 200))
CAR_IMG2 = pygame.Surface((30, 50))
CAR_IMG2.fill((210, 150, 0))
CAR_IMG3 = pygame.Surface((30, 50))
CAR_IMG3.fill((10, 250, 0))
CARS = [CAR_IMG1, CAR_IMG2, CAR_IMG3]
def main():
screen = pygame.display.set_mode((640, 480))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
car = random.choice(CARS)
pos_x = random.randrange(screen_rect.width-30)
pos_y = -50
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pos_y += 15
if pos_y > screen_rect.height:
car = random.choice(CARS)
pos_x = random.randrange(screen_rect.width-30)
pos_y = -50
screen.fill((30, 30, 30))
screen.blit(car, (pos_x, pos_y))
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
pygame.init()
main()
pygame.quit()
First initialize your list of enemy car images from which to choose one.
randomCars = [carImg1, carImg2, carImg3, carImg4]
Inside the game_loop() function but outside of the main loop set enemy = random.choice(randomCars)
Inside the main loop of the game_loop() function check to see if the enemy went off the screen. If so, set the enemy variable to a new random car.
if thing_starty > display_height:
# Reset enemy image
enemy = random.choice(randomCars)
# Reset thing co-ordinates
thing_starty = -600
thing_startx = random.randrange(0, display_width)
If the enemy = random.choice(randomCars) line of code doesn't work you could also try indexing the randomCars list with a random integer.
randomCarsIndex = random.randint(0, len(randomCars) - 1)
enemy = randomCars[randomCarsIndex]
Hope this helps!
import pygame
import time
import random
pygame.init()
display_height = 800#display width and height
display_width = 1000
black = (0,0,0)
white = (255,255,255)#defining colours
red = (255,0,0)
blue = (127, 179, 213)
peru = (139,119,101)
beige = (250,250,225)
lightb = (245,222,179)
bg = (255,248,220)
grey_slate = (50,50,50)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('The Algebra Game')
clock = pygame.time.Clock()
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',50)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def message_display2(text):
largeText = pygame.font.Font('freesansbold.ttf',30)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/3))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
def Try_Again1(msg,x,y,w,h,inac,act,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, act,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "Try Again":
Addition_loop1()
else:
pygame.draw.rect(gameDisplay, inac,(x,y,w,h))
def home_button(msg,x,y,w,h,inac,act,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.ellipse(gameDisplay, act,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "Home":
game_intro()
else:
pygame.draw.ellipse(gameDisplay, inac,(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 button(msg,x,y,w,h,inac,act,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, act,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "Addition":
Addition_loop1()
elif action == "Subtraction":
Subtraction_loop1()
elif action == "Multiplication":
Multiplication_loop1()
elif action == "Division":
Division_loop1()
elif action == "Option 1":
incorrect_loop1()
else:
pygame.draw.rect(gameDisplay, inac,(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 incorrect_loop1():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
message_display2("You are Incorrect")
Try_Again1("Try Again",25,25,150,50,peru,grey_slate,"Try Again")
pygame.display.update()
def Addition_loop1():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
home_button("Home",25,25,150,50,peru,grey_slate,"Home")
addition = pygame.image.load("addition.jpg")
gameDisplay.blit(addition,(330,50))
button("Option 1",50,500,200,50,peru,black,"Option 1")
pygame.display.update()
clock.tick(60)
def Subtraction_loop1():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
home_button("Home",25,25,150,50,peru,grey_slate,"Home")
pygame.display.update()
clock.tick(60)
def Multiplication_loop1():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
home_button("Home",25,25,150,50,peru,grey_slate,"Home")
pygame.display.update()
clock.tick(60)
def Division_loop1():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
home_button("Home",25,25,150,50,peru,grey_slate,"Home")
pygame.display.update()
clock.tick(60)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(grey_slate)
largeText = pygame.font.Font('freesansbold.ttf',50)
TextSurf, TextRect = text_objects("The Algebra Game", largeText)
TextRect.center = ((display_width/2),(display_height/14))
gameDisplay.blit(TextSurf, TextRect)
button("Addition",250,125,500,85,peru,black,"Addition")
button("Subtraction",250,250,500,85,peru,black,"Subtraction")
button("Multiplication",250,375,500,85,peru,black,"Multiplication")
button("Division",250,500,500,85,peru,black,"Division")
mouse = pygame.mouse.get_pos()
pygame.display.update()
clock.tick(15)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()
clock.tick(60)
game_intro()
pygame.quit()
quit
Hi, I am experiencing some difficulties getting a "Try_Again1" button function to work, it is currently not showing up text or taking me to the desired page (Addition_loop1) once clicked, the button is also flickering in and out of view from the screen when running. I am using Python 3.5 (32-bit). Any help with my issue would be much appreciated. Thankyou
So, I am making a simple video game in pygame, and it is very close to finishing. I was working on my pause screen, but when I hit p(the button I chose) it paused but when I hit continue it restarted the game. I went over the code and found nothing wrong. Then, I went to the question forum here and looked up the issue, I found something but they arent doing the code like I am, and on top of that the answer is hard to understand. The pause function is paused() and the unpause is, suprise, unpause(). Can you try to find where it went wrong? Here is my scource code:
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
dark_blue = (0,178,210)
blue = (109,178,201)
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
brown = (102, 51, 0)
ship_width = 96
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('_Asteroid Belt_')
clock = pygame.time.Clock()
thingImg = pygame.image.load("/home/pi/Desktop/asteroid.png")
shipImg = pygame.image.load('/home/pi/Desktop/spaceship.png')
bg = pygame.image.load("/home/pi/Desktop/py.png")
bgi = pygame.image.load("/home/pi/Desktop/introbg.jpg")
pause = False
def quitgame():
pygame.quit()
quit()
def unpause():
global pause
pause = False
def paused():
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Paused", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start Flight",100,450,200,100,dark_blue,blue,game_loop)
button("Land on Desktop",500,450,200,100,dark_blue,blue,quitgame)
#pygame.draw.rect(gameDisplay,dark_blue,(500,450,200,100))
pygame.display.update()
clock.tick(15)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.blit(bgi,(0,0))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Asteroid Belt", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start Flight",100,450,200,100,dark_blue,blue,game_loop)
button("Land on Desktop",500,450,200,100,dark_blue,blue,quitgame)
#pygame.draw.rect(gameDisplay,dark_blue,(500,450,200,100))
pygame.display.update()
clock.tick(15)
def message_display2(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)
def things_dodged(count):
font = pygame.font.SysFont(None,25)
text = font.render("Dodged: "+str(count), True, white)
gameDisplay.blit(text, (0,0))
def things(x,y, thing_width, thing_height,thing_startx,thing_starty):
gameDisplay.blit(thingImg, (x,y))
def ship(x,y):
gameDisplay.blit(shipImg,(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 button(msg,x,y,w,h,ic,ac,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,ac,(x,y,w,h))
if click[0] == 1 and action != None:
if action == game_loop:
game_loop()
elif action == quitgame:
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay,ic,(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_loop():
global pause
x = (300)
y = (410)
x_change=0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 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 = -20
if event.key == pygame.K_RIGHT:
x_change = 20
if event.key == pygame.K_p:
pause = True
paused()
if event.type == pygame.KEYUP:
if event .key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x+= x_change
gameDisplay.blit(bg, (0,0))
things(thing_startx,thing_starty,thing_width,thing_height,x,y)
thing_starty += thing_speed
thing_height=100
ship(x,y)
things_dodged(dodged)
if x > display_width - ship_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+=2
if y < thing_starty+thing_height:
cow = 5
if x > thing_startx and x < thing_startx + thing_width or x+ship_width > thing_startx and x+ship_width< thing_startx +thing_width:
crash()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
It seems that you do not unpause in your pause() function.
You should be adding something like this:
def paused():
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.K_p:
unpause()
In my code, I set the unpause button function to game_loop() instead of unpause(). So every time I went to unpause, I restarted the game loop! This is an example that you have to pay attention to every section of your code, not just the function thats going wrong.