I've been trying to make a button work for a pygame multiple choice game, where after the random question is pressed it will bring you to a question page with 2 answers, one right, one wrong. However they are not reacting to anything when pressed, my code can be seen below;
import pygame
import random
pygame.init()
win = pygame.display.set_mode((1200, 600))
pygame.display.set_caption("History Game")
#Background Image Loading
bg = pygame.image.load('bg.jpg')
bgAus = pygame.image.load('bg_Aus.jpg')
bgEN = pygame.image.load('bg_EN.jpg')
bgIR = pygame.image.load('bg_IR.jpg')
WHITE = (255, 255, 255)
ACTIVE_COLOR = pygame.Color('blue')
INACTIVE_COLOR = pygame.Color('red')
FONT = pygame.font.Font(None, 50)
def draw_buttonStart(buttonStart, win):
pygame.draw.rect(win, buttonStart['color'], buttonStart['rect'])
win.blit(buttonStart['text'], buttonStart['text rect'])
def draw_buttonAus1(buttonAus1, win):
pygame.draw.rect(win, buttonAus1['color'], buttonAus1['rect'])
win.blit(buttonAus1['text'], buttonAus1['text rect'])
def draw_buttonAus2(buttonAus2, win):
pygame.draw.rect(win, buttonAus2['color'], buttonAus2['rect'])
win.blit(buttonAus2['text'], buttonAus2['text rect'])
def draw_buttonIR1(buttonIR1, win):
pygame.draw.rect(win, buttonIR1['color'], buttonIR1['rect'])
win.blit(buttonIR1['text'], buttonIR1['text rect'])
def draw_buttonIR2(buttonIR2, win):
pygame.draw.rect(win, buttonIR2['color'], buttonIR2['rect'])
win.blit(buttonIR2['text'], buttonIR2['text rect'])
def draw_buttonEN1(buttonEN1, win):
pygame.draw.rect(win, buttonEN1['color'], buttonEN1['rect'])
win.blit(buttonEN1['text'], buttonEN1['text rect'])
def draw_buttonEN2(buttonEN2, win):
pygame.draw.rect(win, buttonEN2['color'], buttonEN2['rect'])
win.blit(buttonEN2['text'], buttonEN2['text rect'])
def create_button(x, y, w, h, text, callback):
text_surf = FONT.render(text, True, WHITE)
button_rect = pygame.Rect(x, y, w, h)
text_rect = text_surf.get_rect(center=button_rect.center)
button = {
'rect': button_rect,
'text': text_surf,
'text rect': text_rect,
'color': INACTIVE_COLOR,
'callback': callback,
}
return button
points = 0
def correct_answer():
global points
points += 100
print(points)
def wrong_answer():
global points
points -= 50
print(points)
moveOn = 0
def move_on():
global moveOn
moveOn = 1
win.blit(bg, (0, -200))
#Main Loop
over = False
while not over:
score = FONT.render('Score: ' + str(points), 1, (255,0,0))
win.blit(score, (390, 10))
pygame.display.flip()
buttonStart = create_button(50, 50, 250, 80, 'Random', move_on)
button_listStart = [buttonStart]
draw_buttonStart(buttonStart, win)
#Quits game if X is clicked
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listStart:
if button['rect'].collidepoint(event.pos):
button['callback']()
print (moveOn)
randomQ = random.randint(1,3)
if int(randomQ) == 1:
print("1")
buttonAus1 = create_button(275, 400, 250, 80, '1606', correct_answer)
buttonAus2 = create_button(675, 400, 250, 80, '1723', wrong_answer)
button_listAus = [buttonAus1, buttonAus2]
win.blit(bgAus, (-400, 0))
draw_buttonAus1(buttonAus1, win)
draw_buttonAus2(buttonAus2, win)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listAus:
if button['rect'].collidepoint(event.pos):
button['callback']()
print (points)
#Hover over button changes colour
elif event.type == pygame.MOUSEMOTION:
for button in button_listAus:
if button['rect'].collidepoint(event.pos):
button['color'] = ACTIVE_COLOR
else:
button['color'] = INACTIVE_COLOR
elif int(randomQ) == 2:
print ("2")
buttonEN1 = create_button(675, 400, 250, 80, '1715', correct_answer)
buttonEN2 = create_button(275, 400, 250, 80, '1789', wrong_answer)
button_listEN = [buttonEN1, buttonEN2]
win.blit(bgEN, (0, -150))
draw_buttonEN1(buttonEN1, win)
draw_buttonEN2(buttonEN2, win)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listEN:
if button['rect'].collidepoint(event.pos):
button['callback']()
#Hover over button changes colour
elif event.type == pygame.MOUSEMOTION:
for button in button_listEN:
if button['rect'].collidepoint(event.pos):
button['color'] = ACTIVE_COLOR
else:
button['color'] = INACTIVE_COLOR
else:
print ("3")
buttonIR1 = create_button(275, 400, 250, 80, '1760', correct_answer)
buttonIR2 = create_button(675, 400, 250, 80, '1812', wrong_answer)
button_listIR = [buttonIR1, buttonIR2]
win.blit(bgIR, (-375, -20))
draw_buttonIR1(buttonIR1, win)
draw_buttonIR2(buttonIR2, win)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
for button in button_listIR:
if button['rect'].collidepoint(event.pos):
button['callback']()
#Hover over button changes colour
elif event.type == pygame.MOUSEMOTION:
for button in button_listIR:
if button['rect'].collidepoint(event.pos):
button['color'] = ACTIVE_COLOR
else:
button['color'] = INACTIVE_COLOR
I was wandering if it might have something to do with the for loop as before I combined the for loop for the main loop and the quit feature, the quit feature didn't work at all so any help is appreciated, Thank you.
try binding your buttons to their respective mouse actions.
Related
I have been following this tutorial about animated buttons in pygame. It worked perfectly until I created a button outside of the main loop in another function.
Here is my code:
import pygame
from pygame.locals import *
import sys
import random
# Constants
SCREEN = pygame.display.set_mode((1280, 720), 0, 32)
# Colours
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREY = (100, 100, 100)
LIGHT_BLUE = (66, 233, 245)
# Button Class
class Button:
def __init__(self, text, width, height, pos, elevation):
# Core attributes
self.pressed = False
self.elevation = elevation
self.dynamicElevation = elevation
self.originalYPos = pos[1]
# Top Rectangle
self.topRectangle = pygame.Rect(pos, (width, height))
self.topColor = '#457B9D'
# Bottom Rectangle
self.bottomRectangle = pygame.Rect(pos, (width, elevation))
self.bottomColor = '#1D3557'
# Text
self.textSurface = gui_font.render(text, True, '#FFFFFF')
self.textRectangle = self.textSurface.get_rect(center = self.topRectangle.center)
def draw(self):
# Elevation Logic
self.topRectangle.y = self.originalYPos - self.dynamicElevation
self.textRectangle.center = self.topRectangle.center
self.bottomRectangle.midtop = self.topRectangle.midtop
self.bottomRectangle.height = self.topRectangle.height + self.dynamicElevation
bottom =pygame.draw.rect(SCREEN, self.bottomColor, self.bottomRectangle, border_radius = 12)
top = pygame.draw.rect(SCREEN, self.topColor, self.topRectangle, border_radius = 12)
pygame.draw.rect(SCREEN, '#000000', top, 1, border_radius = 12)
pygame.draw.rect(SCREEN, '#000000', bottom, 1, border_radius = 12)
SCREEN.blit(self.textSurface, self.textRectangle)
self.check_click()
def check_click(self):
mousePosition = pygame.mouse.get_pos()
if self.topRectangle.collidepoint(mousePosition):
self.topColor = '#F1FAEE'
if pygame.mouse.get_pressed()[0]:
self.dynamicElevation = 0
self.pressed = True
else:
self.dynamicElevation = self.elevation
if self.pressed == True:
print("Click")
self.pressed = False
else:
self.topColor = '#457B9D'
class GameState():
def __init__(self):
self.state = "welcome"
def welcomeScreen(self):
SCREEN.fill(WHITE)
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
exit()
if event.key == K_F1:
self.state = "mainGame"
pygame.display.update()
def mainGame(self):
SCREEN.fill(GREY)
buttonBack = Button("Back to Main Screen", 250, 30, (1000, 650), 8)
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
exit()
if event.key == K_F2:
self.state = "welcome"
buttonBack.draw()
pygame.display.update()
def stateManager(self):
if self.state == "welcome":
self.welcomeScreen()
if self.state == "mainGame":
self.mainGame()
pygame.init()
clock = pygame.time.Clock()
gameState = GameState()
pygame.display.set_caption("Button Test")
gui_font = pygame.font.Font(None, 30)
while True:
gameState.stateManager()
clock.tick(60)
I have tried to play around with putting the button in a different screen or at different stages of the loop. Is there a logic error I cannot see or lies my mistake somewhere else?
You are actually creating the button inside the main loop since you create it each time mainGame is called. mainGame is called by stateManager if the state is "mainGame", and that's called at each frame in your while True loop. So as you are recreating your button at each frame I think your problems might come from there.
I suggest you create your button in the parent's class constructor instead:
class GameState():
def __init__(self):
self.state = "welcome"
# Create the button here to make the object persistent.
self.buttonBack = Button("Back to Main Screen", 250, 30, (1000, 650), 8)
# ...
def mainGame(self):
SCREEN.fill(GREY)
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
exit()
if event.key == K_F2:
self.state = "welcome"
self.buttonBack.draw() # <- use your button with self.buttonBack
pygame.display.update()
# ...
The program consists in generating 2 random numbers, rendering them on screen (with the '+' symbol, because it's a sum) and expecting the user to put the result of the sum on the box entry. The code already has a function that generates 2 random numbers (x and y), and another one that renders them on screen (besides the score). Here is the code:
import pygame
import random
from InputBox import InputBox
pygame.init()
clock = pygame.time.Clock()
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Projecte MatZanfe")
font = pygame.font.SysFont('comicsans', 50)
base_font = pygame.font.Font(None, 32)
user_text = ''
color_active = pygame.Color('lightskyblue3')
running = True
points = 0
def start_the_game():
x = random.randint(0, 10)
y = random.randint(0, 10)
is_correct = False
return x, y
def display_the_game(x, y):
# Variables
z = x + y
surface.fill((255, 70, 90))
text = font.render(str(x) + "+" + str(y), True, (255, 255, 255))
text_surface = base_font.render(user_text, True, (255, 255, 255))
surface.blit(text, (260, 120))
input_box.draw(surface)
punts = font.render("PuntuaciĆ³: " + str(points),True, (255,255,255))
surface.blit(punts, (350,30))
x, y = start_the_game()
input_box = InputBox(190, 250, 200, 32)
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
result = input_box.handle_event(event)
if result != None:
if int(result) == int(x) + int(y):
# TODO: when the user is right
points = points + 5
start_the_game()
pygame.display.update()
display_the_game(x, y)
pygame.display.update()
else:
# TODO: when the user is wrong
start_the_game
pygame.display.update()
display_the_game(x, y)
pygame.display.update()
display_the_game(x, y)
pygame.display.update()
pygame.quit()
I need the program to generate two new random numbers if the result is right and render them, apart from adding 5 points to the "PuntuaciĆ³" that appears up to the right (done). If the user is wrong, it just needs to generate 2 new random numbers, and render them (the score doesn't have to change).
Here is the code from the imported InputBox.
import pygame
pygame.init()
surface = pygame.display.set_mode((600, 400))
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('dodgerblue2')
FONT = pygame.font.SysFont('comicsans', 32)
base_font = pygame.font.Font(None, 32)
color_active = pygame.Color('lightskyblue3')
user_text = ''
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pygame.Rect(x, y, w, h)
self.color = COLOR_INACTIVE
self.text = text
self.txt_surface = FONT.render(text, True, self.color)
self.active = False
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
# If the user clicked on the input_box rect.
if self.rect.collidepoint(event.pos):
# Toggle the active variable.
self.active = not self.active
else:
self.active = False
# Change the current color of the input box.
self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
if event.type == pygame.KEYDOWN:
if self.active:
if event.key == pygame.K_RETURN:
user_input = self.text
self.text = ''
self.txt_surface = FONT.render(self.text, True, self.color)
return user_input
elif event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode
# Re-render the text.
self.txt_surface = FONT.render(self.text, True, self.color)
def update(self):
# Resize the box if the text is too long.
width = max(200, self.txt_surface.get_width()+10)
self.rect.w = width
def draw(self, screen):
# Blit the text.
screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
# Blit the rect.
pygame.draw.rect(screen, self.color, self.rect, 2)
def main():
clock = pygame.time.Clock()
input_box2 = InputBox(190, 250, 200, 32)
input_boxes = [input_box2]
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
for box in input_boxes:
box.handle_event(event)
for box in input_boxes:
box.update()
surface.fill((255, 70, 90))
for box in input_boxes:
box.draw(surface)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pygame.quit()
All you have to do is to create new values for x and y and to reset the input box:
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
result = input_box.handle_event(event)
if result != None:
if int(result) == int(x) + int(y):
points = points + 5
# create new random numbers
x, y = start_the_game()
# reset input box (just create a new box)
input_box = InputBox(190, 250, 200, 32)
display_the_game(x, y)
pygame.display.update()
pygame.quit()
I'm trying to make it if you press ESC a quit box appears with the text "Do you want to quit?" on it. If the user clicks y the program ends. I think the first problem may be in the quitBox function but I don't know at all what is wrong in it. To me the function name and variables look okay. when i call the function it says that
name 'quitBoxPosX' is not defined
I think same goes with quitBoxPosY
Here's the code:
import pygame
import random
pygame.init()
# variables
mainLoop = True
font1 = pygame.font.SysFont('comicsansms', 25)
font2 = pygame.font.SysFont('underline', 35)
white = [255, 255, 255]
green = [0, 150, 0]
gray = [200, 200, 200]
black = [0, 0, 0]
clickNum = 0
clickAmount = 1
FPS = pygame.time.Clock()
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 2)
screen = pygame.display.set_mode((1300, 700))
# functions
def switchButton01(events, buttonPlusPos):
global button02
button02 = pygame.transform.scale(button02, (100, 100))
screen.blit(button02, [580, 350])
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
global clickNum
clickNum += 1
global clickplusx, clickplusy
clickplusx = mouse
clickplusy = mouse
return (clickplusx, clickplusy)
return buttonPlusPos
def quitBox():
global quitBoxImage
global quitBoxPosX, quitBoxPosY
quitBoxImage = pygame.transform.scale(quitBoxImage, (300, 200))
quitBoxPosX = 430
quitBoxPosY = 200
return (quitBox, quitBoxPosX, quitBoxPosY)
# load images
button01 = pygame.image.load('button_100.png')
button02 = pygame.image.load('button_100hovered.png')
icon = pygame.image.load('icon_128.png')
buttonPlusImage = pygame.image.load('buttonPlus_32.png')
upgradeIcon = pygame.image.load('upgradesicon_64.png')
quitBoxImage = pygame.image.load('emptyGUI.png')
# title, icon
pygame.display.set_caption("incremental button")
pygame.display.set_icon(icon)
buttonPlusPos = None
while mainLoop:
pygame.display.flip()
FPS.tick(144)
screen.fill(white)
# actual content in the game
events = pygame.event.get()
mouse = pygame.mouse.get_pos()
# define objects
button01 = pygame.transform.scale(button01, (100, 100))
click_counter_text = font1.render("Click counter: ", True, black, white)
button01rect = button01.get_rect(center=(630, 400))
button01collidepoint = button01rect.collidepoint(pygame.mouse.get_pos())
click_counter = font1.render((str(clickNum)), True, black, white)
upgradeIcon = pygame.transform.smoothscale(upgradeIcon, (30, 30))
upgrades = font2.render('UPGRADES:', True, black)
FPScounter = font1.render('Frames per second:' + str(int(FPS.get_fps())), True, black, white)
# show objects
screen.blit(FPScounter, [20, 10])
screen.blit(button01, [580, 350])
screen.blit(click_counter_text, [525, 50])
upgradesBG = pygame.draw.rect(screen, gray, (1060, 44, 193, 600))
screen.blit(upgradeIcon, [1064, 46])
screen.blit(upgrades, [1100, 50])
screen.blit(click_counter, [700, 50])
if button01collidepoint:
buttonPlusPos = switchButton01(events, buttonPlusPos)
if buttonPlusPos:
screen.blit(buttonPlusImage, buttonPlusPos)
# quits
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
quitBoxPos = quitBox(quitBoxPosX, quitBoxPosY)
if quitBoxPos:
screen.blit(quitBoxImage(quitBoxPosX, quitBoxPosY))
font1.render(quitBox, 'Do you want to quit?', True, black, white)
if event.type == pygame.KEYDOWN and event.key == pygame.K_y:
pygame.quit()
quit()
quitBox has to return a the quit box data tuple, which consist of the image and the position of the box:
def quitBox():
img = pygame.transform.scale(quitBoxImage, (300, 200))
text = font1.render('Do you want to quit?', True, black, white)
img.blit(text, text.get_rect(center = img.get_rect().center))
return img, (430, 200)
You have to initialize the variable quitBoxData before the main application loop and to draw the box in the loop if quitBoxData is set:
quitBoxData = None
buttonPlusPos = None
while mainLoop:
# [...]
if quitBoxData:
screen.blit(*quitBoxData)
# [...]
When a KEYDOWN event occurs, then you have to do different things, dependent if quitBoxData is set or not. If it is not set and ESC is pressed, then you have to invoke quitBox and to get the data. If quitBoxData is not set an y is pressed, then leave the application (mainLoop = False) else continue (quitBoxData = None):
while mainLoop:
# [...]
# quits
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if quitBoxData:
if event.key == pygame.K_y:
mainLoop = False
else:
quitBoxData = None
else:
if event.key == pygame.K_ESCAPE:
quitBoxData = quitBox()
Full application code:
import pygame
import random
pygame.init()
# variables
mainLoop = True
font1 = pygame.font.SysFont('comicsansms', 25)
font2 = pygame.font.SysFont('underline', 35)
white = [255, 255, 255]
green = [0, 150, 0]
gray = [200, 200, 200]
black = [0, 0, 0]
clickNum = 0
clickAmount = 1
FPS = pygame.time.Clock()
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 2)
screen = pygame.display.set_mode((1300, 700))
# functions
def switchButton01(events, buttonPlusPos):
global button02
button02 = pygame.transform.scale(button02, (100, 100))
screen.blit(button02, [580, 350])
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
global clickNum
clickNum += 1
global clickplusx, clickplusy
clickplusx = mouse
clickplusy = mouse
return (clickplusx, clickplusy)
return buttonPlusPos
def quitBox():
img = pygame.transform.scale(quitBoxImage, (300, 200))
text = font1.render('Do you want to quit?', True, black, white)
img.blit(text, text.get_rect(center = img.get_rect().center))
return img, (430, 200)
# load images
button01 = pygame.image.load('button_100.png')
button02 = pygame.image.load('button_100hovered.png')
icon = pygame.image.load('icon_128.png')
buttonPlusImage = pygame.image.load('buttonPlus_32.png')
upgradeIcon = pygame.image.load('upgradesicon_64.png')
quitBoxImage = pygame.image.load('emptyGUI.png')
# title, icon
pygame.display.set_caption("incremental button")
pygame.display.set_icon(icon)
quitBoxData = None
buttonPlusPos = None
while mainLoop:
pygame.display.flip()
FPS.tick(144)
screen.fill(white)
# actual content in the game
events = pygame.event.get()
mouse = pygame.mouse.get_pos()
# define objects
button01 = pygame.transform.scale(button01, (100, 100))
click_counter_text = font1.render("Click counter: ", True, black, white)
button01rect = button01.get_rect(center=(630, 400))
button01collidepoint = button01rect.collidepoint(pygame.mouse.get_pos())
click_counter = font1.render((str(clickNum)), True, black, white)
upgradeIcon = pygame.transform.smoothscale(upgradeIcon, (30, 30))
upgrades = font2.render('UPGRADES:', True, black)
FPScounter = font1.render('Frames per second:' + str(int(FPS.get_fps())), True, black, white)
# show objects
screen.blit(FPScounter, [20, 10])
screen.blit(button01, [580, 350])
screen.blit(click_counter_text, [525, 50])
upgradesBG = pygame.draw.rect(screen, gray, (1060, 44, 193, 600))
screen.blit(upgradeIcon, [1064, 46])
screen.blit(upgrades, [1100, 50])
screen.blit(click_counter, [700, 50])
if button01collidepoint:
buttonPlusPos = switchButton01(events, buttonPlusPos)
if buttonPlusPos:
screen.blit(buttonPlusImage, buttonPlusPos)
if quitBoxData:
screen.blit(*quitBoxData)
# quits
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if quitBoxData:
if event.key == pygame.K_y:
mainLoop = False
else:
quitBoxData = None
else:
if event.key == pygame.K_ESCAPE:
quitBoxData = quitBox()
How do I implement a play again feature in this Connect 4 game?
import numpy as np
import pygame
import math
pygame.init()
#COLORS
GREEN = (0,200,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
RED = (200,0,0)
YELLOW = (255,255,0)
WHITE = (255,255,255)
PINK = (255,0,127)
bright_pink = (255,51,153)
bright_red = (255,0,0)
bright_green = (0,255,0)
bright_blue = (0,0,204)
ROW_COUNT = 6
COLUMN_COUNT = 7
pause = False
#DISPLAY
gameDisplay = pygame.display.set_mode((ROW_COUNT, COLUMN_COUNT))
pygame.display.set_caption("Connect 4") #Window Title
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def create_board():
board = np.zeros((ROW_COUNT,COLUMN_COUNT))
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
hitSound.play()
def is_valid_location(board, col):
return board[ROW_COUNT-1][col] == 0
def get_next_open_row(board, col):
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
def print_board(board):
print(np.flip(board, 0))
def winning_move(board, piece):
# Check horizontal locations for win
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
# Check vertical locations for win
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
# Check positively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
# Check negatively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(3, ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
def draw_board(board):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
pygame.draw.rect(screen, bright_blue, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circle(screen, BLACK, (int(c*SQUARESIZE+SQUARESIZE/2), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
if board[r][c] == 1:
pygame.draw.circle(screen, RED, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
elif board[r][c] == 2:
pygame.draw.circle(screen, YELLOW, (int(c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
pygame.display.update()
board = create_board()
print_board(board)
game_over = False
SQUARESIZE = 100
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width, height)
RADIUS = int(SQUARESIZE/2 - 5)
screen = pygame.display.set_mode(size)
draw_board(board)
pygame.display.update()
myfont2 = pygame.font.SysFont("Arial black", 75)
def gameover():
gameDisplay.blit(background, (0, 0))
gameDisplay.blit(gameoverimg, (0, 0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play Again", 210, 350, 300, 80, GREEN, bright_green, )
button("Quit", 260, 470, 200, 80, PINK, bright_pink, quit)
pygame.display.update()
clock.tick(15)
def button(msg, x, y, w, h, ic, ac, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay, ic, (x, y, w, h))
buttonText = pygame.font.SysFont("arial black", 50)
textSurf, textRect = text_objects(msg, buttonText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
gameDisplay.blit(textSurf, textRect)
def quitgame():
pygame.quit()
quit()
def unpause():
global pause
pygame.mixer.music.unpause()
pause = False
def paused():
pygame.mixer.music.pause()
gameDisplay.blit(background, (0, 0))
gameDisplay.blit(pauseimg, (0, 0))
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Continue",210, 350, 300, 80, GREEN, bright_green, unpause)
button("Quit",260, 470, 200, 80, PINK, bright_pink, quit)
pygame.display.update()
clock.tick(15)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.blit(background, (0, 0))
gameDisplay.blit(gmenu, (0, 60))
button("START", 210, 350, 300, 80, GREEN, bright_green, game_loop)
button("QUIT", 260, 470, 200, 80, PINK, bright_pink, quit)
pygame.display.update()
clock.tick(15)
def game_loop(turn=0):
global pause
game_over = False
while not game_over:
print_board(board)
draw_board(board)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(screen, BLACK, (0, 0, width, SQUARESIZE))
posx = event.pos[0]
if turn == 0:
label2 = myfont2.render("RED TURN", 1, WHITE)
screen.blit(label2, (150, 10))
pygame.draw.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS)
else:
label3 = myfont2.render("YELLOW TURN", 1, WHITE)
screen.blit(label3, (50, 10))
pygame.draw.circle(screen, YELLOW, (posx, int(SQUARESIZE/2)), RADIUS)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
pause = True
pause_sound.play()
paused()
# print_board(board)
# draw_board(board)
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE))
# Ask for Player 1 Input
if turn == 0:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 1)
if winning_move(board, 1):
label = myfont2.render("RED WINS", 1, RED)
screen.blit(label, (155,10))
# gameover()
game_over = True #Change to False so it will not auto-quit
# # Ask for Player 2 Input
else:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 2)
if winning_move(board, 2):
label = myfont2.render("YELLOW WINS", 1, YELLOW)
screen.blit(label, (60,10))
game_over = True #Change to False so it will not auto-quit
# gameover()
print_board(board)
draw_board(board)
turn += 1
turn = turn % 2
if game_over:
pygame.time.wait(3000)
gameover()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
Welcome to Stack Overflow. More specific questions, rather than "how do I do this", are preferred.
def gameover():
gameDisplay.blit(background, (0, 0))
gameDisplay.blit(gameoverimg, (0, 0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button("Play Again", 210, 350, 300, 80, GREEN, bright_green, )
button("Quit", 260, 470, 200, 80, PINK, bright_pink, quit)
pygame.display.update()
clock.tick(15)
At the end of your button call for "Play Again", after your color definition, you need to call the correct function to "play again". It seems as though based on your code, you'd need to call game_loop or game_intro.
import pygame
import time
import random
pygame.mixer.pre_init(44100, 16, 2, 4096)
pygame.init()
boop_sound = pygame.mixer.Sound("boop.wav")
display_width = 800
display_height = 600
white = (255,255,255)
black = (0,0,0)
blue = (0, 0, 150)
red = (200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0, 255, 0)
clock = pygame.time.Clock()
smallfont = pygame.font.SysFont("Rockwell", 25)
medfont = pygame.font.SysFont("Rockwell", 35)
largefont = pygame.font.SysFont("Rockwell", 50)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("How fast can you tap?")
##icon = pygame.image.load("apple.png")#should be 32x32
##pygame.display.set_icon(icon)
pygame.display.update()
def score(score):
text = smallfont.render("Clicks: "+str(score), True, blue)
gameDisplay.blit(text, [2,0])
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("How many times can you",
blue,
-80,
"large")
message_to_screen("click the button before the time runs out?",
blue,
-10,
"medium")
#message_to_screen("Press C to play, P to pause or Q to quit.",black,180)
button("Play", 150, 500, 100, 50, green, light_green, action="Play")
button("How to play", 325,500,150,50, yellow, light_yellow, action="How to play")
button("Quit", 550,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def game_over():
game_over = True
while game_over:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Out Of Time!",
red,
-100,
"large")
message_to_screen("You clicked: " + str(click) + " times",
blue,
-30)
button("Play Again", 325, 440, 150, 50, green, light_green, action="Play")
button("Quit", 350,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = ((buttonx +((buttonwidth/2)), buttony+(buttonheight/2)))
gameDisplay.blit(textSurf, textRect)
def message_to_screen(msg,color, y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg, color, size)
#screen_text = font.render(msg, True, color)
#gameDisplay.blit(screen_text, [display_width/2, display_height/2])
textRect.center = (display_width/ 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
def game_controls():
gcont = True
while gcont:
for event in pygame.event.get():
if event.type== pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("How to play", blue, -100,"large")
message_to_screen("You have to click the button as many times", black, -40)
message_to_screen("as you possible can before the time runs out", black, -20)
button("Play", 150, 500, 100, 50, green, light_green, action="Play")
button("Main", 350,500,100,50, yellow, light_yellow, action="Main")
button("Quit", 550,500,100,50, red, light_red, action="Quit")
pygame.display.update()
clock.tick(15)
def button(text, x, y, width, height, inactive_color, active_color, action = None):
cur = pygame.mouse.get_pos()
clicked = pygame.mouse.get_pressed()
global click
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
if clicked[0] == 1 and action != None:
if action == "Quit":
pygame.quit()
quit()
if action == "How to play":
game_controls()
if action == "Play":
gameLoop()
if action == "Main":
game_intro()
if action == "Click":
click += 1
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
text_to_button(text, black, x, y, width, height)
ENDTIMER = pygame.USEREVENT+1
def gameLoop():
gameExit = False
gameOver = False
FPS = 15
click = 0
global click
timed = pygame.time.set_timer(ENDTIMER, 25000)
while not gameExit:
gameDisplay.fill(white)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.mixer.Sound.play(boop_sound)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action="Click")
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
elif event.type == ENDTIMER:
game_over()
score(click)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
game_intro()
gameLoop()
I am trying to make it so that pygame.time.set_time(), will only run after click > 0. I have tried placing the pygame.time.set_time in an if statement, but that did not work. Any responses are greatly appreciated! When placing the timer start in the MOUSEBUTTONDOWN event it will only start when the mouse is clicked, however everytime i click it resets.
def gameLoop():
ENDTIMER = pygame.USEREVENT+1
gameExit = False
gameOver = False
FPS = 15
click = 0
global click
timer_on =False
while not gameExit:
gameDisplay.fill(white)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.MOUSEBUTTONDOWN:
if not timer_on:
timed = pygame.time.set_timer(ENDTIMER, 25000)
pygame.mixer.Sound.play(boop_sound)
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action="Click")
button("CLICK", display_width/2-100,display_height/2-100, 200,200, red, light_red, action=None)
elif event.type == ENDTIMER:
gameExit = True
score(click)
pygame.display.update()
clock.tick(FPS)
game_over()
pygame.quit()
quit()