How do I implement a play again feature in this Connect 4 game?
import numpy as np
import pygame
import math
pygame.init()
#COLORS
GREEN = (0,200,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
RED = (200,0,0)
YELLOW = (255,255,0)
WHITE = (255,255,255)
PINK = (255,0,127)
bright_pink = (255,51,153)
bright_red = (255,0,0)
bright_green = (0,255,0)
bright_blue = (0,0,204)
ROW_COUNT = 6
COLUMN_COUNT = 7
pause = False
#DISPLAY
gameDisplay = pygame.display.set_mode((ROW_COUNT, COLUMN_COUNT))
pygame.display.set_caption("Connect 4") #Window Title
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def create_board():
board = np.zeros((ROW_COUNT,COLUMN_COUNT))
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
hitSound.play()
def is_valid_location(board, col):
return board[ROW_COUNT-1][col] == 0
def get_next_open_row(board, col):
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
def print_board(board):
print(np.flip(board, 0))
def winning_move(board, piece):
# Check horizontal locations for win
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
# Check vertical locations for win
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
# Check positively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
# Check negatively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(3, ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
def draw_board(board):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
pygame.draw.rect(screen, bright_blue, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
if board[r][c] == 1:
pygame.draw.circle(screen, RED, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
elif board[r][c] == 2:
pygame.draw.circle(screen, YELLOW, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
pygame.display.update()
board = create_board()
print_board(board)
game_over = False
SQUARESIZE = 100
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width, height)
RADIUS = int(SQUARESIZE/2 - 5)
screen = pygame.display.set_mode(size)
draw_board(board)
pygame.display.update()
myfont2 = pygame.font.SysFont("Arial black", 75)
def gameover():
gameDisplay.blit(background, (0, 0))
gameDisplay.blit(gameoverimg, (0, 0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play Again", 210, 350, 300, 80, GREEN, bright_green, )
button("Quit", 260, 470, 200, 80, PINK, bright_pink, 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:
action()
else:
pygame.draw.rect(gameDisplay, ic, (x, y, w, h))
buttonText = pygame.font.SysFont("arial black", 50)
textSurf, textRect = text_objects(msg, buttonText)
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()
gameDisplay.blit(background, (0, 0))
gameDisplay.blit(pauseimg, (0, 0))
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Continue",210, 350, 300, 80, GREEN, bright_green, unpause)
button("Quit",260, 470, 200, 80, PINK, bright_pink, 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.blit(background, (0, 0))
gameDisplay.blit(gmenu, (0, 60))
button("START", 210, 350, 300, 80, GREEN, bright_green, game_loop)
button("QUIT", 260, 470, 200, 80, PINK, bright_pink, quit)
pygame.display.update()
clock.tick(15)
def game_loop(turn=0):
global pause
game_over = False
while not game_over:
print_board(board)
draw_board(board)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
posx = event.pos[0]
if turn == 0:
label2 = myfont2.render("RED TURN", 1, WHITE)
screen.blit(label2, (150, 10))
pygame.draw.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS)
else:
label3 = myfont2.render("YELLOW TURN", 1, WHITE)
screen.blit(label3, (50, 10))
pygame.draw.circle(screen, YELLOW, (posx, int(SQUARESIZE/2)), RADIUS)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = True
pause_sound.play()
paused()
# print_board(board)
# draw_board(board)
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE))
# Ask for Player 1 Input
if turn == 0:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 1)
if winning_move(board, 1):
label = myfont2.render("RED WINS", 1, RED)
screen.blit(label, (155,10))
# gameover()
game_over = True #Change to False so it will not auto-quit
# # Ask for Player 2 Input
else:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 2)
if winning_move(board, 2):
label = myfont2.render("YELLOW WINS", 1, YELLOW)
screen.blit(label, (60,10))
game_over = True #Change to False so it will not auto-quit
# gameover()
print_board(board)
draw_board(board)
turn += 1
turn = turn % 2
if game_over:
pygame.time.wait(3000)
gameover()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
Welcome to Stack Overflow. More specific questions, rather than "how do I do this", are preferred.
def gameover():
gameDisplay.blit(background, (0, 0))
gameDisplay.blit(gameoverimg, (0, 0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play Again", 210, 350, 300, 80, GREEN, bright_green, )
button("Quit", 260, 470, 200, 80, PINK, bright_pink, quit)
pygame.display.update()
clock.tick(15)
At the end of your button call for "Play Again", after your color definition, you need to call the correct function to "play again". It seems as though based on your code, you'd need to call game_loop or game_intro.
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.
I've been trying to make a button work for a pygame multiple choice game, where after the random question is pressed it will bring you to a question page with 2 answers, one right, one wrong. However they are not reacting to anything when pressed, my code can be seen below;
import pygame
import random
pygame.init()
win = pygame.display.set_mode((1200, 600))
pygame.display.set_caption("History Game")
#Background Image Loading
bg = pygame.image.load('bg.jpg')
bgAus = pygame.image.load('bg_Aus.jpg')
bgEN = pygame.image.load('bg_EN.jpg')
bgIR = pygame.image.load('bg_IR.jpg')
WHITE = (255, 255, 255)
ACTIVE_COLOR = pygame.Color('blue')
INACTIVE_COLOR = pygame.Color('red')
FONT = pygame.font.Font(None, 50)
def draw_buttonStart(buttonStart, win):
pygame.draw.rect(win, buttonStart['color'], buttonStart['rect'])
win.blit(buttonStart['text'], buttonStart['text rect'])
def draw_buttonAus1(buttonAus1, win):
pygame.draw.rect(win, buttonAus1['color'], buttonAus1['rect'])
win.blit(buttonAus1['text'], buttonAus1['text rect'])
def draw_buttonAus2(buttonAus2, win):
pygame.draw.rect(win, buttonAus2['color'], buttonAus2['rect'])
win.blit(buttonAus2['text'], buttonAus2['text rect'])
def draw_buttonIR1(buttonIR1, win):
pygame.draw.rect(win, buttonIR1['color'], buttonIR1['rect'])
win.blit(buttonIR1['text'], buttonIR1['text rect'])
def draw_buttonIR2(buttonIR2, win):
pygame.draw.rect(win, buttonIR2['color'], buttonIR2['rect'])
win.blit(buttonIR2['text'], buttonIR2['text rect'])
def draw_buttonEN1(buttonEN1, win):
pygame.draw.rect(win, buttonEN1['color'], buttonEN1['rect'])
win.blit(buttonEN1['text'], buttonEN1['text rect'])
def draw_buttonEN2(buttonEN2, win):
pygame.draw.rect(win, buttonEN2['color'], buttonEN2['rect'])
win.blit(buttonEN2['text'], buttonEN2['text rect'])
def create_button(x, y, w, h, text, callback):
text_surf = FONT.render(text, True, WHITE)
button_rect = pygame.Rect(x, y, w, h)
text_rect = text_surf.get_rect(center=button_rect.center)
button = {
'rect': button_rect,
'text': text_surf,
'text rect': text_rect,
'color': INACTIVE_COLOR,
'callback': callback,
}
return button
points = 0
def correct_answer():
global points
points += 100
print(points)
def wrong_answer():
global points
points -= 50
print(points)
moveOn = 0
def move_on():
global moveOn
moveOn = 1
win.blit(bg, (0, -200))
#Main Loop
over = False
while not over:
score = FONT.render('Score: ' + str(points), 1, (255,0,0))
win.blit(score, (390, 10))
pygame.display.flip()
buttonStart = create_button(50, 50, 250, 80, 'Random', move_on)
button_listStart = [buttonStart]
draw_buttonStart(buttonStart, win)
#Quits game if X is clicked
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listStart:
if button['rect'].collidepoint(event.pos):
button['callback']()
print (moveOn)
randomQ = random.randint(1,3)
if int(randomQ) == 1:
print("1")
buttonAus1 = create_button(275, 400, 250, 80, '1606', correct_answer)
buttonAus2 = create_button(675, 400, 250, 80, '1723', wrong_answer)
button_listAus = [buttonAus1, buttonAus2]
win.blit(bgAus, (-400, 0))
draw_buttonAus1(buttonAus1, win)
draw_buttonAus2(buttonAus2, win)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listAus:
if button['rect'].collidepoint(event.pos):
button['callback']()
print (points)
#Hover over button changes colour
elif event.type == pygame.MOUSEMOTION:
for button in button_listAus:
if button['rect'].collidepoint(event.pos):
button['color'] = ACTIVE_COLOR
else:
button['color'] = INACTIVE_COLOR
elif int(randomQ) == 2:
print ("2")
buttonEN1 = create_button(675, 400, 250, 80, '1715', correct_answer)
buttonEN2 = create_button(275, 400, 250, 80, '1789', wrong_answer)
button_listEN = [buttonEN1, buttonEN2]
win.blit(bgEN, (0, -150))
draw_buttonEN1(buttonEN1, win)
draw_buttonEN2(buttonEN2, win)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listEN:
if button['rect'].collidepoint(event.pos):
button['callback']()
#Hover over button changes colour
elif event.type == pygame.MOUSEMOTION:
for button in button_listEN:
if button['rect'].collidepoint(event.pos):
button['color'] = ACTIVE_COLOR
else:
button['color'] = INACTIVE_COLOR
else:
print ("3")
buttonIR1 = create_button(275, 400, 250, 80, '1760', correct_answer)
buttonIR2 = create_button(675, 400, 250, 80, '1812', wrong_answer)
button_listIR = [buttonIR1, buttonIR2]
win.blit(bgIR, (-375, -20))
draw_buttonIR1(buttonIR1, win)
draw_buttonIR2(buttonIR2, win)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listIR:
if button['rect'].collidepoint(event.pos):
button['callback']()
#Hover over button changes colour
elif event.type == pygame.MOUSEMOTION:
for button in button_listIR:
if button['rect'].collidepoint(event.pos):
button['color'] = ACTIVE_COLOR
else:
button['color'] = INACTIVE_COLOR
I was wandering if it might have something to do with the for loop as before I combined the for loop for the main loop and the quit feature, the quit feature didn't work at all so any help is appreciated, Thank you.
try binding your buttons to their respective mouse actions.
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.mixer.pre_init(44100, 16, 2, 4096)
pygame.init()
boop_sound = pygame.mixer.Sound("boop.wav")
display_width = 800
display_height = 600
white = (255,255,255)
black = (0,0,0)
blue = (0, 0, 150)
red = (200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0, 255, 0)
clock = pygame.time.Clock()
smallfont = pygame.font.SysFont("Rockwell", 25)
medfont = pygame.font.SysFont("Rockwell", 35)
largefont = pygame.font.SysFont("Rockwell", 50)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("How fast can you tap?")
##icon = pygame.image.load("apple.png")#should be 32x32
##pygame.display.set_icon(icon)
pygame.display.update()
def score(score):
text = smallfont.render("Clicks: "+str(score), True, blue)
gameDisplay.blit(text, [2,0])
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("How many times can you",
blue,
-80,
"large")
message_to_screen("click the button before the time runs out?",
blue,
-10,
"medium")
#message_to_screen("Press C to play, P to pause or Q to quit.",black,180)
button("Play", 150, 500, 100, 50, green, light_green, action="Play")
button("How to play", 325,500,150,50, yellow, light_yellow, action="How to play")
button("Quit", 550,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def game_over():
game_over = True
while game_over:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Out Of Time!",
red,
-100,
"large")
message_to_screen("You clicked: " + str(click) + " times",
blue,
-30)
button("Play Again", 325, 440, 150, 50, green, light_green, action="Play")
button("Quit", 350,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = ((buttonx +((buttonwidth/2)), buttony+(buttonheight/2)))
gameDisplay.blit(textSurf, textRect)
def message_to_screen(msg,color, y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
#screen_text = font.render(msg, True, color)
#gameDisplay.blit(screen_text, [display_width/2, display_height/2])
textRect.center = (display_width/ 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
def game_controls():
gcont = True
while gcont:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("How to play", blue, -100,"large")
message_to_screen("You have to click the button as many times", black, -40)
message_to_screen("as you possible can before the time runs out", black, -20)
button("Play", 150, 500, 100, 50, green, light_green, action="Play")
button("Main", 350,500,100,50, yellow, light_yellow, action="Main")
button("Quit", 550,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def button(text, x, y, width, height, inactive_color, active_color, action = None):
cur = pygame.mouse.get_pos()
clicked = pygame.mouse.get_pressed()
global click
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
if clicked[0] == 1 and action != None:
if action == "Quit":
pygame.quit()
quit()
if action == "How to play":
game_controls()
if action == "Play":
gameLoop()
if action == "Main":
game_intro()
if action == "Click":
click += 1
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
text_to_button(text, black, x, y, width, height)
ENDTIMER = pygame.USEREVENT+1
def gameLoop():
gameExit = False
gameOver = False
FPS = 15
click = 0
global click
timed = pygame.time.set_timer(ENDTIMER, 25000)
while not gameExit:
gameDisplay.fill(white)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.mixer.Sound.play(boop_sound)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action="Click")
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
elif event.type == ENDTIMER:
game_over()
score(click)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
game_intro()
gameLoop()
I am trying to make it so that pygame.time.set_time(), will only run after click > 0. I have tried placing the pygame.time.set_time in an if statement, but that did not work. Any responses are greatly appreciated! When placing the timer start in the MOUSEBUTTONDOWN event it will only start when the mouse is clicked, however everytime i click it resets.
def gameLoop():
ENDTIMER = pygame.USEREVENT+1
gameExit = False
gameOver = False
FPS = 15
click = 0
global click
timer_on =False
while not gameExit:
gameDisplay.fill(white)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.MOUSEBUTTONDOWN:
if not timer_on:
timed = pygame.time.set_timer(ENDTIMER, 25000)
pygame.mixer.Sound.play(boop_sound)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action="Click")
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
elif event.type == ENDTIMER:
gameExit = True
score(click)
pygame.display.update()
clock.tick(FPS)
game_over()
pygame.quit()
quit()