Main menu help (pygame) - python

I have created mouse clicking functions to print (start, options and about) when I click those buttons. I just don't know how to go to the next stage of actually opening a new page once clicking those buttons. I had a go with trying to screen.fill when clicking the button but it would only last a couple of seconds and buttons would appear in front of it.
I am fairly new to pygame.
Here is my code so far,
import pygame
from pygame import *
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
HOVER_COLOR = (50, 70, 90)
#Background Music
pygame.mixer.music.load('game.ogg')
pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
pygame.mixer.music.play()
pygame.display.update()
clock.tick(15)
#Background
bg = pygame.image.load("greybackground.png")
#Fonts
FONT = pygame.font.SysFont ("Times New Norman", 60)
text1 = FONT.render("START", True, WHITE)
text2 = FONT.render("OPTIONS", True, WHITE)
text3 = FONT.render("ABOUT", True, WHITE)
#Buttons
rect1 = pygame.Rect(300,300,205,80)
rect2 = pygame.Rect(300,400,205,80)
rect3 = pygame.Rect(300,500,205,80)
buttons = [
[text1, rect1, BLACK],
[text2, rect2, BLACK],
[text3, rect3, BLACK],
]
running = False
def game_intro():
while not running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
elif event.type == pygame.MOUSEMOTION:
for button in buttons:
if button[1].collidepoint(event.pos):
button[2] = HOVER_COLOR
else:
button[2] = BLACK
screen.blit(bg, (0, 0))
for text, rect, color in buttons:
pygame.draw.rect(screen, color, rect)
screen.blit(text, rect)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if rect1.collidepoint(event.pos):
screen.fill((0, 0, 0))
elif rect2.collidepoint(event.pos):
print ('options')
elif rect3.collidepoint(event.pos):
print ('about')
if event.type == KEYDOWN:
if (event.key == K_UP):
print ("UP was pressed")
elif (event.key == K_DOWN):
print ("DOWN was pressed")
elif (event.key == K_w):
print ("W was pressed")
elif (event.key == K_s):
print ("S was pressed")
else:
print ("error")
pygame.display.flip()
clock.tick(60)
game_intro()
pygame.quit()

I actually had to do a similar thing myself. This is what you would put at the bottom:
while running:
event = pygame.event.wait()
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
x,y = pygame.mouse.get_pos()
if 300 <= x <= 505 and 300 <= y <= 380:
#change stuff here
running = False
#insert code here \/ for the next screen
This can be used universally for every button. If you need more buttons, just copy and paste the third if statment and change as needed.
Don't forget to do 'pygame.display.update()' to refresh the screen; else, you will see nothing change (which is what happened to me).
I hope this helps!

Related

Why the formated variable is not being updated on the screen and how to fix it

The key space adds +2 to the variable player.mana, when pressed i see the variable incrementing on the console, but the formated string text on the screen don't. How to show it correctly on the screen?
import pygame
import sys
pygame.init()
clock = pygame.time.Clock()
font = pygame.font.SysFont('Arial', 30)
screen = pygame.display.set_mode((640, 480))
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
class Players:
def __init__(self, mana):
self.mana = mana
player = Players(0)
text_player_mana = font.render(f'Mana: {player.mana}', True, WHITE)
running = True
while running:
screen.fill(BLACK)
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if event.type == pygame.KEYDOWN:
if keys[pygame.K_ESCAPE]:
running = False
if keys[pygame.K_SPACE]:
player.mana += 2
screen.blit(text_player_mana, (200, 200))
print(player.mana)
pygame.display.update()
pygame.quit()
sys.exit()
The variable and the rendered Surface are not tied. The Surface does not magically change when you change the variable. You need to re-render the Surface when the variable changes:
text_player_mana = font.render(f'Mana: {player.mana}', True, WHITE)
running = True
while running:
screen.fill(BLACK)
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if event.type == pygame.KEYDOWN:
if keys[pygame.K_ESCAPE]:
running = False
if keys[pygame.K_SPACE]:
player.mana += 2
# player.mana has changed, so text_player_mana needs to be rendered
text_player_mana = font.render(f'Mana: {player.mana}', True, WHITE)
screen.blit(text_player_mana, (200, 200))
print(player.mana)
pygame.display.update()

Fixing an error where the code goes unresponsive after one cycle

I'm trying to have the for loop run 5 iterations of the code below it but once it runs once and i try to click the rectangle the code goes unresponsive.
I can't see why this is happening so i'm looking for some help.
def Reaction_game():
intro = True
while intro == True:
for event in pygame.event.get():
#Stops game when close is selected
if event.type == pygame.QUIT:
file=open('currentuser.txt', 'w')
file.close()
pygame.quit()
quit()
Reaction_times=[]
for x in range (5):
clicked = False
BackGround = Background("background1.png",[0,0])
screen.fill(white)
screen.blit(BackGround.image, BackGround.rect)
pygame.draw.rect(screen, black,(0,0,1000,55))
Font = pygame.font.SysFont('TitilliumWeb.ttf',72)
Label = Font.render("Get Ready:", 1, white)
screen.blit(Label, (380,0,325,75))
pygame.display.update()
time.sleep(2)
screen.blit(BackGround.image, BackGround.rect)
pygame.draw.rect(screen, black,(0,0,1000,55))
Font = pygame.font.SysFont('TitilliumWeb.ttf',72)
Label = Font.render("Go:", 1, white)
screen.blit(Label, (450,0,325,75))
pygame.display.update()
RectX = randrange(50,950)
RectY = randrange(60,513)
round_rect(screen,(RectX,RectY,75,40),(black),10,5,(white))
pygame.display.update()
TimeStart = time.time()
while clicked !=True:
mouse = pygame.mouse.get_pos()
if RectX+75 > mouse[0] > RectX and RectY+40 > mouse[1] > RectY:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
TimeEnd = time.time()
ReactionTime = TimeEnd - TimeStart
Reaction_times.append(ReactionTime)
clicked = True
else:
pass
Reaction_game()
I expect the code to run 5 iterations of this little reaction time game but it doesn't even get past the first loop before going unresponsive.
You have to use for event in pygame.event.get(): inside while clicked to get new events from system. Without this you have the same values in event.type and even.button.
Even pygame.mouse.get_pos() can't work correclty because it uses data created by pygame.event.get() (or similar)
If you have event MOUSEBUTTONDOWN, MOUSEBUTTONUP then you have mouse position in event.pos and you don't need pygame.mouse.get_pos()
while not clicked:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if RectX+75 > event.pos[0] > RectX and RectY+40 > event.pos[1] > RectY:
TimeEnd = time.time()
ReactionTime = TimeEnd - TimeStart
Reaction_times.append(ReactionTime)
clicked = True
EDIT:
You can keep Rectangle position and size in pygame.Rect()
RectX = randrange(50,950)
RectY = randrange(60,513)
rect = pygame.Rect(RectX, RectY, 75, 40)
and then you can use rect instead of (RectX,RectY,75,40)
round_rect(screen, rect, black , 10, 5, white)
and you can use rect to check if you clicked in rectangle rect.collidepoint(event.pos)
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if rect.collidepoint(event.pos):
TimeEnd = time.time()
ReactionTime = TimeEnd - TimeStart
Reaction_times.append(ReactionTime)
clicked = True
EDIT: working example with other changes - ie. I use pygame.time.wait() instead of time.sleep() and pygame.time.get_ticks() instead of time.time(). Both use miliseconds instead of seconds.
import pygame
import random
# --- constants ---
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
# --- main ---
pygame.init()
screen = pygame.display.set_mode((1000, 600))
reaction_times= []
for x in range(5):
clicked = False
screen.fill(WHITE)
pygame.draw.rect(screen, BLACK, (0, 0, 1000, 55))
font = pygame.font.SysFont(None, 72)
label = font.render("Get Ready:", 1, WHITE)
screen.blit(label, (380, 0, 325, 75))
pygame.display.update()
pygame.time.wait(2000) # 2000ms = 2s
pygame.draw.rect(screen, BLACK, (0, 0, 1000, 55))
font = pygame.font.SysFont(None, 72)
label = font.render("Go:", 1, WHITE)
screen.blit(label, (450, 0, 325, 75))
pygame.display.update()
x = random.randrange(50, 950)
y = random.randrange(60, 513)
rect = pygame.Rect(x, y, 75, 40)
pygame.draw.rect(screen, BLACK, rect)
pygame.display.update()
time_start = pygame.time.get_ticks()
while not clicked:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if rect.collidepoint(event.pos):
print('clicked')
time_end = pygame.time.get_ticks()
reaction_time = (time_end - time_start)/1000 # convert to seconds
reaction_times.append(reaction_time)
clicked = True
print(reaction_times)
pygame.quit()

Moving scalable rectangle with mouse in pygame

I'm trying to move a rectangle inside of pygame, and making it scalable.
The scalable rectangle code is something like this then I tried to add an event like this:
from pygame imports *
init()
rect1 = (rect1x, rect1y, 300,300)
rect1x = 0
rect1y = 0
while running:
x,y = mouse.get_pos()
if rect1Pressed == True:
rect1x = x
rect1y = y
for evnt in event.get():
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN:
if evnt.button == 1:
if rect1.collidepoint(mouse.get_pos()):
rect1Pressed == True
How would i incorporate the scalable rectangle and being able to make it move with the mouse? So that the window will follow the mouse motion. So it kinda is like a on your laptop where your able to scale the window and also move it around.
You could check which mouse button is pressed in the elif event.type == pg.MOUSEMOTION: block, e.g. if event.buttons[0]:, and then either move or scale the rect depending on the button. To move the rect, just add the event.rel to the rect.x and rect.y attributes.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect1 = pg.Rect(100, 100, 161, 100)
rect2 = pg.Rect(300, 200, 161, 100)
selected_rect = None
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
for rect in (rect1, rect2):
if rect.collidepoint(event.pos):
selected_rect = rect # Select the colliding rect.
elif event.type == pg.MOUSEBUTTONUP:
selected_rect = None # De-select the rect.
elif event.type == pg.MOUSEMOTION:
if selected_rect is not None: # If a rect is selected.
if event.buttons[0]: # Left mouse button is down.
# Move the rect.
selected_rect.x += event.rel[0]
selected_rect.y += event.rel[1]
else: # Right or middle mouse button.
# Scale the rect.
selected_rect.w += event.rel[0]
selected_rect.h += event.rel[1]
selected_rect.w = max(selected_rect.w, 10)
selected_rect.h = max(selected_rect.h, 10)
screen.fill((30, 30, 30))
pg.draw.rect(screen, (0, 100, 250), rect1)
pg.draw.rect(screen, (0, 200, 120), rect2)
pg.display.flip()
clock.tick(30)

On-screen typing in Pygame

For a programming project in school I have to create a spelling game using pygame. However, as I am fairly new to this whole thing, I can't manage to work out how to allow the user to input letters and make them appear on the game display. This is my code so far (along with my failing attempt at solving this problem):
import pygame
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Spelling Game")
myfont = pygame.font.SysFont("Arial", 50)
clock = pygame.time.Clock()
mouse = pygame.mouse.get_pos()
city = pygame.image.load("city.png")
charac_str = "" #new string to store written character
# font object to render str to surface
font_renderer = pygame.font.SysFont("Arial",30)
def background(x,y):
gameDisplay.blit(city,(-200,-100))
with open("words.txt") as f:
WORDS = f.read().split()
def random_word():
return random.choice(WORDS)
gameExit = False
word = random_word()
while not gameExit:
#event-handling loop based on user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
background(0,0)
textsurface = myfont.render(word, True, red)
gameDisplay.blit(textsurface, (340, 400)) #the random word
rendered_charac = font_renderer.render(charac_str, True, red)
gameDisplay.blit(rendered_charac, (100,100))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if pygame.K_0 < event.key < pygame.K_9: #checks key pressed
character = chr(event.key) #conv num to char
charac_str += str(character) # add num to end of string
gameDisplay.blit(charac_str) # display the input?doesn't work
pygame.KEYDOWN events have a unicode attribute which you can simply add to a string, e.g. text += event.unicode. Then the text is rendered and displayed in the main loop.
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
font = pg.font.Font(None, 32)
clock = pg.time.Clock()
color = pg.Color('dodgerblue2')
text = ''
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
elif event.type == pg.KEYDOWN:
if event.key == pg.K_RETURN:
print(text)
text = ''
elif event.key == pg.K_BACKSPACE:
text = text[:-1]
else:
text += event.unicode
screen.fill((30, 30, 30))
txt_surface = font.render(text, True, color)
screen.blit(txt_surface, (50, 100))
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
This is how you 're going to solve your little problem:
def name():
pygame.init()
screen = pygame.display.set_mode((480, 360))
name = ""
font = pygame.font.Font(None, 50)
while True:
for evt in pygame.event.get():
if evt.type == KEYDOWN:
if evt.unicode.isalpha():
name += evt.unicode
elif evt.key == K_BACKSPACE:
name = name[:-1]
elif evt.key == K_RETURN:
name = ""
elif evt.type == QUIT:
return
screen.fill ((0, 0, 0))
block = font.render(name, True, (255, 255, 255))
rect = block.get_rect()
rect.center = screen.get_rect().center
screen.blit(block, rect)
pygame.display.flip()

How to update my score?

My program works fine but I can't update the score. This is for my project; I am on the last part and cant figure it out myself. I pasted the whole code for reference.
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
betmoney = 100
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()
def menu():
done = True
while done:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
tracks()
elif event.key == pygame.K_F1:
about()
elif event.type == pygame.QUIT:
pygame.quit()
game_S.blit(bg, [0,0])
for i in range (30):
x = random.randrange(0, 700)
y = random.randrange(0, 700)
pygame.draw.circle(game_S, GREEN, [x,y], 5)
pygame.display.update()
game_S.blit(text, [170, 450])
pygame.display.flip()
game_S.blit(betm, [0,0])
pygame.display.flip()
clock.tick(10)
def win():
while True:
game_S.blit(winner, [0,0])
game_S.blit(text, [170, 450])
game_S.blit(betm, [0, 0])
pygame.display.flip()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
menu()
elif event.type == pygame.QUIT:
pygame.quit()
clock.tick(10)
def loser():
while True:
game_S.blit(lose, [0,0])
game_S.blit(text, [170, 450])
pygame.display.flip()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
menu()
elif event.type == pygame.QUIT:
pygame.quit()
clock.tick(10)
def tracks ():
pygame.time.wait(1000)
game_S.blit(track3, [0,0])
pygame.display.update()
pygame.time.wait(1000)
game_S.blit(track2, [0,0])
pygame.display.update()
pygame.time.wait(1000)
game_S.blit(track1, [0,0])
pygame.display.update()
pygame.time.wait(1000)
game_S.blit(trackgo, [0,0])
pygame.display.update()
pygame.time.wait(1000)
game_S.fill(WHITE)
game_S.blit(track, [0,0])
pygame.display.update()
game_S.blit(bet, [0, 230])
game_S.blit(en1, [0, 20])
game_S.blit(en2, [0, 80])
game_S.blit(en3, [0, 160])
game_S.blit(en4, [0, 295])
game_S.blit(en5, [0, 360])
game_S.blit(en6, [0, 440])
pygame.display.update
pygame.display.flip()
r1 = random.randrange(1,10)
r2 = random.randrange(1,10)
r3 = random.randrange(1,10)
r4 = random.randrange(1,10)
r5 = random.randrange(1,10)
r6 = random.randrange(1,10)
racemode(r1,r2,r3,r4,r5,r6,0)
def racemode(a,b,c,d,e,f,wow):
move = True
while move:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and wow <= 600:
game_S.blit(bet, [wow, 230])
wow +=5
pygame.display.update()
clock.tick(10)
continue
elif event.type == pygame.QUIT:
pygame.quit()
if a<= 600:
game_S.blit(en1, [a,20])
a += random.randrange(10,15)
pygame.display.update()
clock.tick(30)
if b<= 600:
game_S.blit(en2, [b,80])
b +=random.randrange(10,15)
pygame.display.update()
clock.tick(30)
if c<= 600:
game_S.blit(en3, [c,160])
c += random.randrange(10,15)
pygame.display.update()
clock.tick(30)
if d<= 600:
game_S.blit(en4, [d,295])
d+= random.randrange(10,15)
pygame.display.update()
clock.tick(30)
if e<= 600:
game_S.blit(en5, [e,360])
e+= random.randrange(10,15)
pygame.display.update()
clock.tick(30)
if f<=600:
game_S.blit(en6, [f,440])
f+=random.randrange(10,15)
pygame.display.update()
clock.tick(30)
if wow >= 600 and a <600 and b <600 and c<600 and d<600 and e<600 and f<600:
win()
elif wow < 600 and a>= 600 or b>=600 or c>= 600 or d >= 600 or e >= 600 or f >=600:
loser()
def about():
tan = True
game_S.fill(WHITE)
game_S.blit(ab, [0,0])
pygame.display.update()
texts = pygame.font.SysFont('Arial', 35, True, False)
fonts = pygame.font.SysFont('Calibri', 30, True, False)
tput1 = texts.render("ABOUT THE BETTING SYSTEM", True, BLACK)
tput2 = fonts.render("-> You are given $100 as starting money", True, RED)
tput3 = fonts.render("-> You can get +100 if you win" , True, RED)
tput3b = fonts.render("-> You will lose 100 if you lose", True, RED)
tput4 = fonts.render("-> You beat the game when you reach 1000", True, RED)
tput5 = fonts.render("-> GAME OVER if you got $0 money", True, RED)
back = font.render(" PRESS F1 to go Back", True, BLACK)
game_S.blit(tput1, [120,80])
pygame.display.update()
game_S.blit(tput2, [100,150])
pygame.display.update()
game_S.blit(tput3, [100,200])
pygame.display.update()
game_S.blit(tput3b, [100,250])
pygame.display.update()
game_S.blit(tput4, [100,300])
pygame.display.update()
game_S.blit(tput5, [100,350])
pygame.display.update()
while tan:
game_S.blit(back, [170,450])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_F1:
menu()
elif event.type == pygame.QUIT:
pygame.quit()
clock.tick(10)
# Set the width and height of the screen [width, height]
size = (700, 500)
game_S = pygame.display.set_mode(size)
pygame.display.set_caption("BET ON YOUR TURTLE")
font = pygame.font.SysFont('Calibri', 34, True, False)
text = font.render("PRESS ENTER TO CONTINUE", True, RED)
betm = font.render(str(betmoney), 1, RED)
#---IMAGES----
bg = pygame.image.load("kim.png")
ab = pygame.image.load("waw.png")
bet = pygame.image.load("witwew.png").convert_alpha()
en1 = pygame.image.load("enemy1.png")
en2 = pygame.image.load("enemy2.png")
en3 = pygame.image.load("enemy3.png")
en4 = pygame.image.load("enemy4.png")
en5 = pygame.image.load("enemy5.png")
en6 = pygame.image.load("enemy6.png")
track = pygame.image.load("TRACK.png")
track3 = pygame.image.load("TRACK3.png")
track2 = pygame.image.load("TRACK2.png")
track1 = pygame.image.load("TRACK1.png")
trackgo = pygame.image.load("TRACKGO.png")
winner = pygame.image.load("winner.png")
lose = pygame.image.load("lose.png")
#--IMAGES (end)--
pygame.mixer.music.load("icecream_8bit.mp3")
pygame.mixer.music.play(-1)
menu()
You can see that I put betmoney as local variable with 100 value and don't know how to add 100 or deduct 100.
There are two ways to go about accessing the "betmoney" variable that come to mind. Firstly, simply pass it into the function that you plan on accessing it as an argument. This is generally the preferred way. Second, simply declare "betmoney" a global variable and it can be accessed from anywhere.

Categories

Resources