Clicking recs in Pygame - python

I am currently starting on python3 in the past few days and started in developing minor projects, but i'm having some trouble, so sorry if i cant use top notch proffessional coders language.
How can I make a pygame.draw.rect rectangle become clickable?
I know about the pygame.mouse. ones, but there might be something wrong in the code.
I want it so that when i press the red rect it will decreese i health and will add a "burn" stat (its just text for now).
Here's the code:
import pygame
import random
import sys
pygame.init()
#Screen Size
screen_width = 600
screen_height = 600
#Screen Settings
screen = pygame.display.set_mode((screen_width, screen_height))
br_color = (0, 0, 0)
pygame.display.set_caption("Type Effect Beta 0.0.1")
#Game Over Bullian
game_over = False
#Other Defenitions
clock = pygame.time.Clock()
myFont = pygame.font.SysFont("arial", 20)
#Basic Recources
health = 50
score = 0
status = "none"
#Colors for the Text
white = (255, 255, 255)
red = (255, 0, 0)
#Mouse Things
mouse_location = pygame.mouse.get_pos()
print(mouse_location)
#Status Text Helpers
burning = "Burning"
#Cards
card_size_x = 45
card_size_y = 60
fire_car_color = (255, 0 ,0)
fire_card_posx = 300
fire_card_posy = 300
card_button_fire = pygame.Rect(fire_card_posx, fire_card_posy, card_size_x, card_size_y)
#Functions
def health_decrease_burn(health, status):
health -= 1
status = "burning"
return health and status
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if pygame.mouse.get_pressed()[0] and card_button_fire.collidepoint(mouse_location):
health_decrease_burn()
if health_decrease_burn(health, status) and health <= 0:
game_over = True
text = "Score:" + str(score)
lable = myFont.render(text, 1, white)
screen.blit(lable, (10, 10))
text = "Health:" + str(health)
lable = myFont.render(text, 1, red)
screen.blit(lable, (10, 30))
text = "Status:" + str(status)
lable = myFont.render(text, 1, white)
screen.blit(lable, (10, 50))
pygame.draw.rect(screen, fire_car_color, (fire_card_posx, fire_card_posy, card_size_x, card_size_y))
clock.tick(30)
pygame.display.update()

You need to grab the mouse_location every iteration of your main loop, as the mouse position/state is constantly changing. The current code is only fetching the mouse position once, on start.
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP: # if mouse button clicked
mouse_location = pygame.mouse.get_pos() # <-- HERE
if pygame.mouse.get_pressed()[0] and card_button_fire.collidepoint(mouse_location):
health_decrease_burn()
#[...etc ]

Related

How create a leaderboard in python

I have created a memory matching game where the player has to match up 15 similar pairs and they are timed. Once all pairs have been matched their end score is displayed in a final scree which says "Your final time was ...". I have also created a Main menu screen where the player has to login with a username and password. I want to add a leaderboard system to this game where the players name and final score is displayed in a table.
Here is the code for my Main menu w/o the login bit:
import pygame, sys, random
from GAME import *
from Time_Trial import *
##from Button import *
#initialises pygame
pygame.init()
#set screen width and height
SCREEN = pygame.display.set_mode((700, 610))
pygame.display.set_caption("Memory Game") # Add window title
orange = (255,97,3)
def get_font(size): # defines desired font and size
return pygame.font.Font("freesansbold.ttf", size)
class Button():
def __init__(self, image, pos, text_input, font, base_color, hovering_color):
self.image = image
self.x_pos = pos[0]
self.y_pos = pos[1]
self.font = font
self.base_color, self.hovering_color = base_color, hovering_color
self.text_input = text_input
self.text = self.font.render(self.text_input, True, self.base_color)
if self.image is None:
self.image = self.text
self.rect = self.image.get_rect(center=(self.x_pos, self.y_pos))
self.text_rect = self.text.get_rect(center=(self.x_pos, self.y_pos))
def update(self, screen):
if self.image is not None:
screen.blit(self.image, self.rect)
screen.blit(self.text, self.text_rect)
def checkForInput(self, position):
if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):
return True
return False
def changeColor(self, position):
if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):
self.text = self.font.render(self.text_input, True, self.hovering_color)
else:
self.text = self.font.render(self.text_input, True, self.base_color)
def play():
while True:
PLAY_MOUSE_POS = pygame.mouse.get_pos()
#Fill the next screen turquoise when Play is clicked
SCREEN.fill("turquoise")
GAME()
#When clicked play button, the next screen will display this
#Creates the exit button in next screen
PLAY_EXIT = Button(image=None, pos=(580, 560),
text_input="EXIT", font=get_font(75), base_color="White", hovering_color="orange")
#Exit button changes colour when mouse hovers over button
PLAY_EXIT.changeColor(PLAY_MOUSE_POS)
#Updates screen when the exit button is clicked
PLAY_EXIT.update(SCREEN)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if PLAY_EXIT.checkForInput(PLAY_MOUSE_POS): # if exit button in play screen is clicked then return back to menu
main_menu()
pygame.display.update()
def time_trial():
while True:
TIME_MOUSE_POS = pygame.mouse.get_pos()
#Fill the next screen turquoise when TIME TRIAL is clicked
SCREEN.fill("turquoise")
Time_Trial()
#Creates the exit button in next screen
TIME_EXIT = Button(image=None, pos=(580, 560),
text_input="EXIT", font=get_font(75), base_color="black", hovering_color="orange")
#Exit button changes colour when mouse hovers over button
TIME_EXIT.changeColor(TIME_MOUSE_POS)
#Updates screen when the exit button is clicked
TIME_EXIT.update(SCREEN)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if TIME_EXIT.checkForInput(TIME_MOUSE_POS): # if exit button in play screen is clicked then return back to menu
main_menu()
pygame.display.update()
def leaderboard():
while True:
leaderboard_MOUSE_POS = pygame.mouse.get_pos()
#Fill the next screen turquoise when leaderboard is clicked
SCREEN.fill("#008000")
#Text inside the leaderboard screen
leaderboard_TEXT = get_font(15).render("This is the leaderboard screen.", True, "Black")
#leaderboard button
leaderboard_RECT = leaderboard_TEXT.get_rect(center=(310, 220))
SCREEN.blit(leaderboard_TEXT, leaderboard_RECT)
#Exit button inside the leaderboard screen
leaderboard_EXIT = Button(image=None, pos=(580, 560),
text_input="EXIT", font=get_font(75), base_color="Black", hovering_color="orange")
#Exit button changes colour when mouse hovers over button
leaderboard_EXIT.changeColor(leaderboard_MOUSE_POS)
#Updates screen when the exit button is clicked
leaderboard_EXIT.update(SCREEN)
for event in pygame.event.get():
if event.type == pygame.QUIT: # if user quits the window then the game ends
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if leaderboard_EXIT.checkForInput(leaderboard_MOUSE_POS): # if exit in leaderboard is clicked, return back to main menu
main_menu()
pygame.display.update()
def main_menu():
while True:
#sets desired colour for the main menu screen
SCREEN.fill('#008000')
MENU_MOUSE_POS = pygame.mouse.get_pos()
#Adds the title Main menu
MENU_TEXT = get_font(50).render("MAIN MENU", True, orange)
MENU_RECT = MENU_TEXT.get_rect(center=(330, 40))
#creates the Play button in main menu screen
PLAY_BUTTON = Button(image=pygame.image.load("assets/Play Rect.png"), pos=(330, 145),
text_input="PLAY", font=get_font(60), base_color="#d7fcd4", hovering_color="orange")
###creates time trial button in the main menu screen
TIME_TRIAL_BUTTON = Button(image=pygame.image.load("assets/Time Rect.png"), pos=(330, 275),
text_input="Time Trial", font=get_font(60), base_color="#d7fcd4", hovering_color="orange")
#creates the leaderboard button in main menu screen
leaderboard_BUTTON = Button(image=pygame.image.load("assets/Options Rect.png"), pos=(370, 400),
text_input="leaderboard", font=get_font(50), base_color="#d7fcd4", hovering_color="orange")
#creates the quit button in main menu screen
QUIT_BUTTON = Button(image=pygame.image.load("assets/Quit Rect.png"), pos=(330, 530),
text_input="QUIT", font=get_font(60), base_color="#d7fcd4", hovering_color="orange")
SCREEN.blit(MENU_TEXT, MENU_RECT)
for button in [PLAY_BUTTON, leaderboard_BUTTON, TIME_TRIAL_BUTTON, QUIT_BUTTON]:
button.changeColor(MENU_MOUSE_POS)
button.update(SCREEN)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if PLAY_BUTTON.checkForInput(MENU_MOUSE_POS): # If the play button is clicked then display the Play screen
play()
if TIME_TRIAL_BUTTON.checkForInput(MENU_MOUSE_POS): #If the leaderboard button is clicked then display the leaderboard screen
time_trial()
if leaderboard_BUTTON.checkForInput(MENU_MOUSE_POS): #If the leaderboard button is clicked then display the leaderboard screen
leaderboard()
if QUIT_BUTTON.checkForInput(MENU_MOUSE_POS): # If Quit button in main menu is clicked then close the program
pygame.quit()
sys.exit()
pygame.display.update()
main_menu()
Here is the code for my Game:
# build a guessing game!
import pygame, random, sys
global options_list, spaces, used, new_board, first_guess, second_guess, first_guess_num, second_guess_num, score, matches, game_over, rows, cols, correct, time
pygame.init()
# game variables and constants
screen_width = 600
screen_height = 600
white = (255, 255, 255)
black = (0, 0, 0)
orange = (255,97,3)
turquoise = (0, 206, 209)
green = (0, 255, 0)
fps = 60
timer = pygame.time.Clock()
rows = 5
cols = 6
correct = [[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0]]
options_list = []
spaces = []
used = []
new_board = True
first_guess = False
second_guess = False
#Guess is assigned an index value. Checks what number is clicked
first_guess_num = 0
second_guess_num = 0
score = 0
matches = 0
game_over = False
cards_left_covered = 0
#timer start time
start_time = pygame.time.get_ticks()
time = 0
# create screen
screen = pygame.display.set_mode([screen_width, screen_height])
pygame.display.set_caption('Memory Game!')
#sets fonts
large_font = pygame.font.Font('freesansbold.ttf', 56)
small_font = pygame.font.Font('freesansbold.ttf', 26)
def generate_board():
global options_list, spaces, used
for item in range(rows * cols // 2):
options_list.append(item)
# goes through list of options between 1-24. Guarantees that only 2 cards can be selected
for item in range(rows * cols):
card = options_list[random.randint(0, len(options_list) - 1)]
spaces.append(card)
if card in used:
used.remove(card)
options_list.remove(card)
else:
used.append(card)
#Sets background colours and shapes
def draw_backgrounds():
global start_time, time
top_menu = pygame.draw.rect(screen, orange, [0, 0, screen_width, 75])
score_text = small_font.render(f'Player 1 score : {score}', True, white)
screen.blit(score_text, (20, 20))
board_space = pygame.draw.rect(screen, turquoise, [0, 100, screen_width, screen_height - 200], 0)
bottom_menu = pygame.draw.rect(screen, orange, [0, screen_height - 100, screen_width, 100], 0)
time = 0 + int((pygame.time.get_ticks() / 1000))
time_text = small_font.render(f'Your time: {time}', True, white)
screen.blit(time_text, (20, 550))
def draw_cards():
global rows, columns, correct
card_list = []
for i in range(cols):
for j in range(rows):
#draws the cards and sets their size and position
card = pygame.draw.rect(screen, orange,[i * 85 + 48, j *78 + 110, 61, 65], 0, 4)
card_list.append(card)
## randomly adds numbers onto the cards. to make sure that the black numbers dont populate instantly when game is created
'''card_text = small_font.render(f'{spaces[i * rows + j]}', True, black)
screen.blit(card_text, (i * 75 + 18, j * 65 + 120))'''
for r in range(rows):
for c in range(cols):
if correct[r][c] == 1:
#creates green border around cards when match is made
pygame.draw.rect(screen, green, [c * 85 + 48, r * 78 + 110, 61, 65], 3, 4)
card_text = small_font.render(f'{spaces[c * rows + r]}', True, black)
screen.blit(card_text, (c * 85 + 55, r * 78 + 125))
return card_list
def check_guesses(first, second):
global spaces, correct, score, matches
if spaces[first] == spaces[second]:
#floor division
col1 = first // rows
col2 = second // rows
row1 = first - (first // rows * rows)
row2 = second - (second // rows * rows)
#checks for match and score incremented by 1
if correct[row1][col1] == 0 and correct[row2][col2] == 0:
correct[row1][col1] = 1
correct[row2][col2] = 1
score += 1
matches += 1
running = True
while running:
timer.tick(fps)
screen.fill(turquoise)
if new_board:
generate_board()
new_board = False
draw_backgrounds()
board = draw_cards()
if first_guess and second_guess:
check_guesses(first_guess_num, second_guess_num)
##delays code for miliseconds to see second guess
pygame.time.delay(1000)
first_guess = False
second_guess = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
for i in range(len(board)):
button = board[i]
#can guess as long as it's not game over
if not game_over:
if button.collidepoint(event.pos) and not first_guess:
first_guess = True
first_guess_num = i
##ensures that the same card cannot be clicked twice
if button.collidepoint(event.pos) and not second_guess and first_guess and i != first_guess_num:
second_guess = True
second_guess_num = i
#Checks for game over
if matches == rows * cols // 2:
if not game_over:
end_time = time
game_over = True
winner = pygame.draw.rect(screen, turquoise,[0, 0, 600, 600])
winner_text = large_font.render(f'YOUR TIME WAS {end_time} !!', True, orange)
screen.blit(winner_text, (30, screen_height - 350))
#allows card to be flipped to show number
if first_guess:
card_text = small_font.render(f'{spaces[first_guess_num]}', True, black)
location = (first_guess_num // rows * 85 + 55, (first_guess_num - (first_guess_num // rows * rows)) * 78 + 125)
screen.blit(card_text, (location))
if second_guess:
card_text = small_font.render(f'{spaces[second_guess_num]}', True, black)
location = (second_guess_num // rows * 85 + 55, (second_guess_num - (second_guess_num // rows * rows)) * 78 + 125)
screen.blit(card_text, (location))
pygame.display.flip()
pygame.quit()

Keep text on screen after clicking [duplicate]

I'm currently making a Python clicking game using Pygame. Right now, there is a coin in the center of the screen that you can click. What I want to add now, it a little green "+$10" icon that appears somewhere next to the coin whenever someone clicks it. This is what I want the game to look like whenever someone clicks the coin:
Here is the code of my coin functions:
def button_collide_mouse(element_x, element_y, x_to_remove, y_to_remove):
mouse_x, mouse_y = pygame.mouse.get_pos()
if mouse_x > element_x > mouse_x - x_to_remove and \
mouse_y > element_y > mouse_y - y_to_remove:
return True
def check_events(coin, settings):
for event in pygame.event.get():
# Change button color if mouse is touching it
if button_collide_mouse(coin.image_x, coin.image_y, 125, 125):
coin.image = pygame.image.load('pyfiles/images/click_button.png')
if event.type == pygame.MOUSEBUTTONUP:
settings.money += settings.income
else:
coin.image = pygame.image.load('pyfiles/images/click_button_grey.png')
Using my current code, how can I add that kind of effect?
See How to make image stay on screen in pygame?.
Use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called. When the coin is clicked, calculate the point in time after that the text image has to be removed. Add random coordinates and the time to the head of a list:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
# [...]
if event.type == pygame.MOUSEBUTTONDOWN:
if coin_rect.collidepoint(event.pos):
pos = ... # random position
end_time = current_time + 1000 # 1000 milliseconds == 1 scond
text_pos_and_time.insert(0, (pos, end_time))
Draw the text(s) in the main application loop. Remove the text when the time has expired from the tail of the list:
for i in range(len(text_pos_and_time)):
pos, text_end_time = text_pos_and_time[i]
if text_end_time > current_time:
window.blit(text, text.get_rect(center = pos))
else:
del text_pos_and_time[i:]
break
Minimal example:
import pygame
import random
pygame.init()
window = pygame.display.set_mode((400, 400))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
coin = pygame.Surface((160, 160), pygame.SRCALPHA)
pygame.draw.circle(coin, (255, 255, 0), (80, 80), 80, 10)
pygame.draw.circle(coin, (128, 128, 0), (80, 80), 75)
cointext = pygame.font.SysFont(None, 80).render("10", True, (255, 255, 0))
coin.blit(cointext, cointext.get_rect(center = coin.get_rect().center))
coin_rect = coin.get_rect(center = window.get_rect().center)
text = font.render("+10", True, (0, 255, 0))
text_pos_and_time = []
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if coin_rect.collidepoint(event.pos):
pos = pygame.math.Vector2(coin_rect.center) + pygame.math.Vector2(105, 0).rotate(random.randrange(360))
text_pos_and_time.insert(0, ((round(pos.x), round(pos.y)), current_time + 1000))
window.fill(0)
window.blit(coin, coin_rect)
for i in range(len(text_pos_and_time)):
pos, text_end_time = text_pos_and_time[i]
if text_end_time > current_time:
window.blit(text, text.get_rect(center = pos))
else:
del text_pos_and_time[i:]
break
pygame.display.flip()
pygame.quit()
exit()

I'n creating my first game in pygame and i need help on showing up a screen when i press any key [duplicate]

This question already has answers here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
As i mention, i'm super new in pygame and need help with this. I'm just testing the pygame commands, and want to show up a white screen with a message whenever i initialize the game and press any key, but apparently, it's not working. Here's my code:
# pygame template
import pygame
# import random
WIDTH = 400
HEIGHT = 500
FPS = 60
TITLE = 'My Game'
FONT_NAME = 'SNAKE/DinoTopia.ttf'
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
CLOCK = pygame.time.Clock()
# classes
class Main:
def __init__(self):
self.running = False
self.game_font = pygame.font.match_font(FONT_NAME)
def show_screen(self):
if self.running is True:
SCREEN.fill(WHITE)
self.draw_text('HELLO', 50, WIDTH/2, HEIGHT/2, BLUE)
pygame.display.flip()
self.wait_for_key()
def wait_for_key(self):
for key in pygame.event.get():
if key.type == pygame.KEYUP:
self.running = True
self.show_screen()
def draw_text(self, text, size, x, y, color):
font = pygame.font.Font(self.game_font, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
SCREEN.blit(text_surface, text_rect)
g = Main()
# game loop
running = True
while running:
# keep loop running at the right speed
CLOCK.tick(FPS)
# process input
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# update
# draw/ render
SCREEN.fill(BLACK)
g.wait_for_key()
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
i know something may be wrong with the wait_for_key function but i can't see what it is, so a little help would be nice! thanks in advance!
show screen function is only called when a key is up. A single frame. You have to call it every frame. Also don't call pygame.event.get and pygame.display.flip more than once.
# pygame template
import pygame
# import random
WIDTH = 400
HEIGHT = 500
FPS = 60
TITLE = 'My Game'
FONT_NAME = 'SNAKE/DinoTopia.ttf'
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
CLOCK = pygame.time.Clock()
# classes
class Main:
def __init__(self):
self.running = False
self.game_font = pygame.font.match_font(FONT_NAME)
def show_screen(self):
if self.running:
SCREEN.fill(WHITE)
self.draw_text('HELLO', 50, WIDTH/2, HEIGHT/2, BLUE)
def wait_for_key(self, events):
for event in events:
if event.type == pygame.KEYUP:
self.running = True
def draw_text(self, text, size, x, y, color):
font = pygame.font.Font(self.game_font, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
SCREEN.blit(text_surface, text_rect)
g = Main()
# game loop
running = True
while running:
# keep loop running at the right speed
CLOCK.tick(FPS)
# process input
events = pygame.event.get()
for event in events:
# check for closing window
if event.type == pygame.QUIT:
running = False
# update
# draw/ render
SCREEN.fill(BLACK)
g.wait_for_key(events)
g.show_screen()
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()

Comparing keypressed to a char

I want to make some sort of typing game in python using pygame. So, if the key pressed character is the same as the character in the word, it should return true... Is there any way to do this in python?
For example:
the word is "cat", if the user presses the key 'c', then it returns true... and so on for the rest of the characters.
here's my main.py file
from time import sleep
import pygame
import random
import winsound
from words import Words
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
done = False
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
w1 = Words(screen) #making a single word (for now) to see if typing works
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(WHITE)
w1.draw()
#attempting to write code here to compare word and user input
pygame.display.flip()
clock.tick(60)
pygame.init()
exit()
here's my words.py file
from random_words import RandomWords
import pygame
import random
from queue import *
rw = RandomWords()
class Words():
def __init__(self, screen):
self.screen = screen
self.x_point = 400
self.y_point = 400
self.word = rw.random_word() #generates a random word
self.queue = Queue() #was hoping to use the queue so that if the user types the char correctly in the right order, then the letter would change color or something (but that's further down the line)
for c in self.word: #iterate through randomized word..
self.queue.put(c) #add each char in randomized word to queue, for typing reasons
def getY(self):
return self.y_point
def draw(self):
#creates a new object
myfont = pygame.font.SysFont('Comic Sans MS' ,30)
#creates a new surface with text drawn on it
textsurface = myfont.render(self.word, False, (0,0,0))
self.screen.blit(textsurface,(self.x_point,self.y_point))
Event KEYDOWN has event.unicode, event.key, event.mod
You can compare
if event.type == pygame.KEYDOWN:
if event.unicode == "a":
or even
if event.type == pygame.KEYDOWN:
if event.unicode.lower() == "a":
to check "a" and "A"
To check char in word
if event.type == pygame.KEYDOWN:
if event.unicode.lower() in your_word.lower():
Example code use event.unicode to render text with pressed keys.
BTW: It is not some Entry widget so it doesn't delete char when you press backspace.
import pygame
# --- constants ---
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 200
FPS = 5 # `FPS = 25` is enough for human eye to see animation.
# If your program don't use animation
# then `FPS = 5` or even `FPS = 1` can be enough
# --- main ---
# - init -
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
screen_rect = screen.get_rect()
# - objects -
font = pygame.font.SysFont(None, 30)
text = ""
text_image = font.render(text, True, GREEN)
text_rect = text_image.get_rect() # get current size
text_rect.center = screen_rect.center # center on screen
# - mainloop -
clock = pygame.time.Clock()
done = False
while not done:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
text += event.unicode
text_image = font.render(text, True, GREEN)
text_rect = text_image.get_rect() # get current size
text_rect.center = screen_rect.center # center on screen
# - draws -
screen.fill(BLACK)
screen.blit(text_image, text_rect)
pygame.display.flip()
clock.tick(FPS)
# - end -
pygame.quit() # <-- quit(), not init()

How to create a pause button in Pygame?

I've been trying to make a game, and everything in there works so far except that the pause button , that when pressed the button P should pause and when pressed S should continue. I kinda understand the problem such that once in enters the while loop in the main code it wont get out. I tried putting the pause function inside the while loop. Please do help or provide tips to fix if possible thank you.
import pygame
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
Blue = (2,55,55)
def recursive_draw(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, WHITE,
[x, y, width, height],
1)
speed = [10,0]
rect_change_x = 10
rect_change_y = 10
# Is the rectangle wide enough to draw again?
if (width > 25):
# Scale down
x += width * .1
y += height * .1
width *= .8
height *= .8
# Recursively draw again
recursive_draw(x, y, width, height)
def recursive_draw2(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, Blue,
[x, y, width, height],
1)
speed = [10,0]
rect_change_x = 10
rect_change_y = 10
# Is the rectangle wide enough to draw again?
if (width > 25):
x += width * .1
y += height * .1
width *= .8
height *= .8
# Recursively draw again
recursive_draw2(x, y, width, height)
def paused():
screen.fill(black)
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()
#gameDisplay.fill(white)
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)
pygame.init()
#rectanglelist = [big()]
# Set the height and width of the screen
size = [700, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
black=(0,0,0)
end_it=False
time = 100
USEREVENT = 0
pygame.time.set_timer(USEREVENT+1, 10)
milliseconds = 0
seconds = 0
start_it = False
while (end_it==False):
screen.fill(black)
myfont=pygame.font.SysFont("Britannic Bold", 40)
nlabel=myfont.render("Welcome to "+ " Jet shooter ", 1, (255, 0, 0))
label=myfont.render("Click on the mouse to start ", 1, (255, 0, 0))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
end_it=True
screen.blit(nlabel,(200, 100))
screen.blit(label, (170,300))
pygame.display.flip()
while (start_it==False):
screen.fill(black)
myfont2=pygame.font.SysFont("Britannic Bold", 40)
label2=myfont2.render("Ready?", 1, (255, 0, 0))
screen.blit(label2, (300,250))
pygame.display.flip()
pygame.time.wait(3000)
start_it = True
fall = False
while (fall==False):
nlist = [3,2,1]
for i in (nlist):
screen.fill(black)
n = str(i)
myfont3=pygame.font.SysFont("Britannic Bold", 40)
score = myfont3.render(n,1,(255,0,0))
screen.blit((score), (350,250))
pygame.display.flip()
pygame.time.wait(1000)
screen.fill(black)
myfont4=pygame.font.SysFont("Britannic Bold", 40)
label4=myfont3.render("GOOO!!!", 1, (255, 0, 0))
screen.blit(label4, (300,250))
pygame.display.flip()
pygame.time.wait (1000)
fall = True
pause = 0
b = 0
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYUP:
if event.key==K_p:
pause=True
if pause == True:
screen.fill(black)
font=pygame.font.SysFont("Britannic Bold", 40)
nlabelBB=myfont.render("Pause", 1, (255, 0, 0))
screen.blit(nlabelBB,(200, 100))
pygame.display.flip()
# Set the screen background
screen.fill(BLACK)
flip = 1
a = 0
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
recursive_draw(0, 0, 700, 500)
recursive_draw2(35,25, 625, 450)
**###I TRIED TO PUT THE PAUSE GAME HERE AND IF PRESSED P PAUSE AND S CONTINUE
while a == 0 :
if flip == 1 :
recursive_draw(35,25,625,450)
recursive_draw2(0, 0, 700, 500)
flip = flip + 1
pygame.display.flip()
if event.type == pygame.KEYUP:
if event.key==K_p:
a = 1
screen.fill(black)
font=pygame.font.SysFont("Britannic Bold", 40)
nlabelBB=myfont.render("Pause", 1, (255, 0, 0))
screen.blit(nlabelBB,(200, 100))
pygame.display.flip()
if event.key==K_s:
a = 0
if flip == 2 :
recursive_draw(0, 0, 700, 500)
recursive_draw2(35, 25, 625, 450)
flip = flip - 1
pygame.display.flip()
if event.type == pygame.KEYUP:
if event.key==K_p:
a = 1
screen.fill(black)
font=pygame.font.SysFont("Britannic Bold", 40)
nlabelBB=myfont.render("Pause", 1, (255, 0, 0))
screen.blit(nlabelBB,(200, 100))
pygame.display.flip()
if event.key==K_s:
a = 0**
if event.type == pygame.QUIT:
done = True
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(20)
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()
Just use a single game loop for everything and keep track of the current state (e.g. main menu, pause screen, game scene) of your game..
Here's an example where we keep track of the state by a simple variable called state and act in our game loop accordingly:
import pygame, math, itertools
def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def sub(u, v):
return [u[i]-v[i] for i in range(len(u))]
def normalize(v):
return [v[i]/magnitude(v) for i in range(len(v))]
pygame.init()
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
path = itertools.cycle([(26, 43), (105, 110), (45, 225), (145, 295), (266, 211), (178, 134), (250, 56), (147, 12)])
target = next(path)
ball, speed = pygame.rect.Rect(target[0], target[1], 10, 10), 3.6
pause_text = pygame.font.SysFont('Consolas', 32).render('Pause', True, pygame.color.Color('White'))
RUNNING, PAUSE = 0, 1
state = RUNNING
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT: break
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_p: state = PAUSE
if e.key == pygame.K_s: state = RUNNING
else:
screen.fill((0, 0, 0))
if state == RUNNING:
target_vector = sub(target, ball.center)
if magnitude(target_vector) < 2:
target = next(path)
else:
ball.move_ip([c * speed for c in normalize(target_vector)])
pygame.draw.rect(screen, pygame.color.Color('Yellow'), ball)
elif state == PAUSE:
screen.blit(pause_text, (100, 100))
pygame.display.flip()
clock.tick(60)
continue
break
As you can see, the rectangle keeps moving until you press P, which will change the state to PAUSE; and a simple message will now be displayed instead of drawing/moving the rectangle further.
If you press S the state switches back to the normal mode; all done in a single game loop.
Further reading:
Pygame level/menu states
Mulitple Displays in Pygame
Trying to figure out how to track Pygame events and organize the game's functions

Categories