As the title says. Using batch drawing I get really good performance, even with 4096 sprites. However, since my sprites need to change their underlying image I run into issues with performance. I'm pretty sure I'm doing something silly here, since I specifically created a grid/sprite sheet to handle this effectively. But, of course, I never really use it in any effective manner. I might as well have had 5 different images.
What I really want is to keep the underlying sprite image constant, but shift the visible part based on the "food" metric. Here's the code:
import sys, pyglet, random, time
# Constants.
WIDTH = 1280
HEIGHT = 960
TARGET_FPS = 60
GROWTH_CHANCE = 0.1
fps = 0
screen = pyglet.window.Window(WIDTH, HEIGHT)
random.seed(time.time())
# Here we load universal assets, images, sounds, etc.
grass_tiles_img = pyglet.image.load('grass_tiles.png')
grass_tiles_grid = pyglet.image.ImageGrid(grass_tiles_img, 1, 5)
# Sprite batches.
grass_batch = pyglet.graphics.Batch()
class GrassTile:
'''Define a grass tile which cows can graze on.'''
def __init__(self, x, y, food):
self.food = food
self.sprite = pyglet.sprite.Sprite(grass_tiles_grid[0], x, y,
batch=grass_batch)
def draw(self):
grid_index = (self.food // 20)
self.sprite.image = grass_tiles_grid[grid_index]
return self.sprite
def grow(self):
if random.random() < GROWTH_CHANCE:
self.food = min(self.food + 1, 99)
#screen.event
def on_close():
sys.exit()
#screen.event
def on_draw():
# Clear the screen.
screen.clear()
# Draw grass.
grass_sprites = []
for grass in grass_tiles:
grass_sprites.append(grass.draw())
grass_batch.draw()
# Draw FPS counter.
label = pyglet.text.Label('FPS: ' + str(fps), 'Times New Roman', 12, 10, 10)
label.draw()
def grow_grass(dt):
for grass in grass_tiles:
grass.grow()
def calculate_fps(dt):
global fps
fps = round(min(pyglet.clock.get_fps(), TARGET_FPS))
grass_tiles = [GrassTile(20 * i, 15 * j, 0) for j in range(64) for i in range(64)]
pyglet.clock.schedule_interval(grow_grass, 1 / TARGET_FPS)
pyglet.clock.schedule_interval(calculate_fps, 1 / TARGET_FPS)
pyglet.app.run()
And here's the image so you can run the code:
https://i.imgur.com/kFe91aA.png
Why not just have the image change during grass.grow()?
You don't need to do anything to the grass in the draw phase except draw the batch. Setting the image of a sprite isn't a draw operation, it just changes texture coordinates.
def grow(self):
if random.random() < GROWTH_CHANCE:
self.food = min(self.food + 1, 99)
grid_index = (self.food // 20)
self.sprite.image = grass_tiles_grid[grid_index]
You also shouldn't be recreating the label every draw frame. Create the label beforehand and just update the text. label.text = f'FPS: {fps}'
Related
I am working on a platformer game in which I want to add random stars in the background. I have written some code in the function drawBackDrop() which will make some stars at random positions on the screen.
It works fine, but for drawing the stars I have to update it every frame, so the function is called everytime and it makes random stars differently every time.
I want it to appear only once and then not update, so the stars remain at constant positions.
My drawBackDrop() function:
def drawBackdrop():
if globals.theme == "dark":
a = random.randint(3, 12)
x = random.randint(5, globals.screen_width - 12)
y = random.randint(5, globals.screen_height - 12)
numberOfStars = random.randint(35, 55)
starRect = pygame.Rect(x, y, a, a)
for i in range(numberOfStars):
pygame.draw.rect(globals.screen, "White", starRect)
if globals.theme == "light":
pass #Sun and Clouds
This is the code of scene in which I call the function:
def draw(self, sceneManager, screen):
if globals.theme == "light":
screen.fill(globals.light_blue)
elif globals.theme == "dark":
screen.fill(globals.black)
draw.drawBackdrop()
self.cameraSystem.update(screen)
What I get:
As you can see, the stars are being formed every frame. I want it to form only once and then draw the same stars in screen until I win/lose/leave.
How do I only call the function once? Or is there any other way to draw random stars?
There's two ways you can go here.
Paint the stars to a background layer, and blit that every frame
Generate the list of random stars once, and store them. Repainting the same Rects every frame. (As #matszwecja suggested in a comment)
But first note that there's a minor bug in your code. It's not generating the stars correctly - IFF I understand your intentions correctly. It looks like you wanted to generate a random set of stars, but it was painting the same star over and over.
def drawBackdrop():
if globals.theme == "dark":
numberOfStars = random.randint(35, 55) # <<-- MOVED outside loop
for i in range(numberOfStars): # <<-- MOVED Loop
a = random.randint(3, 12)
x = random.randint(5, globals.screen_width - 12)
y = random.randint(5, globals.screen_height - 12)
starRect = pygame.Rect(x, y, a, a)
pygame.draw.rect(globals.screen, "White", starRect)
Background Surface
def makeBackgroundStars():
""" Generate a transparent background overlay with stars """
background = pygame.Surface( ( globals.screen_width, globals.screen_height ), pygame.SRCALPHA )
numberOfStars = random.randint(35, 55)
for i in range(numberOfStars):
a = random.randint(3, 12)
x = random.randint(5, globals.screen_width - 12)
y = random.randint(5, globals.screen_height - 12)
starRect = pygame.Rect(x, y, a, a)
pygame.draw.rect( background, "White", starRect )
return background
The you just need to make the initial image, and then blit it every frame. Probably you'd include all background graphics into this image too.
star_field = makeBackgroundStars()
# in main loop
# ...
globals.screen.blit( star_field, ( 0, 0 ) )
List of Star Rectangles
star_positions = [] # global to hold rects
def genererateStars():
""" generate a random amount of stars for the background """
global star_positions
numberOfStars = random.randint(35, 55) # <<-- MOVED outside loop
for i in range(numberOfStars): # <<-- MOVED Loop
a = random.randint(3, 12)
x = random.randint(5, globals.screen_width - 12)
y = random.randint(5, globals.screen_height - 12)
star_positions.append( pygame.Rect(x, y, a, a) ) # save it for later
def paintStars( screen ):
""" Draw the stars to the background """
global star_positions
for starRect in star_positions:
pygame.draw.rect( screen, "White", starRect )
I've gotten the Conway Game of Life in Python 3.9 from git-hub (there's also a great video on youtube here, made by the author)
All works fine.
Now I'd like to auto-detect when the evolution gets stuck, that is when the cell and cell group shapes are all static or regular oscillators (see pics attached at the end of this post).
My first idea was to compare the next generation grid backwards to 4 generations, that is: if the next generation grid is equal to ny of the previous four generation then it's safe to assume that the evolution has stopped.
So I first thought to make copies of the last 4 grids in 4x2D indipendent arrays and compare at each passage the next generation with each of them.
What would be the most efficient (in terms of time lag) way to compare two bidimentional arrays with say 400 columns and 200 rows?
The scripts use pygame.
here is a copy of what I am using (my plan is to use the check_if_over function in the grid.py module to return True if the evolution has stopped).
MAIN MODULE:
modules = ["pygame", "numpy", "ctypes"]
import sys
import importlib
import subprocess
def install(package):
# install packages if needed
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
# check for needed pacjakes/modules
for needed_module in modules:
try:
i = importlib.import_module(needed_module)
print(f"{needed_module} successfully imported")
except ImportError as e:
install(needed_module)
i = importlib.import_module(needed_module)
except:
"Something went wrong"
import pygame
import os
import grid
import ctypes
from pygame.locals import *
## ADJUSTABLE PARMAS
reduction_factor = 2 # reduces the width/height of the window vs screen size
fps = 60 # max frames per second
scaler = 5 # scales down, the smaller the scaler the greater the number of cells
offset = 1 # thickness of grid separator, must be < scaler
#### COLORS
black = (0, 0, 0)
white = (255, 255, 255)
blue = (0, 14, 71)
os.environ["SDL_VIDEO_CENTERED"] = '1'
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
width, height = int(screensize[0]/reduction_factor), int(screensize[1]/reduction_factor)
size = (width, height)
pygame.init()
pygame.display.set_caption("Conway Game of Life")
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
Grid = grid.Grid(width, height, scaler, offset)
Grid.random2d_array()
run = True
# game loop
while run:
clock.tick(fps)
screen.fill(black)
for event in pygame.event.get():
if event.type == QUIT:
run = False
Grid.Conway(off_color=white, on_color=blue, surface=screen)
pygame.display.update()
pygame.quit()
exit(0)
grid.py:
import pygame
import numpy as np
import random
class Grid:
def __init__(self, width, height, scale, offset):
self.scale = scale
self.columns = int(height / scale)
self.rows = int(width / scale)
self.size = (self.rows, self.columns)
self.grid_array = np.ndarray(shape=(self.size))
# next 3 lines defines the set of array copies to save
# the past 4 generations
self.grid_array_copies = []
for i in range(0, 4):
self.grid_array_copies.append(np.ndarray(shape=(self.size)))
self.offset = offset
self.alive = 0
self.evolution_stopped = False
def random2d_array(self):
for x in range(self.rows):
for y in range(self.columns):
self.grid_array[x][y] = random.randint(0, 1)
def Conway(self, off_color, on_color, surface):
for x in range(self.rows):
for y in range(self.columns):
y_pos = y * self.scale
x_pos = x * self.scale
if self.grid_array[x][y] == 1:
pygame.draw.rect(surface, on_color, [x_pos, y_pos, self.scale - self.offset, self.scale - self.offset])
else:
pygame.draw.rect(surface, off_color, [x_pos, y_pos, self.scale - self.offset, self.scale - self.offset])
next = np.ndarray(shape=(self.size))
self.alive = 0
for x in range(self.rows):
for y in range(self.columns):
state = self.grid_array[x][y]
neighbours = self.get_neighbours(x, y)
if state == 0 and neighbours == 3:
next[x][y] = 1
self.alive += 1
elif state == 1 and (neighbours < 2 or neighbours > 3):
next[x][y] = 0
else:
next[x][y] = state
self.alive += state
self.grid_array = next
self.check_if_over(next)
with open("survivors.txt", "w") as f:
f.write(str(self.alive))
def get_neighbours(self, x, y):
total = 0
for n in range(-1, 2):
for m in range(-1, 2):
x_edge = (x + n + self.rows) % self.rows
y_edge = (y + m + self.columns) % self.columns
total += self.grid_array[x_edge][y_edge]
total -= self.grid_array[x][y]
return total
def check_if_over(self, next):
pass
Thanx for the patience.
Initial conditions:
Evolution stopped:
EDIT
I forgot to mention something that may be not that straightforward.
Unlike Golly (another open source for the Conway's Game of Life), the environment where this Game of Life plays is a finite one (see pictures above), that is it's kinda rendering of a spherical suface into a rectangle, so the cells colonies evolving past the right edge of the window re-enter at the left edge, those at the bottom edge re-enter at the top. While in Golly, for example the plan environment is theoretically infinite.
Golly starting conditions, zoomed in:
Golly starting conditions partially zoomed out (could go futher out until cells invisibility and further). The black surface is the environment, the white squares the cells
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()
I want to be able to create some turtles which display values by subclassing turtle.Turtle.
These turtles should display their value as text centered in their own shape. I also want to be able to position the turtles with accuracy, so setting/determining their width and height relative to a given font size is important.
This is my attempt so far:
I think this answer is relevant: How to know the pixel size of a specific text on turtle graphics in python? but it is quite old, and the bounding box it draws around the text is not in the correct position using python 3.8.
import turtle
FONT_SIZE = 32
class Tile(turtle.Turtle):
def __init__(self):
super().__init__(shape="square")
self.penup()
def show_value(self, val):
self.write(val, font=("Arial", FONT_SIZE, "bold"), align="center")
screen = turtle.Screen()
vals = [5, 7, 8, 2]
for i in range(len(vals)):
tile = Tile()
tile_size = (FONT_SIZE / 20)
tile.shapesize(tile_size)
tile.fillcolor("red" if i % 2 == 0 else "blue")
tile.setx(i * FONT_SIZE)
tile.show_value(vals[i])
turtle.done()
It would be very helpful to have Turtle Objects containing text such
as integer values, which can be used to display a variety of puzzles
and games, and can have their own click handlers attached.
Here's the rub, and the (two) reason(s) that approaches using stamp() as suggested in other answers won't work. First, you can't click on a hidden turtle:
from turtle import *
def doit(x, y):
print("Just do it!")
yertle = Turtle()
# comment out the following line if you want `onlick()` to work
yertle.hideturtle()
yertle.shape('square')
yertle.stamp()
yertle.onclick(doit)
done()
Stamps are not clickable entities. Second, you can't even click on a turtle that's behind ink left by this, or another, turtle:
from turtle import *
def doit(x, y):
print("Just do it!")
yertle = Turtle()
yertle.shape('square')
yertle.fillcolor('white')
yertle.onclick(doit)
myrtle = Turtle()
myrtle.shape('turtle')
myrtle.penup()
myrtle.sety(-16)
# comment out the following line if you want `onlick()` to work
myrtle.write('X', align='center', font=('Courier', 32, 'bold'))
myrtle.goto(100, 100) # move myrtle out of the way of clicking
done()
If you click on the letter 'X', nothing happens unless you manage to hit a portion of the square just beyond the letter. My belief is that although we think of the 'X' as dead ink over our live turtle, at the tkinter level they are both similar, possibly both capable of receiving events, so one obscures the click on the other.
So how can we do this? The approach I'm going to use is make a tile a turtle with an image where the images are generate by writing onto bitmaps:
tileset.py
from turtle import Screen, Turtle, Shape
from PIL import Image, ImageDraw, ImageFont, ImageTk
DEFAULT_FONT_FILE = "/Library/Fonts/Courier New Bold.ttf" # adjust for your system
DEFAULT_POINT_SIZE = 32
DEFAULT_OUTLINE_SIZE = 1
DEFAULT_OUTLINE_COLOR = 'black'
DEFAULT_BACKGROUND_COLOR = 'white'
class Tile(Turtle):
def __init__(self, shape, size):
super().__init__(shape)
self.penup()
self.size = size
def tile_size(self):
return self.size
class TileSet():
def __init__(self, font_file=DEFAULT_FONT_FILE, point_size=DEFAULT_POINT_SIZE, background_color=DEFAULT_BACKGROUND_COLOR, outline_size=DEFAULT_OUTLINE_SIZE, outline_color=DEFAULT_OUTLINE_COLOR):
self.font = ImageFont.truetype(font_file, point_size)
self.image = Image.new("RGB", (point_size, point_size))
self.draw = ImageDraw.Draw(self.image)
self.background_color = background_color
self.outline_size = outline_size
self.outline_color = outline_color
def register_image(self, string):
width, height = self.draw.textsize(string, font=self.font)
image = Image.new("RGB", (width + self.outline_size*2, height + self.outline_size*2), self.background_color)
draw = ImageDraw.Draw(image)
tile_size = (width + self.outline_size, height + self.outline_size)
draw.rectangle([(0, 0), tile_size], outline=self.outline_color)
draw.text((0, 0), string, font=self.font, fill="#000000")
photo_image = ImageTk.PhotoImage(image)
shape = Shape("image", photo_image)
Screen()._shapes[string] = shape # underpinning, not published API
return tile_size
def make_tile(self, string):
tile_size = self.register_image(string)
return Tile(string, tile_size)
Other than its image, the only differences a Tile instance has from a Turtle instance is an extra method tile_size() to return its width and height as generic turtles can't do this in the case of images. And a tile's pen is up at the start, instead of down.
I've drawn on a couple of SO questions and answers:
Dump characters (glyphs) from TrueType font (TTF) into bitmaps
How do you set a turtle's shape to a PIL image
And while I'm at it, this answer has been updated to be more system independent:
How to know the pixel size of a specific text on turtle graphics in python?
To demonstrate how my tile sets work, here's the well-know 15 puzzle implemented using them. It creates two tile sets, one with white backgrounds and one with red (pink) backgrounds:
from tileset import TileSet
from turtle import Screen
from functools import partial
from random import shuffle
SIZE = 4
OFFSETS = [(-1, 0), (0, -1), (1, 0), (0, 1)]
def slide(tile, row, col, x, y):
tile.onclick(None) # disable handler inside handler
for dy, dx in OFFSETS:
try:
if row + dy >= 0 <= col + dx and matrix[row + dy][col + dx] == None:
matrix[row][col] = None
row, col = row + dy, col + dx
matrix[row][col] = tile
width, height = tile.tile_size()
x, y = tile.position()
tile.setposition(x + dx * width, y - dy * height)
break
except IndexError:
pass
tile.onclick(partial(slide, tile, row, col))
screen = Screen()
matrix = [[None for _ in range(SIZE)] for _ in range(SIZE)]
white_tiles = TileSet(background_color='white')
red_tiles = TileSet(background_color='pink')
tiles = []
parity = True
for number in range(1, SIZE * SIZE):
string = str(number).rjust(2)
tiles.append(white_tiles.make_tile(string) if parity else red_tiles.make_tile(string))
parity = not parity
if number % SIZE == 0:
parity = not parity
shuffle(tiles)
width, height = tiles[0].tile_size()
offset_width, offset_height = width * 1.5, height * 1.5
for row in range(SIZE):
for col in range(SIZE):
if row == SIZE - 1 == col:
break
tile = tiles.pop(0)
width, height = tile.tile_size()
tile.goto(col * width - offset_width, offset_height - row * height)
tile.onclick(partial(slide, tile, row, col))
matrix[row][col] = tile
screen.mainloop()
If you click on a number tile that's next to the blank space, it will move into the blank space, otherwise nothing happens. This code doesn't guarantee a solvable puzzle -- half won't be solvable due to the random shuffle. It's just a demonstration, the fine details of it, and the tiles themselves, are left to you.
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)