I'm writing a basic program with pygame that in some part needs to take an text input from the user. My problem is that when the user wants to erase part of the text, the old text keeps displaying it in the pygame window.
Let's say the user types '23' and then presses backspace. The console shows 2 but the pygame window will keep displaying 23.
I'm using:
if event.key == pg.K_BACKSPACE:
text = text[:-1]
You have to (re)render the text surface after changing the text and you have to clear the display in every frame:
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((400, 200))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
text = ""
text_surf = font.render(text, True, (0, 0, 0))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
text = text[:-1]
else:
text += event.unicode
text_surf = font.render(text, True, (0, 0, 0))
window_center = window.get_rect().center
window.fill((255, 255, 255))
window.blit(text_surf, text_surf.get_rect(center = window_center))
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
The typical PyGame application loop has to:
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
Related
I an having an error with MOUSEBUTTONDOWN giving an error when used.
Here is the error:
if event.type == MOUSEBUTTONDOWN:
NameError: name 'MOUSEBUTTONDOWN' is not defined
Here is the code that is giving the error:
import pygame
import random
import sys
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.init()
# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
screen.fill(WHITE)
# --- Drawing code should go here
monospace = pygame.font.SysFont("Berlin Sans FB", 169)
label = monospace.render("test", 1, (0, 0, 0))
screen.blit(label, (100, 100))
button_rect = pygame.Rect(0, 0, 50, 50) # start button rectangle
abort = False
start = False
while not abort and not start:
for event in pygame.event.get():
if event.type == pygame.QUIT:
abort = True
if event.type == MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
start = True
# draw title screen
# [...]
done = abort
while not done:
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
pygame.quit()
All the other sources on Stack Overflow about this topic that I can find all talk about errors where MOUSEBUTTONDOWN already works.
Also note that I am using Pycharm.
Either pygame.MOUSEBUTTONDOWN instead of MOUSEBUTTONDOWN or from pygame.locals import *
You need only one application loop:
import pygame
from pygame.locals import *
import random
import sys
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.init()
# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("game")
clock = pygame.time.Clock()
monospace = pygame.font.SysFont("Berlin Sans FB", 169)
label = monospace.render("test", 1, (0, 0, 0))
button_rect = pygame.Rect(0, 0, 50, 50) # start button rectangle
abort = False
start = False
while not abort:
for event in pygame.event.get():
if event.type == pygame.QUIT:
abort = True
if event.type == MOUSEBUTTONDOWN:
if not start and button_rect.collidepoint(event.pos):
start = True
screen.fill(WHITE)
if not start:
# draw title screen
pygame.draw.rect(screen, "red", button_rect)
else:
# draw game
# [...]
screen.blit(label, (100, 100))
pygame.display.flip()
clock.tick(60)
pygame.quit()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()
Solution found:
I did not have the needed libraries imported:
For MOUSEBUTTONDOWN to work you need to use:
from pygame.locals import *
Credit to #Rabbid76 for answering in comments.
So when I set
while not game_over = False
, my window opens properly, but the text doesn't show. Whereas if I set it to True, the text shows but window closes immediately.
Here's the code:
***#Write a Python program to create a simple math quiz.
#Importing libraries
import pygame
import sys
import math
from pygame.locals import *
#Initialising fonts
pygame.init()
pygame.font.init()
#Assigning variables
WIDTH = 600
HEIGHT = 600
#Other important things
background_color = (127,255,0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
pygame.display.set_caption("Math Game")
screen.fill(background_color)
pygame.display.flip()
font = pygame.font.Font("freesansbold.ttf", 40)
textX=10
textY=10
def show_text(x,y):
text=font.render("Math Game", True, (0,0,0))
screen.blit(text,(x,y))
"""
#Adding the Calculator bit
x = input("Enter Your First Nummber To Add: ")
y = input("Enter Your Second Number To Add: ")
z = str(int(x)+int(y))
print(z)
"""
#Game loop
game_over = True
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
show_text(textX, textY)
pygame.display.update()***
It is a matter of Indentation. show_text and pygame.display.update() must be called in the application loop instead of after the application loop.
Additionally you should clear the display in the application loop.
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# INDENTATION
#-->|
screen.fill(background_color)
show_text(textX, textY)
pygame.display.update()
The typical PyGame application loop has to:
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
I am making a text based RPG as my first python/pygame project. In my game I would like to present the player with choices then ask them to type it in. I was able to download and import a module which accepts user input and displays it on the screen. However, before using it for anything like..lets say, if the user input is 'yes', then they go to a new area, I'd like the program to only accept the user input once they hit the enter key. I believe the tutorial for the textinput module I downloaded has directions to do this, but to be honest I just don't understand what it's saying. I've tried multiple types of loops but nothing is happening. Any help will be appreciated. Here is my main game code:
import pygame_textinput
import pygame
pygame.init()
#fps
clock=pygame.time.Clock()
# create font here
font_name = pygame.font.get_default_font()
WHITE_TEXT_COLOR = (255, 255, 255)
# create screen and window and display and font here
screen_width, screen_height = 800, 700
background_color_black = (0, 0, 0)
screen = pygame.display.set_mode((screen_width, screen_height))
our_game_display = pygame.Surface((screen_width, screen_height))
pygame.display.set_caption('MyRPGGame')
#create text input object
textinput = pygame_textinput.TextInput()
def draw_text(text, size, x, y):
pygame.font.init()
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE_TEXT_COLOR)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
our_game_display.blit(text_surface, text_rect)
def choose_to_play():
draw_text("You've decided to play",20,screen_width/2,screen_height/2+50)
def first_area():
our_game_display.fill(background_color_black)
draw_text('The story of this game depends on your choices. Do you wish to play?', 20, screen_width / 2,screen_height / 2 - 100)
draw_text('Type your answer and hit enter.', 20, screen_width / 2,screen_height / 2 - 50)
draw_text('Yes', 20, screen_width/2,screen_height/2+50)
draw_text('No', 20, screen_width/2,screen_height/2+100)
screen.blit(our_game_display, (0, 0))
pygame.display.update()
while True:
our_game_display.fill((background_color_black))
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
first_area()
# Feed it with events every frame
textinput.update(events)
# Blit its surface onto the screen
screen.blit(textinput.get_surface(), (10, 600))
pygame.display.update()
clock.tick(30)
Now here is the source for the pygame textinput module, figured I would link to the code so this post isn't too crowded:
https://github.com/Nearoo/pygame-text-input
You need to a variable for the state of the game. Once enter is pressed change the state. Implement different cases in the application loop depending on the state of the game::
game_state = 'start'
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
game_state = 'input'
our_game_display.fill((background_color_black))
if game_state == 'input':
textinput.update(events)
# [...]
This question already has answers here:
pygame - How to display text with font & color?
(7 answers)
Closed 1 year ago.
import pygame, sys
pygame.init()
clock = pygame.time.Clock()
coordinate = pygame.mouse.get_pos()
screen = pygame.display.set_mode((1000,800), 0, 32)
pygame.display.set_caption("Mouse Tracker")
font = pygame.font.Font(None, 25)
text = font.render(coordinate, True, (255,255,255))
while True:
screen.fill((0,0,0))
screen.blit(text, (10, 10))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
clock.tick(60)
I am trying to make a program that tracks your mouse and shows the coordinates of it on the sreen. I get an error saying:
text = font.render(coordinate, True, (255,255,255))
TypeError: text must be a unicode or bytes.
I am using Python 3.9.1
There are couple of changes to be made:
coordinate = pygame.mouse.get_pos() returns a tuple which the variable coordinate is assigned to. The font.render() method takes a string as an argument not a tuple. So first you need to render the str(coordinate) and not just the coordinate which is actually a tuple. You can read more about rendering the font in pygame here
text = font.render(str(coordinate), True, (255,255,255)) #Rendering the str(coordinate)
Step one alone won't make your code functional, there are still some problems in your code. For blitting the coordinate of the mouse to the screen, you need to get the mouse coordinates at every single frame. For that to function you need to place the line coordinate = pygame.mouse.get_pos() in the while True loop, along with this you also need to place this line text = font.render(str(coordinate), True, (255,255,255)) in the while loop
import pygame,sys
#[...]#part of code
while True:
coordinate = pygame.mouse.get_pos() #Getting the mouse coordinate at every single frame
text = font.render(str(coordinate), True, (255,255,255))
#[...] other part of code
So the final working code should look somewhat like:
import pygame, sys
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((1000,800), 0, 32)
pygame.display.set_caption("Mouse Tracker")
font = pygame.font.Font(None, 25)
while True:
coordinate = pygame.mouse.get_pos() #Getting the mouse coordinate at every single frame
text = font.render(str(coordinate), True, (255,255,255)) #Rendering the str(coordinate)
screen.fill((0,0,0))
screen.blit(text, (10, 10))
for event in pygame.event.get():
if event.type == pygame.QUIT:#
pygame.quit()
sys.exit()
pygame.display.update()
clock.tick(60)
This question already has answers here:
Why doesn't PyGame draw in the window before the delay or sleep?
(1 answer)
How to wait some time in pygame?
(3 answers)
Closed 2 years ago.
I was trying to use pygame to create a script that upon clicking run. The window changes the colours of the screen to blue, grey, red with one second delays between them, and then exit out of that loop and then run the game as per normal being the print("cycle done") code. Unfortunately what happens is that the window opens, hangs for around 3 seconds and then shows a red screen, rather than going through each of the colours.
import pygame as pg
running = True
calibration = False
pg.init()
screen = pg.display.set_mode((600, 400))
screen_rect = screen.get_rect()
clock = pg.time.Clock()
timer = 0
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if not calibration:
pg.time.wait(1000)
screen.fill(blue)
pg.display.flip()
pg.time.wait(1000)
screen.fill(green)
pg.display.flip()
pg.time.wait(1000)
screen.fill(red)
pg.display.flip()
calibration = True
print(calibration)
print("cycle done")
clock.tick(60)
If you just wait for some time, you can use pygame.time.wait or pygame.time.delay. However, if you want to display a message and then wait some time, you need to update the display beforehand. The display is updated only if either pygame.display.update() or pygame.display.flip()
is called. See pygame.display.flip():
This will update the contents of the entire display.
Further you've to handles the events with pygame.event.pump(), before the update of the display becomes visible in the window. See pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
This all means that you have to call pygame.display.flip() and pygame.event.pump() before pygame.time.wait():
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if not calibration:
pygame.event.pump()
pg.time.wait(1000)
screen.fill(blue)
pg.display.flip()
pygame.event.pump()
pg.time.wait(1000)
screen.fill(green)
pg.display.flip()
pygame.event.pump()
pg.time.wait(1000)
screen.fill(red)
pg.display.flip()
pygame.event.pump()
pg.time.wait(1000)
calibration = True
print(calibration)
print("cycle done")
clock.tick(60)