Why is pygame display not bliting properly? - python

I am trying to make a tile-based 2d platformer in Python with Pygame. I've started with just creating the window and tile system. It refers to a text file, and based on each number found in the file, blits an image to the Pygame display window("2" for grass image, "1" for dirt image). When the program is executed, the tiles appear on the screen but rapidly flash and move slowly to one side. There are also gaps in between the tiles too, which I am not sure why they are there, but I want to get rid of them.
import pygame, sys
pygame.init()
dirt_img = pygame.image.load("dirt2.png") #loads dirt image
dirt_img = pygame.transform.scale(dirt_img, (80,80)) #scales dirt image up to 80*80
grass_img = pygame.image.load("grass2.png") #loads grass image
grass_img = pygame.transform.scale(grass_img, (80,80)) #scales grass image up to 80*80
clock = pygame.time.Clock()
window = pygame.display.set_mode((1200, 800))
#load map
def load_map(path):
f = open(path + '.txt','r') #open text file
data = f.read() #reads it
f.close() #closes
data = data.split('\n') #splits the data by the new line character
game_map = [] #creates game map data
for row in data:
game_map.append(list(row)) #ads each line in'map.txt'..
#..data to new game map list
return game_map
game_map = load_map('map')
grass_count = 0 #meant to be used to count each time a grass tile is blitted to..
#..move the position over 80 pixles for the next tile to be blited
dirt_count = 0 # I think this might be where my problem is but I am not sure.
# Main loop
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
window.fill((135, 178,255)) #sets light Blue background color
for layer in game_map:
for tile in layer:
if tile == '1': #finds '1' in file,
dirt_count += 1 #updates dirt count,
window.blit(dirt_img, (100 * dirt_count + 80, 500))#blits next dirt tile
if tile == '2': #finds '2' in file,
grass_count += 1 #updates grass count,
window.blit(grass_img, (100 * grass_count + 80, 500))#blits next tile
clock.tick(60)
pygame.display.update()
pygame.quit()

The variable dirt_count and grass_count are incremented, but they are never changed back to 0. Set the variables to 0, right before the loop: grass_count = 0 grass_count = 0. Anyway, I don't think that this will satisfy you, since the coordinate of the tile doesn't seem to depend on it's index.
Most likely the position of the tile depends on the row an column:
for row, layer in enumerate(game_map):
for column, tile in enumerate(layer):
x, y = 80 + column * 100, 80 + row * 100
if tile == '1':
window.blit(dirt_img, (x, y))
if tile == '2':
window.blit(grass_img, (x, y))

Related

Generate tiles in piano tiles consecutively in pygame

I have created a simple piano tiles game clone in pygame.
Everything working fine except the way i am generating tiles after every certain interval, but as the game speed increases this leaves a gap between two tiles.
In the original version of the game, there's no lag (0 distance ) between two incoming tiles.
Here's a preview of the game:
Currently I am generating tiles like this:
ADDBLOCK = pygame.USEREVENT + 1
ADDTIME = 650
pygame.time.set_timer(ADDBLOCK, ADDTIME)
if event.type == ADDBLOCK:
x_col = random.randint(0,3)
block = Block(win, (67.5 * x_col, -120))
block_group.add(block)
But with time, these tiles speed increase so there's remain a gap between generation of two tiles as shown by red line in the preview. Is there any way to generate tiles consecutively?
Source Code
Use a variable number to know how many tiles have been generated since the start. This variable will start with 0, then you will add 1 to this variable every time a tile is generated.
Then, you can use a variable like scrolling which increases continuously. You will add this scrolling to every tile y pos to render them.
Now you just have to add a tile which y position is like -tile_height - tile_height * number.
If that doesn't make sense to you, look at this MRE:
import pygame
from pygame.locals import *
from random import randint
pygame.init()
screen = pygame.display.set_mode((240, 480))
clock = pygame.time.Clock()
number_of_tiles = 0
tile_height = 150
tile_surf = pygame.Surface((60, tile_height))
tiles = [] # [column, y pos]
scrolling = 0
score = 0
speed = lambda: 200 + 5*score # increase with the score
time_passed = 0
while True:
click = None # used to click on a tile
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == MOUSEBUTTONDOWN:
click = event.pos
screen.fill((150, 200, 255))
if scrolling > number_of_tiles * tile_height:
# new tile
# use "while" instead of "if" if you want to go at really high speed
tiles.append([randint(0, 3), -tile_height - number_of_tiles * tile_height])
number_of_tiles += 1
for x, y in tiles:
screen.blit(tile_surf, (60 * x, y + scrolling))
if y + scrolling > 480: # delete any tile that is no longer visible
tiles.remove([x, y])
if click is not None and Rect((60 * x, y + scrolling), tile_surf.get_size())
.collidepoint(click):
tiles.remove([x, y]) # delete any tile that has been clicked
score += 1 # used to calculate speed
scrolling += speed() * time_passed
pygame.display.flip()
time_passed = clock.tick() / 1000

Surface display able to properly represent opacity, but any other surface cannot

I am trying to make a tic-tac-toe game with pygame. An important thing I want is being able to make my images (eg. X and O) slightly translucent for when my user is only hovering over a grid tile. I also use opacity to visually show whose turn it is.
This is what I have tried:
x_tile = pygame.image.load('x_tile').convert()
x_tile.set_alpha(100)
This works fine when I'm blitting x_tile directly onto the display like this:
# This is for simplicity's sake. The actual blit process is all being done in an infinite loop
screen = pygame.display.set_mode((300, 300))
screen.blit(x_file, x_file.get_rect())
But my game is using another image that represents the grid, and that is what I'm blitting onto. So I'm blitting this board onto the display, then blitting the actual X and O tiles on the board.
screen = pygame.display.set_mode((300, 300))
screen.blit(board, board_rect)
board.blit(x_tile, x_tile.get_rect(center=grid[0].center)) # I have a list of Rects that make a grid on the board image. grid[0] is the top left
When I do it that way, x_tile.set_alpha(100) seems to have no effect and I don't know what to do.
Edit: I am using pygame 2.0.1. I'm on Windows 10.
Here is the entire code
import os
import pygame
from pygame.locals import *
# Game constants
WIN_SIZE = WIN_WIDTH, WIN_HEIGHT = 800, 600
BLACK = 0, 0, 0
WHITE = 255, 255, 255
RED = 255, 0, 0
BLUE = 0, 0, 255
# Game functions
class NoneSound:
"""dummy class for when pygame.mixer did not init
and there is no sound available"""
def play(self): pass
def load_sound(file):
"""loads a sound file, prepares it for play"""
if not pygame.mixer:
return NoneSound()
music_to_load = os.path.join('sounds', file)
try:
sound = pygame.mixer.Sound(music_to_load)
except pygame.error as message:
print('Cannot load following sound:', music_to_load)
raise SystemExit(message)
return sound
def load_image(file, colorkey=None, size=None):
"""loads image into game"""
image_to_load = os.path.join('images', file)
try:
image = pygame.image.load(image_to_load).convert()
except pygame.error as message:
print('Cannot load following image:', image_to_load)
raise SystemExit(message)
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
if size is not None:
image = pygame.transform.scale(image, size)
return image
# Game class
class TTTVisual:
"""Controls game visuals"""
def __init__(self, win: pygame.Surface):
self.win = win
# Load in game images
self.board = load_image('board.png', size=(600, 450), colorkey=WHITE)
self.x_tile = load_image('X_tile.png', size=(100, 100), colorkey=BLACK)
self.o_tile = load_image('O_tile.png', size=(100, 100), colorkey=BLACK)
# Translucent for disabled looking tile
self.x_tile_trans = self.x_tile.copy()
self.o_tile_trans = self.o_tile.copy()
self.x_tile_trans.set_alpha(100)
self.o_tile_trans.set_alpha(100)
# Used to let user know whose turn it is
self.x_turn = pygame.transform.scale(self.x_tile, (50, 50))
self.o_turn = pygame.transform.scale(self.o_tile, (50, 50))
self.x_turn_trans = pygame.transform.scale(self.x_tile_trans, (50, 50))
self.o_turn_trans = pygame.transform.scale(self.o_tile_trans, (50, 50))
self.get_rects()
self.grid = self.setup_grid()
def get_rects(self):
"""Creates coords for some visual game assets"""
self.board_rect = self.board.get_rect(
center=self.win.get_rect().center)
self.x_turn_rect = self.x_turn.get_rect(top=10, left=10)
self.o_turn_rect = self.o_turn.get_rect(top=10, left=WIN_WIDTH-60)
def setup_grid(self):
grid = []
left = 0
top = 150
row = 0
for i in range(9):
if (i != 0) and (i % 3 == 0):
row += 1
left = 0
grid.append(pygame.Rect(left, row*top, 200, 150))
left += 200
return grid
def update_turn_status(self):
"""Updates the X and O tiles on the top left and right to
let user know whose turn it is"""
self.win.blits((
(self.x_turn_trans, self.x_turn_rect),
(self.o_turn, self.o_turn_rect)
))
def update_grid(self):
"""Updates board"""
self.win.blit(self.board, self.board_rect)
# Here is where you could change board to win and see that the tile changes in opacity
self.board.blit(self.x_tile_trans, self.x_tile_trans.get_rect(center=self.grid[0].center))
def update(self):
self.win.fill(WHITE)
self.update_turn_status()
self.update_grid()
pygame.display.flip()
def main():
pygame.init()
win = pygame.display.set_mode(WIN_SIZE)
tttvisual = TTTVisual(win)
tttfunc = TTTFunc(tttvisual)
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
running = False
tttvisual.update()
pygame.quit()
if __name__ == "__main__":
main()
The issue is caused by the line:
self.board.blit(self.x_tile_trans, self.x_tile_trans.get_rect(center=self.grid[0].center))
You don't blit the image on the display Surface, but on the self.board Surface. When a Surface is blit, it is blended with the target. When you draw on a Surface, it changes permanently. Since you do that over and over again, in every frame, the source Surface appears to by opaque. When you decrease the alpha value (e.g. self.x_tile_trans.set_alpha(5)), a fade in effect will appear.
Never draw on an image Surface. Always draw on the display Surface. Cleat the display at begin of a frame. Draw the entire scene in each frame and update the display once at the end of the frame.
class TTTVisual:
# [...]
def update_grid(self):
"""Updates board"""
self.win.blit(self.board, self.board_rect)
# Here is where you could change board to win and see that the tile changes in opacity
x, y = self.grid[0].center
x += self.board_rect.x
y += self.board_rect.y
self.win.blit(self.x_tile_trans, self.x_tile_trans.get_rect(center=(x, y)))
The typical PyGame application loop has to:
handle the events by 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 either pygame.display.update() or pygame.display.flip()

Faster drawing in python pygame

I made a program using Python, with pygame, that loads pictures of materials and then creates blocks and each block is assigned with random material.
Block is a class and in the drawing process, it iterates through the array with stored blocks, but that is very slow. Isn't there a faster method than storing them in array and iterating through?
class block:
def __init__(self, texture, x, y):
self.texture = texture
self.x = x
self.y = y
material = pygame.image
material.grass = pygame.image.load("textures/grass.png")
material.water = pygame.image.load("textures/water.png")
material.sand = pygame.image.load("textures/sand.png")
materials = [material.grass, material.water, material.sand]
white = (255,255,255);(width, height) = (2048, 1008);black = (0, 0, 0);screen = pygame.display.set_mode((width, height))
b_unit = 16
b = []
count = 0
cx = 0
cy = 0
while count < (width * height) / (b_unit * b_unit):
b.append(block(random.choice(materials), b_unit * cx, b_unit * cy))
cx += 1
count += 1
if cx == width / b_unit:
cx = 0
cy += 1
while True:
for block in b:
screen.blit(block.texture, (block.x + viewx, block.y + viewy))
pygame.display.flip()
I've already mentioned in the comments that you should (almost) always convert your images to improve the performance.
It can also help to blit separate images/pygame.Surfaces onto a big background surface and then just blit this background once per frame. I use two nested for loops here to get the coordinates and randomly blit one of two images.
I get around 120 fps if I use separate sprites (5184) here and ~430 fps with this single background image.
Of course I'm just blitting here and in a real game you'd probably have to store the rects of the tiles in a list or use pygame sprites and sprite groups, for example to implement collision detection or other map related logic, so the frame rate would be lower.
import itertools
import pygame as pg
from pygame.math import Vector2
BLUE_IMAGE = pg.Surface((20, 20))
BLUE_IMAGE.fill(pg.Color('lightskyblue2'))
GRAY_IMAGE = pg.Surface((20, 20))
GRAY_IMAGE.fill(pg.Color('slategray4'))
def main():
screen = pg.display.set_mode((1920, 1080))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
images = itertools.cycle((BLUE_IMAGE, GRAY_IMAGE))
background = pg.Surface(screen.get_size())
# Use two nested for loops to get the coordinates.
for y in range(screen.get_height()//20):
for x in range(screen.get_width()//20):
# This alternates between the blue and gray image.
image = next(images)
# Blit one image after the other at their respective coords.
background.blit(image, (x*20, y*20))
next(images)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# Now you can just blit the background image once
# instead of blitting thousands of separate images.
screen.blit(background, (0, 0))
pg.display.set_caption(str(clock.get_fps()))
pg.display.flip()
clock.tick(1000)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
Side notes: Don't add your images to the pygame.image module (that makes no sense at all).
material = pygame.image
material.grass = pygame.image.load("textures/grass.png")
Writing several statements in the same row separated with semicolons is really ugly and makes code less readable.
white = (255,255,255);(width, height) = (2048, 1008)

Pygame buttons functionality and correcting grid select mouse function

I've added two rectangles, red and green to the top of the following code, and for some reason my code, which otherwise worked, does not now. The grid cells should go RED when clicked, but the clicking is skewed. Can anyone advise on the problem? I have two issues:
An upvote to the first one to spot and point out the error, unless I get it first!
I also want to add text (user 1 and user 2) to the rectangles and make them clickable. On clicking, the user selects a random grid cell (which turns either red or green)
Code as follows:
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.init()
size = (350, 350)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
done = False
clock = pygame.time.Clock()
width=22
height=22
margin=12
grid=[]
#Loop for each row in the list
for row in range(7):
#for each row, create a list that will represent an entire row
grid.append([])
#loop for each column
for column in range(7):
#add the number zero to the current row
grid[row].append(0)
#set row 1, column 5 to one
#grid[1][3]=1
#print(grid[1][3]) #this is the 2nd row and the 4th element along (0...1 row and 0...1...2....3 Column)
# -------- Main Program Loop -----------
while not done:
#ALL EVENT PROCESSING SHOULD GO BELOW THIS LINE
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#************CODE ADDED HERE**********************
elif event.type == pygame.MOUSEBUTTONDOWN:
#print("user clicked the screen")
pos=pygame.mouse.get_pos()
#x = grid[0]
#y= grid[1]
#print(pos)
#CHANGE THE X and Y screen coordinates as in the comments above to grid coordinates
column=pos[0]//(width+margin+50)
row=pos[1]//(height+margin+60)
#set the location to one (when selected by the mouse)
grid[row][column]=1
#print("User click ", pos, "Grid coordinates:", row+1, column+1)
# --- 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(BLACK)
# --- Drawing code should go here
#Drawing the red and Green rectangles
pygame.draw.rect(screen,RED, [0,0,120,50])
pygame.draw.rect(screen,GREEN, [240,0,120,50])
for row in range(7):
#the column number - this refers to the number of columns it will produce. 2, for example, will produce only 2 columns
for column in range(7):
color = WHITE
if grid[row][column] ==1:
color = RED
#****MOVING THE REST OF THE GRID DOWN*****
#the 60 is the margin from the top
#the 50 is the margin from the left
pygame.draw.rect(screen,color,[(margin + width) * column + margin+50, (margin + height) * row + margin+60,width,height])
#*******PRINTING TEXT TO THE SCREEN**********
# Select the font to use, size, bold, italics
#font = pygame.font.SysFont('Calibri', 25, True, False)
#text = font.render("a", True, BLACK)
# Put the image of the text on the screen at 250x250
#screen.blit(text, [25, 25])
# --- This bit updates 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()
This is by no means an ideal way to achieve your goal, but I tried to keep the code as consistent with yours as possible. Let me know if you have any questions about how this works. I will do my best to answer quickly.
import pygame
from pygame.locals import *
pygame.init()
# first we define some constants
# doing this will reduce the amount of 'magic' numbers throughout the code
WINWIDTH = 350
WINHEIGHT = 350
WINSIZE = (WINWIDTH, WINHEIGHT)
CELLWIDTH = 22
CELLHEIGHT = 22
CELLSIZE = (CELLWIDTH, CELLHEIGHT)
CELLMARGINX = 12 # number of pixels to the left and right of each cell
CELLMARGINY = 12 # number of pixels to the top and bottom of each cell
SCREENPADX = 60 # number of pixels between the GRID and the left and right of the window
SCREENPADY = 70 # number of pixels between the GRID and the top and bottom of the window
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
DONE = False # is our program finished running?
# information about the two buttons (red and green)
REDBUTTON = (0, 0, 120, 50)
GREENBUTTON = (240, 0, 120, 50)
# create the WINDOW and CLOCK
WINDOW = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('My Game')
CLOCK = pygame.time.Clock()
CURRENTCOLOR = RED # which color is active
# setting up the GRID
# cells can be accessed by GRID[row][col] ie. GRID[3][4] is the 3rd row and 4th column
# each cell contains [x, y, color]
# where x is the x position on the screen
# y is the y position on the screen
# color is the current color of the cell
GRID = []
for y in range(7):
row = []
for x in range(7):
row.append([x * (CELLWIDTH + CELLMARGINX) + SCREENPADX, y * (CELLHEIGHT + CELLMARGINY) + SCREENPADY, WHITE])
GRID.append(row)
# main loop
while not DONE:
# process all events
for event in pygame.event.get():
if event.type == QUIT: # did the user click the 'x' to close the window
DONE = True
if event.type == MOUSEBUTTONDOWN:
# get the position of the mouse
mpos_x, mpos_y = event.pos
# check if REDBUTTON was clicked
button_x_min, button_y_min, button_width, button_height = REDBUTTON
button_x_max, button_y_max = button_x_min + button_width, button_y_min + button_height
if button_x_min <= mpos_x <= button_x_max and button_y_min <= mpos_y <= button_y_max:
CURRENTCOLOR = RED
# check if GREENBUTTON WAS CLICKED
button_x_min, button_y_min, button_width, button_height = GREENBUTTON
button_x_max, button_y_max = button_x_min + button_width, button_y_min + button_height
if button_x_min <= mpos_x <= button_x_max and button_y_min <= mpos_y <= button_y_max:
CURRENTCOLOR = GREEN
# calculations for clicking cells
mpos_x -= SCREENPADX # mouse position relative to the upper left cell
mpos_y -= SCREENPADY # ^ same
col = mpos_x // (CELLWIDTH + CELLMARGINX) # which cell is the mouse clicking
row = mpos_y // (CELLHEIGHT + CELLMARGINY) # ^ same
# make sure the user clicked on the GRID area
if row >= 0 and col >= 0:
try:
# calculate the boundaries of the cell
cell_x_min, cell_y_min = col * (CELLHEIGHT + CELLMARGINY), row * (CELLWIDTH + CELLMARGINX)
cell_x_max = cell_x_min + CELLWIDTH
cell_y_max = cell_y_min + CELLHEIGHT
# now we will see if the user clicked the cell or the margin
if cell_x_min <= mpos_x <= cell_x_max and cell_y_min <= mpos_y <= cell_y_max:
GRID[row][col][2] = CURRENTCOLOR if event.button == 1 else WHITE
else:
# the user has clicked the margin, so we do nothing
pass
except IndexError: # clicked outside of the GRID
pass # we will do nothing
# logic goes here
# drawing
WINDOW.fill(BLACK)
pygame.draw.rect(WINDOW, RED, REDBUTTON)
pygame.draw.rect(WINDOW, GREEN, GREENBUTTON)
for row in GRID:
for x, y, color in row:
pygame.draw.rect(WINDOW, color, (x, y, CELLWIDTH, CELLHEIGHT))
pygame.display.flip()
CLOCK.tick(60)
pygame.quit()

How do I display text in a grid-like structure in Pygame?

I'm new to pygame and currently I'm working on creating a memory game where the computer displays boxes at random positions for like a second and then the user has to click on where he/she thinks those boxes are. It's kind of like this game:
However I'm not really sure how to make the computer display the boxes with like a letter or symbol e.g. 'T' or '%'. (I've already made the grid).
Could anyone please help? It would be really appreciated.
import pygame
size=[500,500]
pygame.init()
screen=pygame.display.set_mode(size)
# Colours
LIME = (0,255,0)
RED = (255, 0, 0)
BLACK = (0,0,0)
PINK = (255,102,178)
SALMON = (255,192,203)
WHITE = (255,255,255)
LIGHT_PINK = (255, 181, 197)
SKY_BLUE = (176, 226, 255)
screen.fill(BLACK)
# Width and Height of game box
width=50
height=50
# Margin between each cell
margin = 5
# Create a 2 dimensional array. A two dimesional
# array is simply a list of lists.
grid=[]
for row in range(20):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(20):
grid[row].append(0) # Append a cell
# Set row 1, cell 5 to one. (Remember rows and
# column numbers start at zero.)
grid[1][5] = 1
# Set title of screen
pygame.display.set_caption("Spatial Recall")
#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 done==False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
if event.type == pygame.MOUSEBUTTONDOWN:
# User clicks the mouse. Get the position
pos = pygame.mouse.get_pos()
# Change the x/y screen coordinates to grid coordinates
column=pos[0] // (width+margin)
row=pos[1] // (height+margin)
# Sete t hat location to zero
grid[row][column]=1
print("Click ",pos,"Grid coordinates: ",row,column)
# Draw the grid
for row in range(10):
for column in range(10):
color = LIGHT_PINK
if grid[row][column] == 1:
color = RED
pygame.draw.rect(screen,color,[(margin+width)*column+margin,(margin+height)*row+margin,width,height])
# Limit to 20 frames per second
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit ()
In order to display text, you have to go through a series of steps. First you will want to get a font by using the command `pygame.font.Font(font name, size). For example:
arialfont=pygame.font.Font('arial', 12)
All available fonts can be gotten from the command pygame.font.get_fonts(). Remember to initialize pygame (pygame.init()) before any of this.
Next, you will have to use the Font.render(text, antialias, color, background=None). For example:
text=arialfont.render('Hello World!', True, (0, 0, 0))
This will return a surface. You can use it just like you would any other surface. Use text.get_rect() to get its rect, then reposition the rect to put it where you want it to be, and blit it to the window. If you don't know anything about surface objects, just ask me.
Here is a working code.
import pygame, sys
pygame.init()#never forget this line
window=pygame.display.set_mode((100, 100))
font=pygame.font.SysFont('arial', 40)
text=font.render('#', True, (0, 0, 0))
rect=text.get_rect()
window.fill((255, 255, 255))
window.blit(text, rect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()

Categories

Resources