So my pause display keeps returning after I click on the button which continues everything.
This is included in the code:
"def paused():
global pause
clock = pygame.time.Clock()"
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.fill(0)
screen.blit(intropic, (0, 0))
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
# print(mouse)
if 270 + 120 > mouse[0] > 270 and 590 + 50 > mouse[1] > 590:
pygame.draw.rect(screen, (0, 0, 0), (268, 588, 124, 54))
pygame.draw.rect(screen, (0, 255, 0), (270, 590, 120, 50))
if click[0] == 1:
pause = False
else:
pygame.draw.rect(screen, (0, 0, 0), (268, 588, 124, 54))
pygame.draw.rect(screen, (100, 255, 100), (270, 590, 120, 50))
if 770 + 150 > mouse[0] > 770 and 590 + 50 > mouse[1] > 590:
pygame.draw.rect(screen, (0, 0, 0), (768, 588, 154, 54))
pygame.draw.rect(screen, (255, 0, 0), (770, 590, 150, 50))
if click[0] == 1:
pygame.quit()
exit()
else:
pygame.draw.rect(screen, (0, 0, 0), (768, 588, 154, 54))
pygame.draw.rect(screen, (255, 100, 100), (770, 590, 150, 50))
healthfont = pygame.font.Font(None, 40)
start = healthfont.render("Weiter", True, (0, 0, 0))
textRect1 = start.get_rect()
textRect1.topright = [370, 603]
screen.blit(start, textRect1)
healthfont = pygame.font.Font(None, 40)
end = healthfont.render("Beenden", True, (0, 0, 0))
textRect1 = end.get_rect()
textRect1.topright = [900, 603]
screen.blit(end, textRect1)
pausefont = pygame.font.Font(None, 80)
pausetxt = pausefont.render("Pause", True, (0, 0, 0))
textRect1 = pausetxt.get_rect()
textRect1.center = [800, 300]
screen.blit(pausetxt, textRect1)
pygame.display.flip()
This is the code if you press P:
if keys[4]:
pause = True
paused()
There is also a global pause = False
any help is much appreciated
Being paused or not paused, it's just a boolean. Your program must decide what that means.
Perhaps it means that the screen is not updated, and perhaps input-handling is different.
Below is a re-working of your code where if the paused flag global_paused ever gets set, the screen stops painting everything except a "*** PAUSED ***" banner.
Note the use of pyagme.Rect to store rectangles, constants for colours, an simpler testing of collisions. Fonts only need to be loaded once, so these have been moved outside the main loop.
global_paused = False
BLACK = (0, 0, 0)
RED = (0, 255, 0)
GREENISH = (100, 255, 100)
area1 = pygame.Rect( 268, 588, 124, 54 )
area2 = pygame.Rect( 270, 590, 120, 50 )
area3 = pygame.Rect(768, 588, 154, 54)
area4 = pygame.Rect(770, 590, 150, 50)
healthfont = pygame.font.Font(None, 40)
start = healthfont.render("Weiter", True, BLACK )
textRect1 = start.get_rect()
textRect1.topright = [370, 603]
healthfont = pygame.font.Font(None, 40)
end = healthfont.render("Beenden", True, BLACK )
textRect1 = end.get_rect()
textRect1.topright = [900, 603]
pausefont = pygame.font.Font(None, 80)
pausetxt = pausefont.render("Pause", True, BLACK )
textRect1 = pausetxt.get_rect()
textRect1.center = [800, 300]
pause_mode = pausefont.render( "*** PAUSED ***", True, RED, BLACK )
clock = pygame.time.Clock()
exiting = False
while not exiting:
mouse_click = None
mouse_pos = pygame.mouse.get_pos()
# Handle Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif ( event.type == pygame.MOUSEBUTTONUP ):
mouse_click = pygame.mouse.get_pressed()
if ( area1.collidepoint( event.pos ) ):
global_paused = not global_paused
elif ( area3.collidepoint( event.pos ) ):
exiting = True
elif ( event.type == pygame.KEYUP ):
if ( event.key == pygame.K_p ):
global_paused = not global_paused
# draw the screen
screen.fill( BLACK )
if ( not global_paused ):
screen.blit(intropic, (0, 0))
pygame.draw.rect(screen, BLACK, area1 )
if ( area1.collidepoint( mouse_pos ) ):
pygame.draw.rect(screen, RED, area2 )
else:
pygame.draw.rect(screen, GREENISH, area2 )
pygame.draw.rect(screen, BLACK, area3 )
pygame.draw.rect(screen, RED, area4 )
else:
pygame.draw.rect(screen, GREENISH, area4 )
screen.blit(start, textRect1)
screen.blit(end, textRect1)
screen.blit(pausetxt, textRect1)
else:
# everything is paused
screen.blit( pause_mode, ( 0, 0 ) )
pygame.display.flip()
clock.tick( 60 )
pygame.quit()
Related
I use a system like this which should theoretically work to close the window:
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Here is the code:
import pygame
import random
import sys
# Set width and height of window
(width, height) = (400, 600)
# Sets the colours
background_colour = (0, 2, 20)
white = (255, 255, 255)
# creates window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Space Dodger")
screen.fill(background_colour)
def gameLoop():
# sets sprite starting coordinates
rocketX = 200
rocketY = 450
leftX = 0
leftY = -25
leftWidth = random.randint(0, 300)
# sets obstacle start speed
obstacleSpeed = 1
# sets starting score
score = 0
pygame.init()
font = pygame.font.Font("Pixeled.ttf", 32)
fontSmall = pygame.font.Font("Pixeled.ttf", 25)
scoreX = 10
scoreY = 10
# All images/sprites
# rocket
rocket = pygame.image.load("rocket.png")
rocket = pygame.transform.smoothscale(rocket, (50, 100))
# background image
backgroundSpace = pygame.image.load("spacesky.png")
backgroundSpace = pygame.transform.rotate(backgroundSpace, 90)
backgroundColour = (10, 32, 61)
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# sets rectangles for obstacles
leftObstacle = pygame.draw.rect(screen, white, pygame.Rect(leftX, leftY, leftWidth, 25))
rightObstacle = pygame.draw.rect(
screen, white, pygame.Rect(leftWidth + 100, leftY, width, 25)
)
rocketRec = pygame.draw.rect(
screen, backgroundColour, pygame.Rect(rocketX + 10, rocketY, 30, 75)
)
# sets score text
displayScore = font.render(str(score), True, (105, 105, 105))
# makes cursor invisible
pygame.mouse.set_visible(False)
# draws new layer over screen
screen.blit(backgroundSpace, (0, 0))
# tracks the mosue location
mouseX, mouseY = pygame.mouse.get_pos()
# draws rectangle behind rocket
pygame.draw.rect(screen, backgroundColour, rocketRec)
# displays the rocket
screen.blit(rocket, (rocketX, rocketY))
# sets rocket horizontal position
if mouseX > width - 50:
rocketX = width - 50
else:
rocketX = mouseX
# displays the score
screen.blit(displayScore, (scoreX, scoreY))
# creates the moving obstacles
pygame.draw.rect(screen, white, leftObstacle)
pygame.draw.rect(screen, white, rightObstacle)
leftY = leftY + obstacleSpeed
# brings obstacle back to top
if leftY > 600:
leftY = -25
leftWidth = random.randint(0, 300)
score = score + 1
if obstacleSpeed >= 6:
obstacleSpeed = 6
else:
obstacleSpeed = obstacleSpeed + 0.2
if rocketRec.colliderect(leftObstacle) or rocketRec.colliderect(rightObstacle):
collisionScreen()
def startScreen():
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# background image
backgroundSpace = pygame.image.load("spacesky.png")
backgroundSpace = pygame.transform.rotate(backgroundSpace, 90)
backgroundColour = (10, 32, 61)
pygame.init()
fontSmall = pygame.font.Font("Pixeled.ttf", 25)
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# start screen
# makes cursor visible
pygame.mouse.set_visible(True)
# tracks the mosue location
mouseX, mouseY = pygame.mouse.get_pos()
# draws new layer over screen
screen.blit(backgroundSpace, (0, 0))
# Puts on logo
logo = pygame.image.load("name.png")
logo = pygame.transform.smoothscale(logo, (500, 300))
screen.blit(logo, (-40, 10))
# creates start button
startRecU = pygame.draw.rect(screen, darkGrey, pygame.Rect(120, 270, 160, 60))
startRec = pygame.draw.rect(screen, lightGrey, pygame.Rect(125, 275, 150, 50))
startText = fontSmall.render("START", True, (0, 0, 0))
# displays the start text
screen.blit(startText, (135, 262))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 330 > mouseY > 270:
darkGrey = (200, 200, 200)
lightGrey = (165, 165, 165)
else:
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
# detects if start button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 330 > mouseY > 270:
gameLoop()
# creates quit button
quitRecU = pygame.draw.rect(screen, darkGrey2, pygame.Rect(120, 350, 160, 60))
quitRec = pygame.draw.rect(screen, lightGrey2, pygame.Rect(125, 355, 150, 50))
quitText = fontSmall.render("QUIT", True, (0, 0, 0))
# displays the start text
screen.blit(quitText, (156, 340))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 410 > mouseY > 350:
darkGrey2 = (200, 200, 200)
lightGrey2 = (165, 165, 165)
else:
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# detects if quit button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 410 > mouseY > 350:
running = False
def collisionScreen():
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# background image
backgroundSpace = pygame.image.load("spacesky.png")
backgroundSpace = pygame.transform.rotate(backgroundSpace, 90)
backgroundColour = (10, 32, 61)
# explosion
explosion = pygame.image.load("explosion.png")
explosion = pygame.transform.smoothscale(explosion, (100, 100))
pygame.init()
fontSmall = pygame.font.Font("Pixeled.ttf", 25)
fontMini = pygame.font.Font("Pixeled.ttf", 15)
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# draws new layer over screen
screen.blit(backgroundSpace, (0, 0))
# makes cursor visible
pygame.mouse.set_visible(True)
# tracks the mosue location
mouseX, mouseY = pygame.mouse.get_pos()
# displays the explosion
screen.blit(explosion, (150, 400))
# creates play again button
playAgainRecU = pygame.draw.rect(screen, darkGrey, pygame.Rect(120, 270, 160, 60))
playAgainRec = pygame.draw.rect(screen, lightGrey, pygame.Rect(125, 275, 150, 50))
playAgainText = fontMini.render("PLAY AGAIN", True, (0, 0, 0))
# displays the start text
screen.blit(playAgainText, (135, 278))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 330 > mouseY > 270:
darkGrey = (200, 200, 200)
lightGrey = (165, 165, 165)
else:
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
# detects if play button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 330 > mouseY > 270:
gameLoop()
# creates quit button
quit2RecU = pygame.draw.rect(screen, darkGrey2, pygame.Rect(120, 350, 160, 60))
quit2Rec = pygame.draw.rect(screen, lightGrey2, pygame.Rect(125, 355, 150, 50))
quit2Text = fontSmall.render("QUIT", True, (0, 0, 0))
# displays the start text
screen.blit(quit2Text, (156, 340))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 410 > mouseY > 350:
darkGrey2 = (200, 200, 200)
lightGrey2 = (165, 165, 165)
else:
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# detects if quit button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 410 > mouseY > 350:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
startScreen()
Your code is pretty messy, try to do all your code to only one main loop (you have three now). This is how I suggest how it should be done.
import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
#Conststants, variables and images
startMenu = True
mainGame = False
collisionScreen = False
#Main loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
#All things that are supposed to happen can be pressed by the mouse (if statement)
if startMenu:
#Start Menu code
elif mainGame:
#Main game code
elif collisionScreen:
#Collision screen code
pygame.display.update()
clock.tick(60) #fps
I hope it helps you, Adam
Hello I am making a tic tac toe game in pygame the problem i encountered is that when i draw an x on the board it does not draw.it works when i draw a circle as shown in the code. please tell me how to fix also can you tell me how to take turns in this game because i cannot figure out how to draw an x and let the computer draw an o and so on.i want to wait for the user to draw an x and then let the computer draw an o.
Here Is The Code:
import pygame,random
pygame.init()
width = 600
height = 600
res = (width,height)
screen = pygame.display.set_mode(res)
pygame.display.set_caption("Tic Tac Toe")
background = (255,150,150)
color_light = (170,170,170)
color_dark = (100,100,100)
hover_color = (255, 204, 203)
rect_list = [
pygame.Rect(10, 10, 180, 190),
pygame.Rect(200, 10, 190, 190),
pygame.Rect(400, 10, 190, 190),
pygame.Rect(10, 210, 180, 180),
pygame.Rect(200, 210, 190, 180),
pygame.Rect(400, 210, 190, 180),
pygame.Rect(10, 400, 180, 190),
pygame.Rect(200, 400, 190, 190),
pygame.Rect(400, 400, 190, 190)]
clicked_list = [0 for _ in rect_list]
count = 0
def draw_x(x,y,width,height):
for i in range(5):
pygame.draw.aaline(screen,"blue",(x+i,y),(width+x+i,height+y)) # start_pos(x+thickness,y)---end_pos(width+x+thickness,height+y)
pygame.draw.aaline(screen,"blue",(width+x+i,y),(x+i,height+y)) # start_pos(x+width+thickness,y)---end_pos(x+thickness,y+height)
def draw_line():
line_color = (212, 212, 255)
pygame.draw.rect(screen, line_color, (190,10,10,580))
pygame.draw.rect(screen, line_color, (390, 10, 10, 580))
pygame.draw.rect(screen, line_color, (10, 200, 580, 10))
pygame.draw.rect(screen, line_color, (10, 390, 580, 10))
def highlight():
for rect in rect_list:
if rect.collidepoint(mouse):
pygame.draw.rect(screen,hover_color,rect)
def random_no():
randomno = random.randint(0,len(rect_list)-1)
if clicked_list[randomno] != 1:
pass
else:
random_no()
return randomno
def mouse_click():
x_turn = True
y_turn = False
o_no = random_no()
clicked_list[o_no] = 2
for i,rect in enumerate(rect_list):
if clicked_list[i] == 1:
if x_turn and clicked:
pygame.draw.rect(screen, background, rect)
draw_x(rect.x,rect.y,rect.width,rect.height)
if clicked_list[i] == 2:
if y_turn:
pygame.draw.rect(screen, background, rect)
pygame.draw.ellipse(screen, "blue", rect, 5)
# rect_list.remove(rect_list[i])
# clicked_list.remove(clicked_list[i])
while True:
mouse = pygame.mouse.get_pos()
x = screen.get_at(mouse)[:3]
screen.fill(background)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
clicked = True
for i, rect in enumerate(rect_list):
if rect.collidepoint(ev.pos) and x == hover_color:
clicked_list[i] = 1
draw_line()
highlight()
mouse_click()
pygame.display.update()
The mouse click must be handled in the event loop. However, you need a function draw_borad that draws "X" and "O".
Add a variable that indicates if its the turn of "X" or "O":
x_turn = True
If the mouse is pressed and a field is empty (0), change the status of the field and change the x_turn variable:
if rect.collidepoint(ev.pos) and x == hover_color:
if clicked_list[i] == 0:
clicked_list[i] = 1 if x_turn else 2
x_turn = not x_turn
Draw all the "X" and "O" in draw_borad:
def draw_borad():
for i,rect in enumerate(rect_list):
if clicked_list[i] == 1:
pygame.draw.rect(screen, background, rect)
draw_x(rect.x,rect.y,rect.width,rect.height)
if clicked_list[i] == 2:
pygame.draw.rect(screen, background, rect)
pygame.draw.ellipse(screen, "blue", rect, 5)
x_turn = True
while True:
mouse = pygame.mouse.get_pos()
x = screen.get_at(mouse)[:3]
screen.fill(background)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
clicked = True
for i, rect in enumerate(rect_list):
if rect.collidepoint(ev.pos) and x == hover_color:
if clicked_list[i] == 0:
clicked_list[i] = 1 if x_turn else 2
x_turn = not x_turn
draw_line()
highlight()
draw_borad()
pygame.display.update()
My game has been created but I would really like to add a second level to it how could I go about and creating another level for my racing game? I have created the first level to it but I would want to add another level as soon as my car reaches the end of the of the finish line. How can I do that? Thank you in advance!
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")
final_tone = pygame.mixer.Sound("image/Victory.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')
main_img = pygame.image.load("image/img4.png")
main_img2 = pygame.image.load("image/img5.png")
side_img = pygame.image.load("image/bull2.png")
side_img2 = pygame.image.load("image/fox.png")
pauseimg = pygame.image.load("image/pause2.png")
clock = pygame.time.Clock()
pause = False
# 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 = []
next_level = 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 level(next_level):
level = normalfont.render("Level: "+ str(next_level), True, BLACK)
screen.blit(level, [250, 10])
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
pygame.display.flip()
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(screen, iC, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "Play":
game_loop()
if action == "unpause":
unpause()
elif action == "Quit":
pygame.quit()
quit()
else:
pygame.draw.rect(screen, aC, (x, y, w, h))
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 unpause():
global pause
pause = False
def paused():
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects("paused", newtext)
textReact.center = ((100 + (100 / 2))), (100 + (100 / 2))
screen.blit(textSurf, textReact)
screen.fill(WHITE)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(pauseimg, (0, 1))
button(" Continue!?", 40, 40, 125, 50, DARK_BLUE, BLUE, "unpause")
button("QUIT!", 260, 40, 100, 50, LIGHT_RED, 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()
screen.fill(BLACK)
text = normalfont.render("Super Racer!", 8, (0, 66, 37))
new_text = normalfont.render("By Rafa94", 8, (0, 66, 37))
screen.blit(text, (35 - (text.get_width() / 5), 5))
screen.blit(new_text, (300 - (text.get_width() / 5), 5))
screen.blit(main_img, (5,340))
screen.blit(main_img2, (85, 115))
screen.blit(side_img, (330, 455))
screen.blit(side_img2, (5, 445))
button("GO!", 60, 40, 100, 50, DARK_BLUE, BLUE, "Play")
button("QUIT!", 260, 40, 100, 50, LIGHT_RED, RED, "Quit")
pygame.display.update()
clock.tick(15)
# Main game loop
def game_loop():
global pause
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
next_level = 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))
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
if keys[pygame.K_SPACE]:
pause = True
paused()
# 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", 17)
textrect = font.render(finish_text, False, (0, 66, 37))
#print('x', (SCREENWIDTH - text.get_width()) / 2)
screen.blit(textrect, (65 - (text.get_width() / 5), -2))
#screen.blit(textrect, ((SCREENWIDTH - textrect.get_width()) // 2, -5))
if (finish_line_rect.collidepoint and players_finished):
#pygame.mixer.final_tone.play(-1)
final_tone.play()
pygame.mixer.music.play(0)
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, (100, 345))
#final_tone.play()
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = 0
if players_finished == 4:
next_level = 1
score(players_finished)
level(next_level)
pygame.display.update()
clock.tick(60)
game_intro()
pygame.quit()
Make everything you currently have for the level 1 specifically (track, soundtrack, etc) as a class of Level1. And create similar for Level2. Then in your game loop initialize level (for now it can be a global variable to look from, but it is suggested to have a Game object that has attributes like this encapsulated inside it) as Level1 while starting a new game. And when player is finished with level1 (handle the check inside Level1 class that way you can have different parameters of finishing on different levels), change the level to Level2.
What different things you need to keep in mind? Render your level based on currently selected level. Look into this answer for some more insight.
I am making a game, and when I want to go through the loop normally, it doesn't work.
it goes through the loop, but for some reason, it backtracks, rather than starting over. When I add a continue statement, the button just disappears.
Why isn't the continue statement working properly?
Here is my code:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
bro = True
x = 100
y = 100
#button1 = pygame.draw.rect(screen, (0, 0, 255), (200, 200, 30, 30))
#if check <= pos - (w/2) and check >=
pygame.display.set_caption("Auto Maze!")
donk = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
try:
assert button1.collidepoint(mouse)
except AssertionError:
pass
except NameError:
pass
else:
donk = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
screen.fill((0, 0, 0))
"""try:
assert player.colliderect(wall1)
except AssertionError:
pass
except NameError:
pass
else:
death_screen = pygame.display.set_mode((400, 300))
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (200, 200, 30, 30))
if donk:
break"""
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
if player.colliderect(wall1):
death_screen = pygame.display.set_mode((400, 300))
myfont = pygame.font.SysFont("Comic Sans MS", 10)
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if donk:
screen = pygame.display.set_mode((400, 300))
clock.tick(60)
pygame.display.flip()
quit()
Add a gameover to your application:
gameover = False:
Do different things in the application loop, dependent on the state of gameover:
while not done:
# [...]
if not gameover:
# draw game scene
# [...]
else:
# draw gamover scene (button)
# [...]
Set the gameover state if the player collides:
gameover = player.colliderect(wall1)
Reset the position of the player if the continue button is pressed:
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
See the example:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Auto Maze!")
pygame.font.init()
myfont = pygame.font.SysFont("Comic Sans MS", 10)
x, y = 100, 100
gameover = False
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
screen.fill((0, 0, 0))
if not gameover:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
gameover = player.colliderect(wall1)
else:
button1 = pygame.draw.rect(screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
pygame.display.flip()
clock.tick(60)
quit()
This does the same as your code, but just cleaned up. Hopefully it solves your problem
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
mouse = None
click = False
state = "main"
myfont = pygame.font.SysFont("Comic Sans MS", 10)
player = pygame.Rect(100,100,60,60)
wall1 = pygame.Rect(300, 0, 100, 300)
button1 = pygame.Rect(175, 100, 60, 30)
pygame.display.set_caption("Auto Maze!")
while not done:
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
click = True
screen.fill((0, 0, 0))
if state == "main":
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
player.y -= 5
elif pressed[pygame.K_s]:
player.y += 5
elif pressed[pygame.K_a]:
player.x -= 5
elif pressed[pygame.K_d]:
player.x += 5
#draw player and wall
pygame.draw.rect(screen, (0, 255, 0), player)
pygame.draw.rect(screen, (255, 0, 0), wall1)
if player.colliderect(wall1):
state = "death"
else:
pygame.draw.rect(screen, (0, 0, 255), button1)
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if click:
if button1.collidepoint(mouse):
state = "main"
player.x = 100
player.y = 100
clock.tick(60)
pygame.display.flip()
quit()
This is the code I have started to use to make a start menu.
# we need some colours!!
black = (0,0,0)
white = (255,255,200)
red = (200,0,0)
green = (0, 200, 0)
bright_red = (255, 0 ,0)
bright_green = (0, 255, 0)
bright_white = (255, 255, 255)
def main():
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("CrazyPongMainMenu")
menu = cMenu(50, 50, 20, 5, "vertical", 100, screen,
[("Start Game", 1, None),
("Options", 2, None),
("Exit", 3, None)])
menu.set_center(True, True)
menu.set_alignment("center", "center")
state = 0
prev_state = 1
rect_list = []
pygame.event.set_blocked(pygame.MOUSEMOTION)
while 1:
if prev_state != state:
pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key = 0))
prev_state = state
e = pygame.event.wait()
if e.type == pygame.KEYDOWN or e.type == EVENT_CHANGE_STATE:
if state == 0:
rect_list, state = menu.update(e, state)
elif state == 1:
print ("Start Game!")
state = 0
elif state == 2:
print ("Options!")
state = 0
else:
print ("Exit!")
pygame.quit()
sys.exit()
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
mouse = pygame.mouse.get_pos()
#print(mouse)
if 200+150 > mouse[0] > 200 and 250+30 > mouse[1] > 250:
pygame.draw.rect(screen, bright_green,(200, 250, 150, 30))
else:
pygame.draw.rect(screen, green,(200, 250, 150, 30))
if 200+150 > mouse[0] > 200 and 290+21 > mouse[1] > 290:
pygame.draw.rect(screen, bright_white,(200, 290, 150, 21))
else:
pygame.draw.rect(screen, white,(200, 290, 150, 21))
if 200+150 > mouse[0] > 200 and 318+25 > mouse[1] > 318:
pygame.draw.rect(screen, bright_red,(200, 318, 150, 25))
else:
pygame.draw.rect(screen, red,(200, 318, 150, 25))
pygame.display.update(rect_list)
if __name__ == ("__main__"):
main()
I would like to put text onto the 3 rectangles but i don't know how to. If anybody could please tell my how to put the text onto the rectangles it will be much appreciated!
Check out this stack overflow question:
How to add text into a pygame rectangle
Specifically these bits:
self.font = pygame.font.SysFont('Arial', 25)
def addText(self):
self.screen.blit(self.font.render('Hello!', True, (255,0,0)), (200, 100))
pygame.display.update()
Basically you want to define a font
Then blit it onto the screen, where render takes the args (text, antialias (you want true), color)
and finally update