Pygame buttons not functioning [duplicate] - python

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How can I add an image or icon to a button rectangle in Pygame?
(1 answer)
Closed 2 years ago.
def button(text, x, y, width, height, inactive_color, active_color,action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#click1 = pygame.MOUSEBUTTONDOWN()
if x + width > cur[0] > x and y+height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x,y,width,height))
if click[0] == 1 and action !=None:
if action == "start": #actions define what each thing does. modify the actions for it to do different things.
game_intro()
pygame.display.update()
if action == "play":
scene1()
pygame.display.update()
if action == "next":
scene1_p2()
pygame.display.update()
if action == "next1":
scene1_p3()
pygame.display.update()
if action == "next2":
scene2()
pygame.display.update()
if action == "next3":
scene2_p2()
pygame.display.update()
else:
x + width > cur[0] > x and y+height > cur[1] > y
pygame.draw.rect(gameDisplay, inactive_color, (x,y,width,height))
text_to_button(text,black,x,y,width,height)
def game_title():
title = True
while title:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(opimg, [0, 0])
message_to_screen("TBN", red, -100, size='large')
pygame.draw.rect(gameDisplay, blue, (380, 500, 230, 50))
text_to_button("Press to Start", red, 450, 500, 100, 50)
mouse = pygame.mouse.get_pos()
#print(mouse)
if 380+230 > mouse[0] > 380 and 500+50 > mouse[1] > 500:
button("Press to Start",380, 500, 230, 50,blue,light_blue,"start")
'''
if event.type == pygame.KEYDOWN:
if event.key == pygame.MOUSEBUTTONDOWN:
title = False
game_intro()
'''
pygame.display.update()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Welcome to TBN", red, -100, size='large')
message_to_screen('This is a story based RPG',
black,
10)
message_to_screen('By Stephen Wang',
black,
50)
message_to_screen('Assets used not owned by me but by their respective owners.',
black,
100)
button("Play", 420, 550, 150, 50, blue, light_blue,action="play")
pygame.display.update()
def scene1():
scene1= True
mouse_click=False
while scene1 == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
button("I can't hear anything...", 0,700 , 1000, 100, blue,blue,action="next")
pygame.display.update()
def scene1_p2():
scene1= True
while scene1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
button("Where am I?", 0,700 , 1000, 100, blue, blue,action="next1")
pygame.display.update()
def scene1_p3():
scene1= True
while scene1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(black)
button("Slowly, I opened my eyes.", 0,700 , 1000, 100, blue, blue,action="next2")
pygame.display.update()
def scene2():
scene2 = True
while scene2:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(forest, [0, 0])
button("Nearby, I could hear the sounds of battle.", 0, 700, 1000, 100, blue, blue, action="next3")
pygame.display.update()
def scene2_p2():
scene2 = True
while scene2:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
gameDisplay.blit(forest, [0, 0])
button("Nearby, I could hear the sounds of battle.", 0, 700, 1000, 100, blue, blue, action="next3")
pygame.display.update()
game_title()
game_intro()
So that is the code that I have. I am currently making a choose your own adventure type game for school. Since I'm still new to Pygame, I don't know how to do the textboxes so I create a new screen for each update. I use the button as a textbox, and when it is pressed, it proceeds to the next screen.
However, when I tried to add more screens in, the buttons just straight up won't function at all. Please help!

Related

go button does not work due to issues in main loop

def game_controls(): # First page of controls #################################
gcont = True
global intro
gameDisplay.fill(white)
while gcont:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_controls1()
message_to_screen("Cystal Caves", green,-100, size="large")
message_to_screen("Created by 'Alan Benoy'", black, 10)
message_to_screen("-- -- -- -- -- Press -C- to continue along screens -- -- -- -- --", yellow, 250)
def game_controls1(): # Page 1 of controls ###################################
gcont1 = True
global intro
gameDisplay.fill(white)
while gcont1:
message_to_screen("Welcome to Crystal Caves!",green,-100,size="large")
message_to_screen("Journey through different caverns and explore the caves mysteries!",black,10)
message_to_screen("Find the caves hidden treasures and become rich!",black,50)
message_to_screen("But BEWARE... Danger lurks around every corner with monster hiding in dark!",black,90)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_controls2()
def game_controls2(): # Page 2 of controls ###################################
gcont2 = True
global intro
gameDisplay.fill(white)
while gcont2:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_controls3()
message_to_screen("Controls:",green,-100,size="large")
message_to_screen("Press the right arrow key to movie right",black,10)
message_to_screen("Press the left arrow key to move left",black,50)
message_to_screen("Press the up arrow key to jump up",black,90)
message_to_screen("Press -E- to exit the game whenever",black,130)
message_to_screen("Press -P- to pause the game",black,170)
message_to_screen("Press -C- to unpause and continue the game",black,210)
message_to_screen("Press -R- to restart the game (to Main Menu)",black,250)
def game_controls3(): # Final page of controls ###############################
gcont3 = True
global intro
gameDisplay.fill(white)
while gcont3:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_intro() # Leads user back to game intro screen
message_to_screen("Now it's Time to Play:",green,-100,size="large")
message_to_screen("Enter the cave to begin your adventure... IF YOU DARE!!!",black,10)
######################## Message to Screen Variables ##########################
def text_objects(text, color,size = "small"):
if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)
pygame.display.update()
########################## Game Intro Buttons #################################
def button(msg,x,y,w,h,ic,ac, action = None ):
global intro
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
#print(mouse)
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":
intro = False
redrawGameWindow()
if click[0] == 1 and action != None:
if action == "controls":
game_controls()
if click[0] == 1 and action != None:
if action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ic,(x, y, w, h))
font = pygame.font.SysFont('calbri', 30)
text = font.render(msg, 1, (255, 255, 255))
position = ( ((x+8)+((w-100)/2)), ((y+40)+((h-100)/2)) )
win.blit(text, position)
########################## Game Intro Function ################################
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
elif event.key == pygame.K_e:
pygame.quit()
quit()
win.fill((0, 255, 255))
font = pygame.font.SysFont('Bahnschrift Light', 60)
text = font.render('Cystal Caves', 1, (0, 0, 255))
win.blit(text, (424, 60))
button(' Go!',(150+160),450,100,50,(0, 255, 0),(0, 200, 0), "play")
button("Controls",(350+160),450,100,50,(249, 166, 2), (255, 255, 0), "controls")
button(' Quit?',(550+160),450,100,50,(255, 0, 0),(200, 0, 0), "quit")
pygame.display.update()
clock.tick(15)
This is the issue as it does not activate the go button, I have tried using the redraw game window and variables but nothing seems to work. I really need this fixed as it is part of a very big assignment that is due soon and I am having mental breakdowns. I have gotten the c button to work and it enters the game and I tried for the go button but its not working and I just don't know why. PLEASE HELP!!!!
I believe this is an issue with your global intro variable. The global keyword should be used when you want to assign a new value to a global variable inside a function and a global variable should be initialized outside of a function.
So if you initialize the intro variable outside of any function e.g.
intro = true
def game_controls(): # First page of controls #################################
gcont = True
global intro
gameDisplay.fill(white)
...
and then change your game_intro() function to
def game_intro():
global intro
while intro:
...
then your issue should be solved (or at least an issue should be solved).

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()

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.

Pygame Index Out of Range

I am building an asteroids-like game with python, but I'm running into trouble with keeping within the range of my possibleTurrets array. All I'm doing is iterating through the array, and when the edge cases outside of the array occur, I deal with them through:
if currentTurPos > 8:
currentTurPos = 8
elif currentTurPos < 0:
currenTurPos = 0
This is in reference to this array:
possibleTurrets = [ (x-27,y-2),
(x-26,y-5),
(x-25,y-8),
(x-23,y-12),
(x-20,y-14),
(x-18,y-15),
(x-15,y-17),
(x-13,y-19),
(x-11,y-21)
]
For some reason this code works fine on pygame.K_UP but not on pygame.K_DOWN and I have no idea why.
This seems like it should be really obvious, but I've spent an hour trying to fix it, and am drawing a blank. The issue is with my ufo function, and the currentTurPos variable.
# Libraries
import pygame
import time
import random
import os
# Initialize Pygame
pygame.init()
# Colors
white = (255,255,255)
black = (0,0,0)
red = (200,0,0)
blue = (0,0,255)
green = (34,177,76)
light_green = (0,255,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
light_red = (255,0,0)
# Display
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
#pygame.display.set_caption('Slither')
#icon = pygame.image.load('apple.bmp')
#pygame.display.set_icon(icon)
clock = pygame.time.Clock()
# Sprites
ufoWidth = 40
ufoHeight = 20
turretWidth = 5
turretHeight = 10
fps = 15 # Speed
# Fonts
smallFont = pygame.font.SysFont("comicsansms", 25)
medFont = pygame.font.SysFont("comicsansms", 50)
largeFont = pygame.font.SysFont("comicsansms", 80)
def ufo(x,y,turPos):
x = int(x)
y = int(y)
possibleTurrets = [ (x-27,y-2),
(x-26,y-5),
(x-25,y-8),
(x-23,y-12),
(x-20,y-14),
(x-18,y-15),
(x-15,y-17),
(x-13,y-19),
(x-11,y-21)
]
pygame.draw.circle(gameDisplay, blue, (x,y),int(ufoHeight/2))
pygame.draw.ellipse(gameDisplay, black, (x-ufoHeight, y, ufoWidth, ufoHeight))
pygame.draw.line(gameDisplay,blue,(x,y),possibleTurrets[turPos],turretWidth)
# Font sizes
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()
# Displays a message: Requires message, color, y-displacement, and size arguments
def message_to_screen(msg, color, y_displace=0, size="small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (int(display_width/2), (int(display_height/2) + y_displace))
gameDisplay.blit(textSurf, textRect)
# Show button text
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)
# On button hover
def button(text,x,y,width,height,inactive_color,active_color,action):
cursor = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cursor[0] > x and y + height > cursor[1] > y:
pygame.draw.rect(gameDisplay,active_color,(x,y,width,height))
if click[0] == 1 and action != None:
if action == "play":
gameLoop()
if action == "controls":
game_controls()
if action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay,inactive_color,(x,y,width,height))
text_to_button(text,black,x,y,width,height)
def game_controls():
gcont = True
while gcont:
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("Controls", green, -100, size="large")
message_to_screen("Fire: Spacebar", black, -30, size="small")
message_to_screen("Move turret: Up and Down arrows", black, 10, size="small")
message_to_screen("Move UFO: Left and Right arrows", black, 50, size="small")
message_to_screen("Pause: P", black, 90, size="small")
button("Play",150,450,100,50, green, light_green, action="play")
button("Quit",550,450,100,50, red, light_red, action="quit")
pygame.display.update()
clock.tick(fps)
# Pauses game and gives continue and quit options
def pause():
paused = True
message_to_screen("Paused", black, -100, size="large")
message_to_screen("Press P to play, or Q to quit.", black, 25, size="small")
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
pygame.display.update()
clock.tick(fps)
# Keeps track of, and displays the score
def score(score):
text = smallFont.render(" Score: " + str(score), True, black)
gameDisplay.blit(text, [0,0])
# Barrier
def barrier():
xlocation = (display_width/2) + random.randint(-0.2*displayWidth,0.2*displayWidth)
# Intro screen - Title and directions
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("Welcome to UFO!", green, -100, size="large")
message_to_screen("The objective of the game is to search and destroy.", black, -30, size="small")
message_to_screen("Destroy your opponent before they destroy you.", black, 10, size="small")
message_to_screen("The more enemies you destroy, the harder they get.", black, 50, size="small")
button("Play",150,450,100,50, green, light_green, action="play")
button("Controls",350,450,100,50, yellow, light_yellow, action="controls")
button("Quit",550,450,100,50, red, light_red, action="quit")
pygame.display.update()
clock.tick(fps)
# Main game loop
def gameLoop():
gameExit = False
gameOver = False
mainUfoX = display_width * 0.9
mainUfoY = display_height * 0.9
ufoMove = 0
currentTurPos = 0
changeTur = 0
# Game over screen and changes for key inputs
while not gameExit:
if gameOver == True:
message_to_screen("Game over!", red, -50, size="large")
message_to_screen("Press C to play again, Q to quit.", black, 50, size="medium")
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
# Make changes for specific key inputs
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
ufoMove = -5
elif event.key == pygame.K_RIGHT:
ufoMove = 5
elif event.key == pygame.K_UP:
changeTur = 1
elif event.key == pygame.K_DOWN:
changeTur = -1
elif event.key == pygame.K_p:
pause()
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
ufoMove = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
changeTur = 0
gameDisplay.fill(white)
mainUfoX += ufoMove
currentTurPos += changeTur
if currentTurPos > 8:
currentTurPos = 8
elif currentTurPos < 0:
currenTurPos = 0
ufo(mainUfoX,mainUfoY,currentTurPos)
pygame.display.update()
clock.tick(fps)
# Quits
pygame.quit()
quit()
# Loads game intro screen
game_intro()
# gameLoop calls itself to begin game
gameLoop()
It was a typo (I'm an idiot).
currentTurPos was currenTurPos.
Lesson learned: complex variable names with repeating letters are dangerous.

Weird glitching out Pygame Python images

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'.

Categories

Resources