How do I display text on the screen in pygame [duplicate] - text

This question already has answers here:
pygame - How to display text with font & color?
(7 answers)
Closed 1 year ago.
My question is all I want to do is display text on the screen in pygame. If someone known how to do this please tell me!
My code
import time
import pygame
from pygame.locals import *
pygame.init
blue = (0,0,255)
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit
exit()
font = pygame.font.SysFont(None, 25)
def show_text(msg,color):
text = font.render(msg,True,color)
WINDOW.blit(text,[WINDOW_WIDTH/2,WIDTH_HEIGHT/2])
show_text("This is a message!", blue)
pygame.display.update()
I want to just make text that says "This is a message!". That is all

You are pretty close already. To render text you need to first define a font, then use it to render(). This creates a bitmap with the text in it, which needs to be blit() to the window.
All the necessary parts are in the question-code, they are just a bit mixed-up.
import time
import pygame
from pygame.locals import *
# Constants
blue = (0,0,255)
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
def show_text( msg, color, x=WINDOW_WIDTH//2, y=WINDOW_WIDTH//2 ):
global WINDOW
text = font.render( msg, True, color)
WINDOW.blit(text, ( x, y ) )
pygame.init()
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")
# Create the font (only needs to be done once)
font = pygame.font.SysFont(None, 25)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
WINDOW.fill( ( 255, 255, 255 ) ) # fill screen with white background
show_text("This is a message!", blue)
pygame.display.update()

Related

My score system in Pygame overlaps over and over again [duplicate]

This question already has an answer here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
Closed 2 years ago.
I have looked at many YouTube videos and information online but is seems I can't find the answer. Every time I run the code the text appears with a zero but when clicking the enemy to earn points the number 1 overlaps with the zero and it doesn't change. This problem repeats over and over again. What do/can I do? I am new to the python code and there might be some unnecessary code so please bare that in mind if you see a rookie mistake thank you.
import pygame
import time
import random
pygame.init()
from pygame.locals import *
white = (255,255,255)
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Extended Essay game")
BADGUY = pygame.image.load('enemy.png')
pygame.font.init()
#Enemy char
class Enemy():
def __init__(self, x, y):
self.x = x
self.y = y
def main():
run = True
FPS = 60
x = 0
enemies = 0
clock = pygame.time.Clock()
font = pygame.font.Font('freesansbold.ttf', 32)
window.fill((255,255,255))
window.blit(BADGUY,(0,0))
def update():
text = font.render("Enemies: " + str(enemies), True, (0,0,0))
window.blit(text, (200, 300))
pygame.display.update()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
window.blit(BADGUY, (random.randint(0, 700), random.randint(0 , 700)))
enemies += 1
update()
main()
You need to clear the screen before putting new stuff on it. Put this at the beginning of update() or right before it is called in the loop:
window.fill((255, 255, 255))

Pygame - put updating mouse coords on the screen

Can anyone help me figure out how to put constantly updating ouse coords in the upper right corner of the screen? I think it would be a big help to have it there just for dev purposes, but I cant figure it out. Here is my code so far:
'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 17 20:26:57 2020
#author: wohlsr
"""
import pygame
from pygame.locals import *
from sys import exit
background_image_filename = ('menu-start.jpg')
mouse_image_filename = ('mouse-pointer.png')
icon = pygame.image.load('go-stop-icon.png')
pygame.init()
screen = pygame.display.set_mode((1024, 768), 0, 32)
pygame.display.set_caption("Gostop")
pygame.display.set_icon(icon)
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
pygame.mouse.set_visible(0)
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
'''
Visual of what I have so far
This code puts the mouse position in the top right corner of the screen.
import pygame
from pygame.locals import *
from sys import exit
background_image_filename = ('menu-start.jpg')
mouse_image_filename = ('mouse-pointer.png')
icon = pygame.image.load('go-stop-icon.png')
pygame.init()
screen = pygame.display.set_mode((1024, 768), 0, 32)
pygame.display.set_caption("Gostop")
pygame.display.set_icon(icon)
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
font=pygame.font.SysFont('arial',20,True,False) # font for mouse position
def showcoords(screen,x,y):
q1Text= font.render("{} {}".format(int(x),int(y)).center(20),1,(0,0,0)) # surface with coord text
bg = q1Text.copy() # copy surface for background
bg.fill((0,100,100)) # background
textRect = q1Text.get_rect()
textRect.topright = ((1024,0)) # put in top\right corner
screen.blit(bg,textRect) # draw background
screen.blit(q1Text,textRect) # draw coords
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
pygame.mouse.set_visible(0)
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
showcoords(screen,x,y) # show mouse coords
pygame.display.update()
If you want to use the global x,y values without passing parameters, make these changes:
def showcoords(screen):
global x,y # use existing x,y values
.......
showcoords(screen) # show mouse coords
Output

How to prompt user to open a file with python3?

I'm making a game and I want the user to be able to click a button which opens the file manager and asks them to open a game save file. Is there a module / how could I put this in my game? If there's no good gui way how would I make a text input thing (without using the terminal)? Thanks!
Pygame is a low-level library, so it doesn't have the kind of built-in dialogs you're after. You can create such, but it will be quicker to use the tkinter module which is distributed with Python and provides an interface to the TK GUI libraries. I'd recommend reading the documentation, but here's a function that will pop up a file selection dialog and then return the path selected:
def prompt_file():
"""Create a Tk file dialog and cleanup when finished"""
top = tkinter.Tk()
top.withdraw() # hide window
file_name = tkinter.filedialog.askopenfilename(parent=top)
top.destroy()
return file_name
Here's a small example incorporating this function, pressing Spacebar will popup the dialog:
import tkinter
import tkinter.filedialog
import pygame
WIDTH = 640
HEIGHT = 480
FPS = 30
def prompt_file():
"""Create a Tk file dialog and cleanup when finished"""
top = tkinter.Tk()
top.withdraw() # hide window
file_name = tkinter.filedialog.askopenfilename(parent=top)
top.destroy()
return file_name
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
f = "<No File Selected>"
frames = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
f = prompt_file()
# draw surface - fill background
window.fill(pygame.color.Color("grey"))
## update title to show filename
pygame.display.set_caption(f"Frames: {frames:10}, File: {f}")
# show surface
pygame.display.update()
# limit frames
clock.tick(FPS)
frames += 1
pygame.quit()
Notes: This will pause your game loop, as indicated by the frame counter but as events are being handled by the window manager, this shouldn't be an issue.
I'm not sure why I needed the explicit import tkinter.filedialog, but I get an AttributeError if I don't.
As for string entry in pygame, you might want to do this natively, in which case you'd be handling KEYUP events for letter keys to build the string and perhaps finishing when the user presses Enter or your own drawn button. You could continue down the tk path, in which case you'll want to use something like tkinter.simpledialog.askstring(…)
It is possible to make a file dialogue (though not using the native file explorer) using the pygame_gui module.
Simply create an instance of UIFileDialog and grab the path when the user hits 'ok':
file_selection = UIFileDialog(rect=Rect(0, 0, 300, 300), manager=manager, initial_file_path='C:\\')
if event.ui_element == file_selection.ok_button:
file_path = file_selection.current_file_path
If you want to allow selecting a directory set allow_picking_directories to True, but note that it does not allow picking an initial_file_path.
file_selection = UIFileDialog(rect=Rect(0, 0, 300, 300), manager=manager, allow_picking_directories=True)
Here's the above code in a simple program that allows you to pick a file when the button is clicked:
#!/usr/bin/env python
import pygame
import pygame_gui
from pygame_gui.windows.ui_file_dialog import UIFileDialog
from pygame_gui.elements.ui_button import UIButton
from pygame.rect import Rect
pygame.init()
window_surface = pygame.display.set_mode((800, 600))
background = pygame.Surface((800, 600))
background.fill(pygame.Color('#000000'))
manager = pygame_gui.UIManager((800, 600))
clock = pygame.time.Clock()
file_selection_button = UIButton(relative_rect=Rect(350, 250, 100, 100),
manager=manager, text='Select File')
while 1:
time_delta = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
if event.ui_element == file_selection_button:
file_selection = UIFileDialog(rect=Rect(0, 0, 300, 300), manager=manager, allow_picking_directories=True)
if event.ui_element == file_selection.ok_button:
print(file_selection.current_file_path)
manager.process_events(event)
manager.update(time_delta)
window_surface.blit(background, (0, 0))
manager.draw_ui(window_surface)
pygame.display.update()

name 'win' is not defined - pygame

I'm trying to implement some text into my game. I've followed a tutorial that has led me to this
pygame.font.init()
gamefont = pygame.font.SysFont('Bahnschrift', 16)
text = gamefont.render("Round: ", 1, (0,0,0))
win.blit(text, (390, 10))
However, when I run my code, it says that the name 'win' is not defined. I was wondering if anyone knew how to fix this?
win is the pygame.Surface object which is associated to the window.
Somewhere you have t o initialize pygame (pygame.init()) and to create the window Surface (pygame.display.set_mode):
Minimal applicaiton:
import pygame
# initializations
pygame.init()
win = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
# create font ad render text
pygame.font.init()
gamefont = pygame.font.SysFont('Bahnschrift', 16)
text = gamefont.render("Round: ", 1, (0,0,0))
# main application loop
run = True
while run:
clock.tick(60)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# clear the display
win.fill((255, 255, 255))
# draw the text
win.blit(text, (390, 10))
# update the display
pygame.display.flip()

Python /Pygame blitting multiple image to list coordinates

So i'm making a space game where you have a open world to explore (A black Screen)
and i wanna create planets(Blit images to screen) around the universe(from a list).
This is my code currently
star = pygame.image.load("star.png")
planets = random.randrange(100,500) #<------#####NOT IMPORTANT#######
positions = [(300,50),(400,27),(900,55)] #<------
position = ()
positions has coorinates where images should be blitted
but when i blit them
for position in positions:
ikkuna.blit(star, position)
it blits the first one or nothing and does not crash
why?
################################################-
Here is the full code if it helps (there is bits of the finish language in there hope it does not bother)
"ikkuna = screen (leveys,korkeus) = (width,hight) toiminnassa = in action"
import pygame
import random
import time
import sys
import math
pygame.init()
White = (255,255,255)
red = (255,0,0)
kello = pygame.time.Clock()
star = pygame.image.load("star.png")
planets = random.randrange(100,500)
positions = [(300,50)]
position = ()
tausta_vari = (255,255,255)
(leveys, korkeus) = (1000, 1000)
ikkuna = pygame.display.set_mode((leveys, korkeus))
pygame.display.set_caption("SpaceGenerationTest")
######################################################################
toiminnassa = True
while toiminnassa:
for event in pygame.event.get():
if event.type == pygame.QUIT:
toiminnassa = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_g:
print("Generating World....")
print(planets)
for position in positions:
ikkuna.blit(star, position)
print("hello")
There's some problems with your code:
Your not updating the display, which means that all your changes won't be visible. Use pygame.display.update() or pygame.display.flip() at the end of the game loop to update the screen.
When you're mixing English and Finnish it becomes very inconsistent and hard to follow, especially for people who don't speak Finnish. Try to use English, even when you're just practicing.
Your full example only contain one position in the list, thus it's only creating one star at one position.
Pressing the 'g'-key won't generate any planets. You might want to introduce a boolean variable like in the example below.
I changed your code to english and made some adjustment so it's more consistent.
import pygame
import random
pygame.init()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# I changed the background color to black, because I understood it as that is what you want.
BACKGROUND_COLOR = (0, 0, 0) # tausta_vari
clock = pygame.time.Clock() # kello
star = pygame.Surface((32, 32))
star.fill((255, 255, 255))
planets = random.randrange(100, 500)
positions = [(300, 50), (400, 27), (900, 55)]
WIDTH, HEIGHT = (1000, 1000) # (leveys, korkeus)
screen = pygame.display.set_mode((WIDTH, HEIGHT)) # ikkuna
pygame.display.set_caption("SpaceGenerationTest")
display_stars = False
running = True # toiminnassa
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_g:
print("Generating World....")
print(planets)
display_stars = True
screen.fill(BACKGROUND_COLOR)
if display_stars:
for position in positions:
# This will create 3 stars because there're 3 elements in the list positions.
# To create more stars you'll need to add more in the list positions.
screen.blit(star, position)
pygame.display.update()
Your blitting all your images to the exact same position: positions = [(300, 50)], so the last image covers all the other images up. Also, you may not know this, but to display anything in pygame you have to either call pygame.display.flip() or pygame.display.update() after you finish drawing. I made a few revisions to your code, so the stars should show-up:
import pygame
import random
import time
import sys
import math
def main():
pygame.init()
White = (255,255,255)
red = (255,0,0)
kello = pygame.time.Clock()
star = pygame.image.load("star.png")
planets = random.randrange(100,500)
positions = [(300,50), (310, 60), (320, 80), (607, 451), (345, 231)]
tausta_vari = (255,255,255)
(leveys, korkeus) = (1000, 1000)
ikkuna = pygame.display.set_mode((leveys, korkeus))
pygame.display.set_caption("SpaceGenerationTest")
######################################################################
toiminnassa = True
while toiminnassa:
for event in pygame.event.get():
if event.type == pygame.QUIT:
toiminnassa = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_g:
print("Generating World....")
print(planets)
ikkuna.fill((0, 0, 0)) # fill the screen with black
for position in positions:
ikkuna.blit(star, position)
print("Hello")
pygame.display.flip() # updating the screen
if __name__ == '__main__': # are we running this .py file as the main program?
try:
main()
finally:
pg.quit()
quit()
~Mr.Python

Resources