The issue that I am having is every time I run my game the start screen won't work right, for example, all click on the GO button and it won't let me start my game yet everything seems correct and in place, if anyone can please help it would very much be appreciated
import pygame, random
from time import sleep
pygame.init()
# music/sounds
CarSound = pygame.mixer.Sound("image/CAR+Peels+Out.wav")
CarSound_two = pygame.mixer.Sound("image/racing01.wav")
CarSound_three = pygame.mixer.Sound("image/RACECAR.wav")
CarSound_four = pygame.mixer.Sound("image/formula+1.wav")
Crowds = pygame.mixer.Sound("image/cheer_8k.wav")
Crowds_two = pygame.mixer.Sound("image/applause7.wav")
Crowds_three = pygame.mixer.Sound("image/crowdapplause1.wav")
music = pygame.mixer.music.load("image/Led Zeppelin - Rock And Roll (Alternate Mix) (Official Music Video).mp3")
pygame.mixer.music.play(-1)
bg = pygame.image.load('image/Crowds.png')
clock = pygame.time.Clock()
# Setting up our colors that we are going to use
GREEN = (20, 255, 140)
GREY = (210, 210, 210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACKWHITE = (96, 96, 96)
BLACK = (105, 105, 105)
RGREEN = (0, 66, 37)
LIGHT_RED = (200, 0, 0)
BRIGHT_GREEN = (0, 255, 0)
DARK_BLUE = (0, 0, 139)
BLUE = (0, 0, 255)
NAVY = (0, 0 , 128)
DARK_OLIVE_GREEN = (85, 107, 47)
YELLOW_AND_GREEN = (154, 205, 50)
SCREENWIDTH = 400
SCREENHEIGHT = 500
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
Icon = pygame.image.load("image/redca_iconr.png")
pygame.display.set_icon((Icon))
# This will be a list that will contain all the sprites we intend to use in our game.
# all_sprites_list = pygame.sprite.Group()
# player
playerIMG = pygame.image.load("image/red_racecar.png")
playerX = 280
playerY = 450
playerCar_position = 0
# player2
playerIMG_two = pygame.image.load("image/greencar.png")
playerX_two = 150
playerY_two = 450
playerCar_position_two = 0
# player3
playerIMG_three = pygame.image.load("image/Orangecar.png")
playerX_three = 60
playerY_three = 450
playerCar_position_three = 0
# player4
playerIMG_four = pygame.image.load("image/yellowcar2.png")
playerX_four = 210
playerY_four = 450
playerCar_position_four = 0
# Putting cars to the screen
def player(x, y):
screen.blit(playerIMG, (x, y))
def player_two(x, y):
screen.blit(playerIMG_two, (x, y))
def player_three(x, y):
screen.blit(playerIMG_three, (x, y))
def player_four(x, y):
screen.blit(playerIMG_four, (x, y))
finish_text = ""
font2 = pygame.font.SysFont("Papyrus", 65)
players_finished = 0
placings = ["1st", "2nd", "3rd", "4th"]
smallfont = pygame.font.SysFont("Papyrus", 15)
normalfont = pygame.font.SysFont("arial", 25)
differntfont = pygame.font.SysFont("futura", 25)
def score(score):
text = smallfont.render("Race cars passing: " + str(score), True, RGREEN)
screen.blit(text, [145, 490])
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def message_display(text):
largText = pygame.font.Font("Mulish-Regular.ttf", 15)
TextSurf, TextRect = text_objects(text, largText)
TextRect.center = ((SCREENWIDTH / 1), (SCREENHEIGHT / 1))
screen.blit(TextSurf, TextRect)
text_two = normalfont.render("Start new game?", 5, (0, 66, 37))
time_to_blit = None
screen.blit(bg, (0, 0))
pygame.display.flip()
Here is my button the Quit button works fine its just the GO button that when pressed won't let me start my game my only guess could be unless I placed something in the wrong place?
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(screen, 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(screen, aC, (x , y, w, h))
if 260 + 100 > mouse[0] > 260 and 40 + 50 > mouse[1] > 40:
pygame.draw.rect(screen, BLUE, (260, 40, 100, 50))
else:
pygame.draw.rect(screen, DARK_BLUE, (260, 40, 100, 50))
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects(msg, newtext)
textReact.center = ((x + (100 / 2))), (y + (h / 2))
screen.blit(textSurf, textReact)
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects("QUIT!", newtext)
textReact.center = ((260 + (100 / 2))), (40 + (50 / 2))
screen.blit(textSurf, textReact)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(YELLOW_AND_GREEN)
text = normalfont.render("Super Racer!", 8, (0, 66, 37))
screen.blit(text, (165 - (text.get_width() / 5), 100))
button("GO!", 60, 40, 100, 50, RED, LIGHT_RED, "Play")
button("QUIT!", 260, 40, 100, 50, BLUE, DARK_BLUE, "Quit")
pygame.display.update()
clock.tick(15)
# Main game loop
def game_loop():
run = True
while run:
# Drawing on Screen
screen.fill(BLACK)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
# Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 20)
text = font.render("Finish line!", 2, (150, 50, 25))
screen.blit(text, (185 - (text.get_width() / 2), 45))
screen.blit(bg, (-236, -34))
screen.blit(bg, (-236, -5))
screen.blit(bg, (-235, 140))
screen.blit(bg, (-235, 240))
screen.blit(bg, (-235, 340))
screen.blit(bg, (340, -60))
screen.blit(bg, (340, -60))
screen.blit(bg, (335, 5))
screen.blit(bg, (335, 130))
screen.blit(bg, (335, 230))
screen.blit(bg, (335, 330))
screen.blit(bg, (333, 330))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
CarSound.play()
playerCar_position = -0.5
if keys[pygame.K_q]:
playerCar_position = 0.5
if keys[pygame.K_2]:
CarSound_two.play()
playerCar_position_two = -0.5
if keys[pygame.K_w]:
playerCar_position_two = 0.5
if keys[pygame.K_3]:
CarSound_three.play()
playerCar_position_three = -0.5
if keys[pygame.K_e]:
playerCar_position_three = 0.5
if keys[pygame.K_4]:
CarSound_four.play()
playerCar_position_four = -0.5
if keys[pygame.K_r]:
playerCar_position_four = 0.5
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
finish_line_rect = pygame.Rect(50, 70, 235, 32)
game_intro()
score(players_finished)
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
inish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
Crowds.play()
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
Crowds_three.play()
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
Crowds_two.play()
if (players_finished and finish_text):
font = pygame.font.SysFont("Impact", 15)
text = font.render(finish_text, 5, (0, 66, 37))
screen.blit(text, (90 - (text.get_width() / 2), -2))
if (finish_text):
font = pygame.font.SysFont("Impact", 20)
text = font.render('Game Over!!!', 5, (0, 66, 37))
screen.blit(text, (250 - (text.get_width() / 5), -2))
if players_finished == 4:
time_to_blit = pygame.time.get_ticks() + 5000
if time_to_blit:
print(screen.blit(text_two, (130, 460)))
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = None
pygame.quit()
In the game loop, you're not calling the screen update. You also need to render the cars in the loop.
# Main game loop
def game_loop():
print(".......GAME LOOP........")
global playerCar_position,playerCar_position_two,playerCar_position_three,playerCar_position_four
global playerY,playerY_two,playerY_three,playerY_four,playerX,playerX_two,playerX_three,playerX_four
finish_line_rect = pygame.Rect(50, 70, 235, 32)
finish_text = ""
players_finished = 0
time_to_blit = 0
run = True
while run:
# Drawing on Screen
screen.fill(BLACK)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
# Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 20)
text = font.render("Finish line!", 2, (150, 50, 25))
screen.blit(text, (185 - (text.get_width() / 2), 45))
#.............
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
# CarSound.play()
playerCar_position = -0.5
if keys[pygame.K_q]:
playerCar_position = 0.5
if keys[pygame.K_2]:
# CarSound_two.play()
playerCar_position_two = -0.5
if keys[pygame.K_w]:
playerCar_position_two = 0.5
if keys[pygame.K_3]:
# CarSound_three.play()
playerCar_position_three = -0.5
if keys[pygame.K_e]:
playerCar_position_three = 0.5
if keys[pygame.K_4]:
# CarSound_four.play()
playerCar_position_four = -0.5
if keys[pygame.K_r]:
playerCar_position_four = 0.5
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
finish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
# Crowds.play()
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
# Crowds_three.play()
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
# Crowds_two.play()
if (players_finished and finish_text):
print("ft:", finish_text)
font = pygame.font.SysFont("Impact", 15)
textrect = font.render(finish_text, False, (0, 66, 37))
print('x', (SCREENWIDTH - text.get_width()) / 2)
screen.blit(textrect, (0,0))
screen.blit(textrect, ((SCREENWIDTH - textrect.get_width()) // 2, -5))
if (finish_text):
font = pygame.font.SysFont("Impact", 20)
text = font.render('Game Over!!!', 5, (0, 66, 37))
screen.blit(text, (250 - (text.get_width() / 5), -2))
if players_finished == 4:
time_to_blit = pygame.time.get_ticks() + 5000
if time_to_blit:
screen.blit(text_two, (130, 460))
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = 0
pygame.display.update()
clock.tick(60)
game_intro()
score(players_finished)
pygame.quit()
Try:
if action == "Play":
game_loop()
return
I think there is something wrong with your indentation of the code. You have pygame.quit() at the global level. So, you run pygame.init(), then define some functions, then pygame.quit()
Comment out the pygame.quit() line and see what happens.
Related
This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How do I detect collision in pygame?
(5 answers)
Closed 12 months ago.
I run the codes below. The computer always print "win" if (500 < mouse_x < 700) and (100 < mouse_y < 211) (player = 2) and "lose" if (100 < mouse_x < 300) and (100 < mouse_y < 221) (player = 1). I had checked the "player" and it works fine, but the "computer" always print value "2". If I change "if computer <= 10" to "else": "computer" always print value "1"
This is my codes:
import pygame
from random import randint
def draw_floor():
screen.blit(floor, (floorrunning, 453))
screen.blit(floor, (floorrunning + 800, 453))
pygame.init()
bg = pygame.image.load("background.png")
screen = pygame.display.set_mode((800,500))
GREY = (120, 120, 120)
WHITE = (255, 255, 255)
BLANK = (0, 0, 0)
floor = pygame.image.load("quangcaobanthan.png")
floorrunning = 0
xucxac1 = pygame.image.load("nan1.png")
xucxac2 = pygame.image.load("nan1_2.png")
xucxac3 = pygame.image.load("nan1_3.png")
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
youlose = pygame.image.load("youlose.png")
youlose_rect = youlose.get_rect(center = (400, 250))
youwin = pygame.image.load("youwin.png")
youwin_rect = youwin.get_rect(center = (400, 250))
running = True
replay = True
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
game_font = pygame.font.SysFont("04B_19.ttf", 40)
player = 0
def ketqua():
ketqua1_infor = game_font.render(str(ketqua1), True, (0,0,0))
ketqua1_rect = (190, 334)
screen.blit(ketqua1_infor, ketqua1_rect)
ketqua2_infor = game_font.render(str(ketqua2), True, (0,0,0))
ketqua2_rect = (390, 334)
screen.blit(ketqua2_infor, ketqua2_rect)
ketqua3_infor = game_font.render(str(ketqua3), True, (0,0,0))
ketqua3_rect = (590, 334)
screen.blit(ketqua3_infor, ketqua3_rect)
while running:
screen.blit(bg,(0,0))
mouse_x, mouse_y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and replay == False:
replay = True
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (100 < mouse_x < 300) and (100 < mouse_y < 221):
player = 1
if (500 < mouse_x < 700) and (100 < mouse_y < 211):
player = 2
if 10 < computer <= 18:
computer = 1
if computer <= 10:
computer = 2
if xucxac1_rect == (41, 300) and xucxac2_rect == (241, 300) and xucxac3_rect == (441, 300):
if computer == player:
print("win")
else:
print("lose")
pygame.draw.rect(screen, WHITE, (100, 100, 200, 121))
pygame.draw.rect(screen, WHITE, (500, 100, 200, 111))
pygame.draw.rect(screen, WHITE, (277, 0, 240, 100))
screen.blit(pygame.image.load("tai.png"), (100,100))
screen.blit(pygame.image.load("xiu.png"), (500,100))
screen.blit(pygame.image.load("start.png"), (275, -60))
draw_floor()
floorrunning -= 0.5
if floorrunning <= -800:
floorrunning = 0
if replay == False:
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
if replay:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (141 < mouse_x < 241) and (300 < mouse_y < 400):
xucxac1_rect = (41, 300)
if (341 < mouse_x < 441) and (300 < mouse_y < 400):
xucxac2_rect = (241, 300)
if (541 < mouse_x < 641) and (300 < mouse_y < 400):
xucxac3_rect = (441, 300)
if (277 < mouse_x < 527) and (0 < mouse_y < 79):
replay = False
pygame.draw.rect(screen, GREY, (50, 290, 700, 120))
pygame.draw.circle(screen, GREY, (195, 350), 48)
pygame.draw.circle(screen, GREY, (395, 350), 48)
pygame.draw.circle(screen , GREY,(595, 350), 48)
screen.blit(xucxac1, xucxac1_rect)
screen.blit(xucxac2, xucxac2_rect)
screen.blit(xucxac3, xucxac3_rect)
else:
pygame.draw.rect(screen, BLANK, (50, 290, 700, 120))
ketqua()
pygame.display.flip()
pygame.quit()
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 what am trying to get is a text to pop up after a car crosses the finish line for example “Game over first car won” but everything I done so far hasn’t worked and was hoping I can get some assistance here.
import pygame, random
import time
pygame.init()
# music/sounds
CarSound = pygame.mixer.Sound("image/CAR+Peels+Out.wav")
CarSound_two = pygame.mixer.Sound("image/racing01.wav")
CarSound_three = pygame.mixer.Sound("image/RACECAR.wav")
CarSound_four = pygame.mixer.Sound("image/formula+1.wav")
music = pygame.mixer.music.load("image/Led Zeppelin - Rock And Roll (Alternate Mix) (Official Music Video).mp3")
pygame.mixer.music.play(-1)
bg = pygame.image.load('image/Crowds.png')
#Setting up our colors that we are going to use
GREEN = (20, 255, 140)
GREY = (210, 210, 210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACKWHITE =(96, 96, 96)
SCREENWIDTH = 400
SCREENHEIGHT = 500
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
Icon = pygame.image.load("image/redca_iconr.png")
pygame.display.set_icon((Icon))
# This will be a list that will contain all the sprites we intend to use in our game.
#all_sprites_list = pygame.sprite.Group()
#player
playerIMG = pygame.image.load("image/red_racecar.png")
playerX = 250
playerY = 450
playerCar_position = 0
#player2
playerIMG_two = pygame.image.load("image/greencar.png")
playerX_two = 150
playerY_two = 450
playerCar_position_two = 0
#player3
playerIMG_three = pygame.image.load("image/Orangecar.png")
playerX_three = 50
playerY_three = 450
playerCar_position_three = 0
#player4
playerIMG_four = pygame.image.load("image/yellow_car.png")
playerX_four = 200
playerY_four = 450
playerCar_position_four = 0
#Putting cars to the screen
def player(x, y):
screen.blit(playerIMG, (x, y))
def player_two(x, y):
screen.blit(playerIMG_two, (x, y))
def player_three(x, y):
screen.blit(playerIMG_three, (x, y))
def player_four(x, y):
screen.blit(playerIMG_four, (x, y))
finish_text = ""
font2 = pygame.font.SysFont("Papyrus", 45)
players_finished = 0
placings = ["1st", "2nd", "3rd", "4th"]
def text_objects(text, font):
textSurface = font.render(text, True, RED)
return textSurface, textSurface.get_rect()
def message_display(text):
largText =pygame.font.Font("Mulish-Regular.ttf", 15)
TextSurf, TextRect = text_objects(text, largText)
TextRect.center = ((SCREENWIDTH / 1), (SCREENHEIGHT / 1))
screen.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
screen.blit(bg, (0, 0))
pygame.display.flip()
# Main game loop
run = True
clock = pygame.time.Clock()
#TIP - lots of our actions take place in our while loop cause we want the function/program to run consistently
while run:
# Drawing on Screen
screen.fill(GREEN)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
#Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 35)
text = font.render("Finish line!", 4, (150, 50, 25))
screen.blit(text, (180 - (text.get_width() / 2), -8))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
CarSound.play()
playerCar_position = -0.1
if keys[pygame.K_q]:
playerCar_position = 0.1
if keys[pygame.K_2]:
CarSound_two.play()
playerCar_position_two = -0.1
if keys[pygame.K_w]:
playerCar_position_two = 0.1
if keys[pygame.K_3]:
CarSound_three.play()
playerCar_position_three = -0.1
if keys[pygame.K_e]:
playerCar_position_three = 0.1
if keys[pygame.K_4]:
CarSound_four.play()
playerCar_position_four = -0.1
if keys[pygame.K_r]:
playerCar_position_four = 0.1
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
finish_line_rect = pygame.Rect(50, 70, 235, 32)
Here is where I been trying to see if I can get my text to pop up but haven’t had any luck I do get an output of which player crosses the line from first to last car but am trying to get a text that says “Whichever car crosses first won Game over” as soon the car crosses the line
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
finish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
#print("Player two has crossed into finish line first other car lost!")
#finish_text = "Player 4 is " + placings[players_finished]
pygame.display.flip()
pygame.quit()
Try something like this. At the end of the loop, if there is a finisher, blit the text to the screen the same way you wrote "Finish Line!"
if (players_finished and finish_text):
font = pygame.font.SysFont("Impact", 35)
text = font.render(finish_text, 4, (150, 250, 25))
screen.blit(text, (180 - (text.get_width() / 2), -8))
If you want the 'popup' to be temporary, you will need add a timer or counter to clear the finish_text so it stops being drawn.
I am trying to get a text to say "Game Over" for 5 seconds once a car reaches the finish line.
import pygame, random
from time import sleep
pygame.init()
# music/sounds
CarSound = pygame.mixer.Sound("image/CAR+Peels+Out.wav")
CarSound_two = pygame.mixer.Sound("image/racing01.wav")
CarSound_three = pygame.mixer.Sound("image/RACECAR.wav")
CarSound_four = pygame.mixer.Sound("image/formula+1.wav")
music = pygame.mixer.music.load("image/Led Zeppelin - Rock And Roll (Alternate Mix) (Official Music Video).mp3")
pygame.mixer.music.play(-1)
bg = pygame.image.load('image/Crowds.png')
#Setting up our colors that we are going to use
GREEN = (20, 255, 140)
GREY = (210, 210, 210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACKWHITE =(96, 96, 96)
SCREENWIDTH = 400
SCREENHEIGHT = 500
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
Icon = pygame.image.load("image/redca_iconr.png")
pygame.display.set_icon((Icon))
# This will be a list that will contain all the sprites we intend to use in our game.
#all_sprites_list = pygame.sprite.Group()
#player
playerIMG = pygame.image.load("image/red_racecar.png")
playerX = 250
playerY = 450
playerCar_position = 0
#player2
playerIMG_two = pygame.image.load("image/greencar.png")
playerX_two = 150
playerY_two = 450
playerCar_position_two = 0
#player3
playerIMG_three = pygame.image.load("image/Orangecar.png")
playerX_three = 50
playerY_three = 450
playerCar_position_three = 0
#player4
playerIMG_four = pygame.image.load("image/yellow_car.png")
playerX_four = 200
playerY_four = 450
playerCar_position_four = 0
#Putting cars to the screen
def player(x, y):
screen.blit(playerIMG, (x, y))
def player_two(x, y):
screen.blit(playerIMG_two, (x, y))
def player_three(x, y):
screen.blit(playerIMG_three, (x, y))
def player_four(x, y):
screen.blit(playerIMG_four, (x, y))
finish_text = ""
font2 = pygame.font.SysFont("Papyrus", 65)
players_finished = 0
placings = ["1st", "2nd", "3rd", "4th"]
def text_objects(text, font):
textSurface = font.render(text, True, RED)
return textSurface, textSurface.get_rect()
def message_display(text):
largText =pygame.font.Font("Mulish-Regular.ttf", 15)
TextSurf, TextRect = text_objects(text, largText)
TextRect.center = ((SCREENWIDTH / 1), (SCREENHEIGHT / 1))
screen.blit(TextSurf, TextRect)
screen.blit(bg, (0, 0))
pygame.display.flip()
**Here is the function on where am trying to show the text temporary on the screen**
def Game_over():
if (players_finished):
clock.tick(1)
pygame.time.delay(5000)
font = pygame.font.SysFont("Impact", 25)
text = font.render("Game over!", 4, (0, 66, 37))
screen.blit(text, (185 - (text.get_width() / 2), 120))
pygame.display.flip()
# Main game loop
run = True
clock = pygame.time.Clock()
#TIP - lots of our actions take place in our while loop cause we want the function/program to run consistently
while run:
# Drawing on Screen
screen.fill(GREEN)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
#Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 35)
text = font.render("Finish line!", 4, (150, 50, 25))
screen.blit(text, (180 - (text.get_width() / 2), -8))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
CarSound.play()
playerCar_position = -0.1
if keys[pygame.K_q]:
playerCar_position = 0.2
if keys[pygame.K_2]:
CarSound_two.play()
playerCar_position_two = -0.1
if keys[pygame.K_w]:
playerCar_position_two = 0.2
if keys[pygame.K_3]:
CarSound_three.play()
playerCar_position_three = -0.1
if keys[pygame.K_e]:
playerCar_position_three = 0.2
if keys[pygame.K_4]:
CarSound_four.play()
playerCar_position_four = -0.1
if keys[pygame.K_r]:
playerCar_position_four = 0.2
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
finish_line_rect = pygame.Rect(50, 70, 235, 32)
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
finish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
if (players_finished and finish_text):
font = pygame.font.SysFont("Impact", 25)
text = font.render(finish_text, 4, (0, 66, 37))
screen.blit(text, (185 - (text.get_width() / 2), 90))
Game_over()
pygame.display.update()
#print("Player two has crossed into finish line first other car lost!")
#finish_text = "Player 4 is " + placings[players_finished]
pygame.display.flip()
pygame.quit()
add a variable at the start of your code with the name tick_var and if you want a fixed tickrate remove it from the parameter of the function if not change your code and att the tickrate as a paramter of the function when used.
def Game_over(tickrate):
global tick_var
tick_var +=1
if(tick_var>5*tickrate):
if (players_finished):
clock.tick(tickrate)
font = pygame.font.SysFont("Impact", 25)
text = font.render("Game over!", 4, (0, 66, 37))
screen.blit(text, (185 - (text.get_width() / 2), 120))
pygame.display.flip()
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!