I'm having some trouble while trying to quit from a function that I made. It just doesn't seem to break the loop. The game opens and I can play around but I can't quit, It just stays there without doing anything and the icon on the task bar goes full yellow.
Here's my code:
import pygame, os, sys, math
black = (0,0,0)
white = (255,255,255)
grey = (128, 128, 128)
gameDisplay = pygame.display.set_mode((800,600))
def game_menu():
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
pygame.display.set_caption(".")
menu = True
events = pygame.event.get()
while menu:
for event in events:
if event.type == pygame.QUIT:
menu = False
pygame.quit()
quit()
DISPLAYSURF = pygame.display.set_mode((800, 600))
DISPLAYSURF.fill(black)
font = pygame.font.Font('MATRIX.ttf',60)
TextSurf, TextRect = text_objects("MATRIX PASA PALABRA", font,white)
TextRect.center = ((600/2),(50))
gameDisplay.blit(TextSurf, TextRect)
#Jugar
button("Jugar",300,200,200,50,None)
button("Instrucciones",300,275,200,50,None)
button("Dificultad",300,350,200,50,None)
button("Salir",300,425,200,50,None)
pygame.display.update()
def text_objects(text, font,color):
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,action=None):
mouse = pygame.mouse.get_pos()
events = pygame.event.get()
if x+w> mouse[0] > (x) and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay,grey,(x,y,w,h))
for event in events:
if event.type ==pygame.MOUSEBUTTONUP and msg=="Salir":
pygame.quit()
quit()
elif event.type==pygame.MOUSEBUTTONUP and msg=="Jugar":
None
else:
pygame.draw.rect(gameDisplay,white,(x,y,w,h))
smalltext= pygame.font.Font("MATRIX.ttf",30)
textsrf,textrct=text_objects(msg,smalltext,black)
textrct.center = ((x+(w/2)),(y+(h/2)))
gameDisplay.blit(textsrf,textrct)
if __name__ == "__main__":
game_menu()
Thanks and sorry for my bad english.
The reason why it doesn't work is that you call pygame.event.get multiple times per frame. The event queue will be emptied after the first call, so the events won't get processed correctly. There should be only one pygame.event.get call per frame.
To fix this problem, you can assign the list of events that pygame.event.get returns to a variable in the main while loop and then pass it to the button function.
while menu:
events = pygame.event.get()
for event in events:
# etc.
button("Jugar",300,200,200,50,events,None)
Add an events parameter to the button function:
def button(msg,x,y,w,h,events,action=None):
mouse = pygame.mouse.get_pos()
if x+w> mouse[0] > (x) and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay,grey,(x,y,w,h))
for event in events:
# etc.
BTW, this button function keeps popping up here again and again, probably because it's a really bad way to implement buttons. I'd recommend a solution similiar to one of these: https://stackoverflow.com/a/47664205/6220679 or search for pygame GUI toolkits (SGC is pretty good).
The others have already mentioned that the indentation in your example is wrong and that sys.exit is a better way to quit than the quit function.
Here's a fixed, complete example:
import pygame, os, sys, math
black = (0,0,0)
white = (255,255,255)
grey = (128, 128, 128)
gameDisplay = pygame.display.set_mode((800,600))
def game_menu():
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
pygame.display.set_caption(".")
DISPLAYSURF = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
menu = True
while menu:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
menu = False
pygame.quit()
sys.exit()
DISPLAYSURF.fill((30, 30, 30))
font = pygame.font.Font(None,60)
TextSurf, TextRect = text_objects("MATRIX PASA PALABRA", font,white)
TextRect.center = ((600/2),(50))
gameDisplay.blit(TextSurf, TextRect)
#Jugar
button("Jugar",300,200,200,50,events,None)
button("Instrucciones",300,275,200,50,events,None)
button("Dificultad",300,350,200,50,events,None)
button("Salir",300,425,200,50,events,None)
pygame.display.update()
clock.tick(60)
def text_objects(text, font,color):
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,events,action=None):
mouse = pygame.mouse.get_pos()
if x+w> mouse[0] > (x) and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay,grey,(x,y,w,h))
for event in events:
if event.type ==pygame.MOUSEBUTTONUP and msg=="Salir":
pygame.quit()
sys.exit()
elif event.type==pygame.MOUSEBUTTONUP and msg=="Jugar":
print("jugar")
else:
pygame.draw.rect(gameDisplay,white,(x,y,w,h))
smalltext= pygame.font.Font(None,30)
textsrf,textrct=text_objects(msg,smalltext,black)
textrct.center = ((x+(w/2)),(y+(h/2)))
gameDisplay.blit(textsrf,textrct)
if __name__ == "__main__":
game_menu()
If you import sys then you can use that to exit your code.
import sys
def game_menu():
menu = True
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
Try adding pygame.display.quit() before the line pygame.quit(). This should close any open displays.
Edit:
The problem is that most of your program isn't inside the while loop. Most importantly, the events = pygame.event.get() isn't inside the while loop so the events are never updated.
Rearranging the code to something like this should work:
def game_menu():
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
pygame.display.set_caption(".")
menu = True
while menu:
events = pygame.event.get()
DISPLAYSURF = pygame.display.set_mode((800, 600))
DISPLAYSURF.fill(black)
font = pygame.font.Font('MATRIX.ttf',60)
TextSurf, TextRect = text_objects("MATRIX PASA PALABRA", font,white)
TextRect.center = ((600/2),(50))
gameDisplay.blit(TextSurf, TextRect)
#Jugar
button("Jugar",300,200,200,50,None)
button("Instrucciones",300,275,200,50,None)
button("Dificultad",300,350,200,50,None)
button("Salir",300,425,200,50,None)
pygame.display.update()
for event in events:
if event.type == pygame.QUIT:
menu = False
pygame.quit()
quit()
Related
I made an endscreen when ever my player health reaches -1 it loads the end screen but here is the problem Video it wont restart the game and I have to hold the start game to show my main game
my end screen def my point is how could I make it restart my game to the start not just blit the game where I was
#------------------------------------------------------
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def endScreen():
red = (200,0,0)
green = (0,200,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
largeText = pygame.font.Font('BLOODY.ttf',81)
TextSurf, TextRect = text_objects("You Have Died Fool", largeText)
TextRect.center = ((800/2), (800/2))
window.blit(TextSurf, TextRect)
button("Start Game",150,450,100,50,green,bright_green,game_loop)
# make the square brighter if collideded with the buttons
mouse = pygame.mouse.get_pos()
if 150+120 > mouse[0] > 150 and 450+50 > mouse[1] > 450:
pygame.draw.rect(window, bright_green,(150,450,120,50))
else:
pygame.draw.rect(window, green,(150,450,120,50))
if 550+110 > mouse[0] > 550 and 450+50 > mouse[1] > 450:
pygame.draw.rect(window, bright_red,(550,450,110,50))
else:
pygame.draw.rect(window, red,(550,450,110,50))
# ---------------------------------------------------------------------
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects("Start Game", smallText)
textRect.center = ( (150+(120/2)), (450+(50/2)) )
window.blit(textSurf, textRect)
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects("Quit Game", smallText)
textRect.center = ( (150+(910/2)), (450+(50/2)) )
window.blit(textSurf, textRect)
pygame.display.update()
clock.tick(15)
#----------------------------------------------------------
here is what I did in my main loop
when my player health reaches 0 it shows the end screen
def game_loop():
# coin scoring
font = pygame.font.Font('times.ttf',29)
score = 0
text = font.render("Hearts = " + str(score), True, (255,255,255))
textRect = text.get_rect()
textRect.center = ((80,70))
shootsright = []
bullets = []
bulls = []
bullss = []
bullsss = []
bullssss = []
runninggame = True
while runninggame:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
runninggame = False
if playerman.health < -5:
endScreen()
The problem is that all of your game loop variables have been saved so when you restart you still have all the variables set to what they when you died.
So what you will need to do is put everything in one giant while loop. For example:
import ...
quit = False
while not quit:
# all of your code goes here
But once you do this you must change the pygame.QUIT if statement in your game loop as follows:
if event.type == pygame.QUIT:
runninggame = False
|
V
if event.type == pygame.QUIT:
sys.exit()
and the same goes for the pygame.QUIT at the top of your endScreen function.
Change 1: The next thing that must be changed is exiting the game loop function. This can be done by modifying one of the button functions to return a bool stating whether or not the restart button was clicked. From there that value can be passed onto the game loop function and if the button is pressed the while loop in the function will be broken out of causing everything in the while loop to rerun.
Explanation: Currently, the problem is that you never exit the loop meaning when you click the retry button you just start right back from where you let off. Instead, you need to redefine all your variables which is why all the code needs to be in a while loop (you can actually leave out the functions all that needs to be in the while loop are the global variables, but it is not necessary to move the functions out).
Change 2 (minor changes): Sys needs to be imported at the top of the script and the pygame.quit() function at the end of the script needs to be deleted.
Explanation: Sys is imported so that sys.exit can be run which allows the program to be terminated once the window is closed out. The pygame.quit() is deleted because running that will uninitialized pygame and that would prevent you from using any pygame functions after you have pressed the retry button. And this code is no longer necessary since sys.exit() pretty much just takes care of all that for you.
And a minor note: enemys should actually be enemies (it would look bad if you had the word enemies spelled incorrectly in your code and you put it up on GitHub) so I recommend just doing a quick replace all.
So this is my code :
import pygame
import pygame as pg
pygame.init()
displayWidth = 800
displayHeight = 600
### colour codes ###
bgColour = (245, 230, 255)
grey = (150, 150, 150)
darkGrey = (100, 100, 100)
darkBlack = (0,0,0)
clock = pygame.time.Clock()
mouse_clicked = False
display = pygame.display.set_mode((displayWidth, displayHeight))#sets height and width of screen
pygame.display.set_caption('Fashion!')
def screenDisplay(): #subroutine to display screens
display = pygame.display.set_mode((displayWidth, displayHeight))#sets height and width of screen
pygame.display.set_caption('Fashion!') #sets screen title
display.fill(bgColour)
def text_objects(text, font): #font colour
textSurface = font.render(text, True, darkBlack)
return textSurface, textSurface.get_rect()
def textDisplay(s,t,x,y): #subroutine for displaying text on screen
smallText = pygame.font.SysFont("",s) #creates front and font size
textSurf, textRect = text_objects(t, smallText) #inputs text
textRect.center = (x,y) #centres text
display.blit(textSurf, textRect) #displays test
def button(msg,s,x,y,w,h,ic,ac,action=None): #format for button
mouse = pygame.mouse.get_pos() #gets mouse position (tracks cursor)
click = pygame.mouse.get_pressed() #gets status of mouse (tracks click)
print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y: #draws rectangle for button
pygame.draw.rect(display, ac,(x,y,w,h)) #draws rectangle after colour if mouse is on area
if click[0] == 1 and action != None: #performs function on click
action()
else:
pygame.draw.rect(display,ic,(x,y,w,h)) #draws rectangle initial colour if mouse isnt on area
smallText = pygame.font.SysFont("",s) #adds text to button
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
display.blit(textSurf, textRect)
smallText = pygame.font.SysFont("",s) #adds text to button
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
display.blit(textSurf, textRect)
def menuDisplay():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screenDisplay()
button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
button("OUTFIT", 60,200,250,400,100,grey,darkGrey,page)
button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
button("QUIT", 40,300,530,200,50,grey,darkGrey,page)
pygame.display.update()
clock.tick(30)
def page():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screenDisplay()
pygame.display.update()
clock.tick(30)
menuDisplay()
It prints the get pressed but it only returns [0,0,0] until at random times (sometimes straight away sometimes after 10 clicks sometimes after like 50 clicks) it registers [1,0,0]. it has never worked even on other computers.
It didn't work when I didnt have a clock either so like that didnt change anything.
I am so sad and stressed please help ππ
The issue is the call to pygame.display.set_mode in screenDisplay. Note, pygame.display.set_mode reinitialize the window and causes losing all mouse event states.
screenDisplay is called in the main application loop. It is a wast of performance and bad style to initialize the display in every frame.
Do not call screenDisplay in the main application loop, just clear the display by display.fill(bgColour) to solve the issue:
def menuDisplay():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# screenDisplay() <-- DELETE
display.fill(bgColour)
button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
button("OUTFIT", 60,200,250,400,100,grey,darkGrey,page)
button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
button("QUIT", 40,300,530,200,50,grey,darkGrey,page)
pygame.display.update()
clock.tick(30)
Do the same in page()
def page():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# screenDisplay() <-- DELETE
display.fill(bgColour)
pygame.display.update()
clock.tick(30)
I changed some things and this works:
import pygame
pygame.init()
displayWidth = 800
displayHeight = 600
### colour codes ###
bgColour = (245, 230, 255)
grey = (150, 150, 150)
darkGrey = (100, 100, 100)
darkBlack = (0,0,0)
smallText = pygame.font.SysFont("",32)
display = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Fashion!')
def text_objects(text, font): #font colour
textSurface = font.render(text, True, darkBlack)
return textSurface, textSurface.get_rect()
def button(msg,s,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(display, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(display, ic,(x,y,w,h))
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
display.blit(textSurf, textRect)
def menuDisplay():
display.fill(bgColour)
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
button("WARDROBE",60,200,100,400,100,grey,darkGrey,page)
button("OUTFIT", 60,200,250,400,100,grey,darkGrey,page)
button("SHOPPING",60,200,400,400,100,grey,darkGrey,page)
button("QUIT", 40,300,530,200,50,grey,darkGrey,page)
pygame.display.update()
def page():
display.fill(bgColour)
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.draw.rect(display,grey,(50,50,50,50) )
pygame.display.update()
menuDisplay()
(English isnβt my first language, so please excuse any mistakes.)
(Thanks for everyone!!)
When I click the button"1", BE01 will appear but if I don't click, scene01Img will return.
I tried use gameExit = true in def BE01():, but it doesn't work.
pygame.init()
clock = pygame.time.Clock()
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 BE01():
gameDisplay.fill(white)
gameDisplay.blit(BE01Img,(0,0))
button("BACK",350,450,100,50,black,gray,game_intro)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(introImg,(0,0))
button("START",350,450,100,50,black,gray,game_loop)
pygame.display.update()
clock.tick(15)
def quitgame():
pygame.quit()
quit()
def game_loop():
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(scene01Img,(0,0))
button("1",200,450,100,50,black,gray,BE01)
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
After click the button"1", BE01 will appear and run the another program, scene01 shouldn't appear.
Every scene should have own loop and when you press button then you should go to new loop.
If you want to change elements in one loop then put old elements in some function (ie. draw_intro) and new elements in other function (ie. draw_other) - at start uses draw_intro in loop and when you press button then replace this function with draw_other
In Python you can assign function name (without ()) to variable
show = print
and later use this name (using ())
show("Hello World")
You can do the same with draw_intro, draw_other.
Inside game loop (before while)you can set
global draw
draw = draw_intro
and use it inside while
draw()
When you press button then it should replace funtion
draw = draw_other
Here full working code - I only removed all blit(image) to run it easily without images.
import pygame
black = (0,0,0)
white = (255,255,255)
gray = (128,128,128)
red = (255,0,0)
pygame.init()
gameDisplay = pygame.display.set_mode( (800,600))
clock = pygame.time.Clock()
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 = smallText.render(msg, True, red)
textRect = textSurf.get_rect()
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def change_draw(new_draw):
global draw
draw = new_draw
def draw_BE01():
gameDisplay.fill(white)
#gameDisplay.blit(BE01Img,(0,0))
button("BACK",350,450,100,50,black,gray,lambda:change_draw(draw_intro))
def draw_intro():
gameDisplay.fill(white)
#gameDisplay.blit(introImg,(0,0))
button("START",350,450,100,50,black,gray,lambda:change_draw(draw_other))
def draw_other():
gameDisplay.fill(white)
#gameDisplay.blit(scene01Img,(0,0))
button("1",200,450,100,50,black,gray,lambda:change_draw(draw_BE01))
def quitgame():
pygame.quit()
quit()
def game_loop():
global draw
draw = draw_intro
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
EDIT:
If you didn't use lamda before then you can do it without lambda but you will need change_draw_to_intro, change_draw_to_other, change_draw_to_BE01 instead of single change_draw
import pygame
black = (0,0,0)
white = (255,255,255)
gray = (128,128,128)
red = (255,0,0)
pygame.init()
gameDisplay = pygame.display.set_mode( (800,600))
clock = pygame.time.Clock()
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 = smallText.render(msg, True, red)
textRect = textSurf.get_rect()
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def change_draw_to_intro():
global draw
draw = draw_intro
def change_draw_to_other():
global draw
draw = draw_other
def change_draw_to_BE01():
global draw
draw = draw_BE01
def draw_BE01():
gameDisplay.fill(white)
#gameDisplay.blit(BE01Img,(0,0))
button("BACK",350,450,100,50,black,gray,change_draw_to_intro)
def draw_intro():
gameDisplay.fill(white)
#gameDisplay.blit(introImg,(0,0))
button("START",350,450,100,50,black,gray,change_draw_to_other)
def draw_other():
gameDisplay.fill(white)
#gameDisplay.blit(scene01Img,(0,0))
button("1",200,450,100,50,black,gray,change_draw_to_BE01)
def quitgame():
pygame.quit()
quit()
def game_loop():
global draw
draw = draw_intro
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
I am just new in pygame, this is my code, pieces. I have main button function, and in gameloop i i successfully create a interactive button, and i don't know exactly, how can i press the button in gameloop ("Start playing") and fill my gameDisplay, for example...white color. Thanks in advance
...........................................................................................................................................................
import pygame,sys
pygame.init()
#############
pygame.mixer.music.load('Invincible.mp3')
pygame.mixer.music.play()
#############
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)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('One Day After')
clock = pygame.time.Clock()
gameIcon = pygame.image.load('gameicon.jpg')
pygame.display.set_icon(gameIcon)
pause = False
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def GameOver():
####################################
pygame.mixer.Sound.play("smb_gameover.wav")
pygame.mixer.music.stop()
####################################
largeText = pygame.font.SysFont("comicsansms",115)
TextSurf, TextRect = text_objects("Game Over", 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:
pygame.mixer.music.stop()
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()
sys.exit()
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():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pilt1 = pygame.image.load('apoc2.jpg').convert()
gameDisplay.blit(pilt1, [0,0])
pygame.display.flip()
button("Start",150,450,100,50,green,bright_green,game_loop)
button("Quit",550,450,100,50,red,bright_red,quitgame)
pygame.display.update()
def game_loop():
global pause
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
quit()
gameDisplay.fill(white)
gameDisplaypic = pygame.image.load('back.jpg').convert()
gameDisplay.blit(gameDisplaypic, [0,0])
tekst = "This game will go as far as you choose!"
meie_font = pygame.font.SysFont("Arial", 36)
teksti_pilt = meie_font.render(tekst, False, (50,50,155))
gameDisplay.blit(teksti_pilt, (100, 250))
tekst2 = "You are the smith of your destiny"
meie_font = pygame.font.SysFont("Arial", 36)
teksti_pilt = meie_font.render(tekst2, False, (50,50,155))
gameDisplay.blit(teksti_pilt, (100, 400))
button("Start playing",300,500,150,50,green,bright_green)
pygame.display.update()
game_intro()
game_loop()
pygame.quit()
quit()
I hope this program will help.
import pygame,sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((400,400))
white=(255,255,255)
blue=(0,0,255)
bright_red = (255,0,0)
red = (200,0,0)
black=(0,0,0)
color=white
def changecolor(newcolor):
global color
color=newcolor
while True:
screen.fill(color)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONUP:
# Whenever somebody clicks on the screen the color
# will change from the initial color to the color
# value you send to the function. Using this you could
# make it specifically for your button. Like calling
# the change color function whenever the button is clicked.
changecolor(blue)
pygame.display.update()
You can use state variables (True/False) to control which element to display and you can change those varibles using button.
In example I have
display_text = True
display_button_1 = True
display_button_2 = False
to control when display text and two buttons.
First button change values and it hides text and first button, and it shows second button.
There is one problem - your button function is ugly and it use get_buttons() so when I hold pressed button and I remove one button and put another in the same place then it automatically click second button. You should use event.type == MOUSEBUTTONUP (as suggest #Hilea) to fix this.
import pygame
import sys # every import in separated line
# --- constants ---
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)
# --- functions ---
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
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:
pygame.mixer.music.stop()
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()
sys.exit()
quit()
def hide_text():
global display_text
global display_button_1
global display_button_2
display_text = False
display_button_1 = False
display_button_2 = True
def game_loop():
global display_text
global display_button_1
global display_button_2
gameExit = False
display_text = True
display_button_1 = True
display_button_2 = False
meie_font = pygame.font.SysFont("Arial", 36)
tekst = "This game will go as far as you choose!"
teksti_pilt = meie_font.render(tekst, False, (50,50,155))
tekst2 = "You are the smith of your destiny"
teksti_pilt = meie_font.render(tekst2, False, (50,50,155))
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
gameDisplay.fill(white)
if display_text:
gameDisplay.blit(teksti_pilt, (100, 250))
gameDisplay.blit(teksti_pilt, (100, 400))
if display_button_1:
button("Start playing", 300,500,150,50,green,bright_green, hide_text)
if display_button_2:
button("Exit", 300,100,150,50,green,bright_green, pygame.quit)
pygame.display.update()
# --- main ---
pygame.init()
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('One Day After')
clock = pygame.time.Clock()
pause = False
game_loop()
pygame.quit()
I have no idea why when the button is pressed it doesnt just go to the next function. It goes back to the other one its really weird and annoying.
It should go to the whattodo function but it does for like half a second then goes to the other. Anyone know why?
#!/usr/bin/python
import pygame
pygame.init()
screen = pygame.display.set_mode((1400,700))
pygame.display.set_caption("Anti-Docter")
titlescreen = pygame.image.load('titleframe.bmp')
boxinfo = pygame.image.load('boxinfo.bmp')
black = (0,0,0)
white = (255,255,255)
randommommycolor = (255,139,12)
Brown = (102,51,0)
Lighter_Brown = (120,59,5)
def mts(text, textcolor, x, y, fs):
font = pygame.font.Font(None,fs)
text = font.render(text, True, textcolor)
screen.blit(text, [x,y])
def buttonPlay(x,y,w,h,ic,ac):
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, ac,(x,y,w,h))
if click[0] == 1:
whattodo()
else:
pygame.draw.rect(screen, ic,(x,y,w,h))
def whattodo():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(boxinfo, (0,0))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(titlescreen, (0,0))
buttonPlay(580, 350, 200, 90, Brown, Lighter_Brown)
mts("Play", black, 620, 365, 80)
pygame.display.update()
Every time your main loop repeats, it calls 'buttonPlay'. There is nothing inside 'whattodo' that changes this behaviour, so 'whattodo' runs once then control flow passes back to the main loop, which just repeats 'buttonPlay'.