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
Related
I'm trying to fix my game. When the game is over, it calls a crash() function. It gives the user the option to play again or quit. When calling my game_loop function in the "Play Again" button inside the crash() function, the game will not restart. Any suggestions? Thanks in advance.......................
import math
import random
import time
import pygame
from pygame import mixer
# Intialize the pygame
pygame.init()
# next setup the display
display_width = 800
display_height = 600
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('waterbackground.jpg')
# game clock to time frames per second
clock = pygame.time.Clock()
# Sound
mixer.music.load("ocean.wav")
mixer.music.play(-1)
# setup colors needed in the game
black = (0,0,0)
white = (255, 255, 255)
red = (200, 0, 0)
bright_red = (255,0,0)
block_color = (53,115,255)
green = (0,200,0)
bright_green = (0,255,0)
# Caption and Icon
pygame.display.set_caption("Pirate War")
icon = pygame.image.load('pirateship.png')
pygame.display.set_icon(icon)
# cannon
cannonImg = pygame.image.load('cannonball.png')
cannonX = 0
cannonY = 480
cannonX_change = 0
cannonY_change = 10
cannon_state = "ready"
# Player
playerImg = pygame.image.load('cannon.png')
playerX = 370
playerY = 480
playerX_change = 0
# Score
score_value = 0
# add explosion sound
crash_sound = pygame.mixer.Sound("explosion.wav")
# ship
shipImg = []
shipX = []
shipY = []
shipX_change = []
shipY_change = []
num_of_ships = 6
for i in range(num_of_ships):
shipImg.append(pygame.image.load('pirateship.png'))
shipX.append(random.randint(0, 736))
shipY.append(random.randint(50, 150))
shipX_change.append(4)
shipY_change.append(40)
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
testY = 10
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
credits_font = pygame.font.Font('freesansbold.ttf', 24)
# text object function called by message display function
def text_objects(text, font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (255, 255, 255))
screen.blit(score, (x, y))
def game_over_text():
over_text = over_font.render("GAME OVER!", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
crash()
def game_credits_text(text):
over_text = over_font.render(text, True, (255, 255, 255))
screen.blit(over_text, (200, 150))
def game_credits_text_small(text):
credits_text = credits_font.render(text, True, (255, 255, 255))
screen.blit(credits_text, (20, 350))
def game_intro_text_small(text):
credits_text = credits_font.render(text, True, (255, 255, 255))
screen.blit(credits_text, (125, 375))
def player(x, y):
screen.blit(playerImg, (x, y))
def ship(x, y, i):
screen.blit(shipImg[i], (x, y))
def fire_cannon(x, y):
global cannon_state
cannon_state = "fire"
screen.blit(cannonImg, (x + 16, y + 10))
def isCollision(shipX, shipY, cannonX, cannonY):
distance = math.sqrt(math.pow(shipX - cannonX, 2) + (math.pow(shipY - cannonY, 2)))
if distance < 27:
return True
else:
return False
# function to setup message display
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))
screen.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
def crash():
#add crash sound
pygame.mixer.music.stop()
pygame.mixer.Sound.play(crash_sound)
game_credits_text("Game Over!")
game_credits_text_small("Created by: Dominique Kellam, Hayley Cull and Dewayne Bowen")
while True:
# check for quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill((0, 0, 0))
#add buttons to start screen
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() # returns a list of [x,y]
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y: #check is mouse over button
# redraw the rectange with active color when mouseover
pygame.draw.rect(screen, ac, (x, y, w, h))
#check for a click
if click[0] == 1 and action!=None:
action()
else:
pygame.draw.rect(screen, ic, (x, y, w, h))
# now display text on top of button that was just redrawn
smallText = pygame.font.Font('freesansbold.ttf', 20)
TextSurf, TextRect = text_objects(msg, smallText)
TextRect.center = ((x+(w/2)), (y+(h/2)))
screen.blit(TextSurf, TextRect)
def quitgame():
pygame.quit()
quit()
# start screen code
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Pirate War", largeText)
game_intro_text_small("[space bar] - fire cannon, [<] [>] arrows to move")
TextRect.center = ((display_width/2), (display_height/2))
screen.blit(TextSurf, TextRect)
#add buttons to start screen
button("Go!",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 playerX
global playerX_change
global cannonX
global cannonY
global cannon_state
global score_value
# Game Loop
running = True
while running:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if cannon_state == "ready":
cannonSound = mixer.Sound("cannon_x.wav")
cannonSound.play()
# Get the current x cordinate of the spaceship
cannonX = playerX
fire_cannon(cannonX, cannonY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# 5 = 5 + -0.1 -> 5 = 5 - 0.1
# 5 = 5 + 0.1
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# ship Movement
for i in range(num_of_ships):
# Game Over
if shipY[i] > 440:
for j in range(num_of_ships):
shipY[j] = 2000
game_over_text()
break
shipX[i] += shipX_change[i]
if shipX[i] <= 0:
shipX_change[i] = 1 #######SHIP MOVEMENT
shipY[i] += shipY_change[i]
elif shipX[i] >= 736:
shipX_change[i] = -1 ######SHIP MOVEMENT
shipY[i] += shipY_change[i]
# Collision
collision = isCollision(shipX[i], shipY[i], cannonX, cannonY)
if collision:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
cannonY = 480
cannon_state = "ready"
score_value += 1
shipX[i] = random.randint(0, 736)
shipY[i] = random.randint(50, 150)
ship(shipX[i], shipY[i], i)
# cannon Movement
if cannonY <= 0:
cannonY = 480
cannon_state = "ready"
if cannon_state == "fire":
fire_cannon(cannonX, cannonY)
cannonY -= cannonY_change
player(playerX, playerY)
show_score(textX, testY)
pygame.display.update()
game_intro()
You are setting the ship y to 2000 which is > 400 so it just goes back to crash. Change this to zero and it will work.
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'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!
The image im trying to use is the drakeImg, which is supposed to drop from the top of the game frame, the game is working fine but i cannot see the drakeImg dropping from the top of the screen, all i can see is the boatImg and the background, but the dodged count and crash() still work. Here is my code:
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 700
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (3,30,104)
boat_width = 110
drake_width = 110
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Gotta Go Fast')
clock = pygame.time.Clock()
drakeImg = pygame.image.load('drake.png')
drakeImg = pygame.transform.scale(drakeImg, (100, 100))
boatImg = pygame.image.load('boat.png')
boatImg = pygame.transform.scale(boatImg, (100, 150))
bg = pygame.image.load("bg.png")
def drakes_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Drakes Dodged: " + str(count), True, green)
gameDisplay.blit(text,(0,0))
def drake(drakex, drakey):
gameDisplay.blit(drakeImg, (drakex, drakey))
def boat(x,y):
gameDisplay.blit(boatImg, (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/3))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Lost!')
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.75)
drake_startx = random.randrange(0, display_width)
drake_starty = -550
drake_speed = 4
drake_height = 100
drakesDodged = 0
gameExit = False
key_right = False
key_left = 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:
key_left = True
if event.key == pygame.K_RIGHT:
key_right = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
key_left = False
if event.key == pygame.K_RIGHT:
key_right = False
gameDisplay.blit(bg, (0, 0))
drake_starty += drake_speed
boat(x,y)
drakes_dodged(drakesDodged)
if key_left == True and x > 0:
x += -5
if key_right == True and x < (display_width - boat_width):
x += 5
if drake_starty > display_height:
drake_starty = 0 - drake_height
drake_startx = random.randrange(0,display_width)
drakesDodged += 1
if drakesDodged % 10 == 0:
drake_speed += 2
if y < drake_starty + drake_height:
if x + boat_width > drake_startx and x < drake_startx + drake_width:
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
You missed to call the drake method:
def game_loop():
# [...]
while not gameExit:
# [...]
drake(drake_startx, drake_starty) # <---
pygame.display.update()
clock.tick(60)
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.