Pygame low frame rate on simple game - python

I'm making a sandbox game/simulation which looks like powdergame from danball.com except way simpler.
My game lags when there is a certain amount of squares that are spawned
don't pay attention to the comments
import pygame
import time
import random
pygame.init()
clock = pygame.time.Clock()
fps = 120
wnx = 800
wny = 600
black = (0,0,0)
grey = (80,80,80)
white = (255,255,255)
black_transparent = (255,255,255,128)
red = (255,0,0)
BACKGROUNDCOLOR = (40,40,40)
#__ Elements __
sand = (255,160,50)
rock = (125,125,125)
bsand = (255,180,150)
brock = (180,180,180)
dirt = (110, 45, 0)
bdirt = (200, 90, 0)
water = (0, 150, 255)
bwater = (25, 200, 255)
wall = (100,100,100)
bwall = (140,140,140)
erase = False
Onbutton = False
color = sand
cubec = sand
wn = pygame.display.set_mode((wnx, wny))
wn.fill(white)
def cursor(cux,cuy,cuw):
boxc = pygame.draw.rect(wn, black, [cux, cuy, cuw, cuw], 1)
def message(Font,Size,colort,xt,yt,text):
font = pygame.font.SysFont('freepixelregular', Size, True)
text = font.render(text, True, colort)
wn.blit(text, (xt, yt))
def cube(cx,cy,cw,ch,cubec):
pygame.draw.rect(wn, cubec, [cx, cy, cw, ch])
def floor(fx,fy,fw,fh):
pygame.draw.rect(wn, grey, [fx, fy, fw, fh])
pygame.draw.line(wn, black, (150,504), (800, 504), 10)
def sidebar(sx,sy,sw,sh):
pygame.draw.rect(wn, grey, [0, 0, 150, 600])
pygame.draw.line(wn, black, (154,0), (154, 500), 10)
def button(bx, by, bw, bh, text, abcol, bcol, colorchange):
global color
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if bx+bw > mouse[0] > bx and by+bh > mouse[1] > by:
Onbutton = True
pygame.draw.rect(wn, abcol, [bx, by, bw, bh])
if click[0] == 1 and colorchange != None:
color = colorchange
else:
pygame.draw.rect(wn, bcol, [bx, by, bw, bh])
Onbutton = False
font = pygame.font.SysFont('freepixelregular', 25,True)
text = font.render(text, True, black)
wn.blit(text, (bx + (bw/14), by + (bh/4)))
def main():
number = 0
toggle_fast = False
erase = False
cubex = [0] * number
cubey = [0] * number
cubec = [0] * number
cubew = 10 #cube size
cubeh = cubew
floory = 500
gravity = (cubew*-1)
clickt = False
exit = False
while not exit:
#________________ QUIT ________________________________________
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
toggle_fast = not toggle_fast
if event.key == pygame.K_v:
erase = not erase
#_____________________ Click / spawn cube / erase cube _____________________________
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if toggle_fast == False:
if event.type == pygame.MOUSEBUTTONDOWN:
if mouse[1] < floory and mouse[0] >= 154:
cubex.append(round((mouse[0]/cubew),0)*cubew)
cubey.append(round((mouse[1]/cubew),0)*cubew)
cubec.append(color)
if click[0] == 1 and toggle_fast == True:
print(erase)
if mouse[1] < floory and mouse[0] >= 154:
cubex.append(round((mouse[0]/cubew),0)*cubew)
cubey.append(round((mouse[1]/cubew),0)*cubew)
cubec.append(color)
#_____________________ GRAVITY _____________________________
for i in range(len(cubex)):
cubeR = pygame.Rect(cubex[i], cubey[i] + cubew, cubew, cubeh)
cisect = [j for j in range(len(cubey)) if j != i and cubeR.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
watercheck = [j for j in range(len(cubey)) if j != i and cubec[i] != (0, 150, 255) and cubec[j] == (0, 150, 255) and cubeR.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
if not any(cisect) and not (cubey[i] + cubew) >= floory:
if not cubec[i] == (100,100,100):
cubey[i] -= gravity
#for j in range(len(cubex):
# if any(watercheck):
# if not (cubey[i] + cubew) >= floory or any(cisect):
# oldposy = CUBEINFO[i][1]
# oldposx = CUBEINFO[i][0]
# CUBEINFO.append(oldposx, oldposy, (0, 150, 255))
#cubex.append(oldposx)
#cubey.append(oldposy)
#cubec.append((0, 150, 255))
#________water physics___________
cubeRxr = pygame.Rect(cubex[i] - cubew, cubey[i], cubew, cubeh)
cubeRxl = pygame.Rect(cubex[i] + cubew, cubey[i], cubew, cubeh)
cubeRdiagr = pygame.Rect(cubex[i] + 10, cubey[i] + 10, cubew, cubeh)
cubeRdiagl = pygame.Rect(cubex[i] - 10, cubey[i] + 10, cubew, cubeh)
cisectx = [j for j in range(len(cubex)) if j != i and cubeRxr.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
cisectxl = [j for j in range(len(cubex)) if j != i and cubeRxl.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
cisectdr = [j for j in range(len(cubex)) if j != i and cubeRdiagr.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
cisectdl = [j for j in range(len(cubex)) if j != i and cubeRdiagl.colliderect(pygame.Rect(cubex[j], cubey[j], cubew, cubeh))]
if cubec[i] == (0, 150, 255):
if (cubey[i] + cubew) >= floory or any(cisect): # on ground
if not (cubex[i] + cubew) >= 800 and not cubex[i] <= 164:
if any(cisectx) and not any(cisectxl): #going right because of right wall
cubex[i] += 10
elif any(cisectxl) and not any(cisectx): #going left because of left wall
cubex[i] -= 10
elif any(cisectx) and any(cisectxl):
cubex[i] += 0
elif any(cisect) or (cubey[i] + cubew) >= floory:
negative = [-10, 10]
cubex[i] += random.choice(negative)
elif any(cisect) and not any(cisectdl) and not any(cisectdr):
negative = [-10, 10]
cubex[i] += random.choice(negative)
#____________________ Element _____________________________
#_____________________ DRAW _____________________________
wn.fill(BACKGROUNDCOLOR)
floor(0,floory,800,100)
sidebar(0, 0, 150, 600)
for i in range(len(cubex)):
cube(cubex[i], cubey[i], cubew, cubeh, cubec[i])
cursor(round((mouse[0]/cubew),0)*cubew, round((mouse[1]/cubew),0)*cubew, cubew,)
button(20, 40, 50, 40, 'RCK', brock, rock, (125,125,125))
button(20, 85, 50, 40, 'SND', bsand, sand, (255,160,50))
button(20, 130, 50, 40, 'DRT', bdirt, dirt, (110, 45, 2))
button(20, 175, 50, 40, 'WTR', bwater, water, (0, 150, 255))
button(20, 220, 50, 40, 'WLL', bwall, wall, (100,100,100))
#(Font,Size,colort,xt,yt,message):
message(None, 20, black, 10,400,('ERASE:'+str(erase)))
pygame.display.update()
clock.tick(fps)
main()
pygame.quit()
quit()
Maybe it is because of the fact that the squares positions (refered as cubex,cubey) are in separate lists or something?
im just starting out with python so it can be a silly error
thanks for the help!

The only way to speed up your game is to avoid the continuously searching in the array of cubes.
To achieve this you have to change the representation of your data. You have to think the problem from the other direction. Don't search a cube at a position, but "ask" a position if a cube is on it. Instead of storing the cubes in lists, create a 2 dimensional playground grid and associate a cube to a field in the grid.
Create and object for a cube (the attribute '.dir' is for the water and explained later):
class Cube:
def __init__(self, color):
self.color = color
self.dir = 1
Create the empty playground (each filed is initialized by None):
cubew = 10 #cube size
cubeh = cubew
pg_rect = pygame.Rect(160, 0, 650, 500)
pg_size = (pg_rect.width // cubew, pg_rect.height // cubeh)
pg_grid = [[None for i in range(pg_size[1])] for j in range(pg_size[0])]
On mouse click a cube can be added to the playground with ease:
if event.type == pygame.MOUSEBUTTONDOWN:
if mouse[1] < floory and mouse[0] >= 154:
i, j = ((mouse[0]-pg_rect.left) // cubew, (mouse[1]-pg_rect.top) // cubeh)
if not pg_grid[i][j]:
pg_grid[i][j] = Cube(color)
To draw the cubes the entire field has to be traversed:
for i in range(pg_size[0]):
for j in range(pg_size[1]):
if pg_grid[i][j]:
pos = (pg_rect.left + i * cubew, pg_rect.top + j * cubeh)
cube(*pos, cubew, cubeh, pg_grid[i][j].color)
For the update of positions of the cubes (gravity, water), all the cubes have to be listed and the location of the cube in the filed has to be changed.
cubes = [(i, j) for i in range(pg_size[0]) for j in range(pg_size[1]-1, 0, -1) if pg_grid[i][j]]
for i, j in cubes:
# [...]
For gravity it has to be checked if the filed below the cube is "free" (None):
fall_down = pg_grid[i][j].color != wall
if fall_down and j < pg_size[1]-1 and pg_grid[i][j+1] == None:
pg_grid[i][j+1] = pg_grid[i][j]
pg_grid[i][j] = None
And for the water effect it has to be checked if the filed beside the cube, which is identified by self.dir is "free", If it is "free", then the cube steps forward. Else its direction has to be changed:
is_water = pg_grid[i][j].color == water
if is_water:
if pg_grid[i][j].dir < 0:
if i <= 0 or pg_grid[i-1][j]:
pg_grid[i][j].dir = 1
else:
pg_grid[i-1][j] = pg_grid[i][j]
pg_grid[i][j] = None
else:
if i >= pg_size[0]-1 or pg_grid[i+1][j]:
pg_grid[i][j].dir = -1
else:
pg_grid[i+1][j] = pg_grid[i][j]
pg_grid[i][j] = None
See the example, where I applied the changes to your original code:
import pygame
import time
import random
pygame.init()
clock = pygame.time.Clock()
fps = 120
wnx = 800
wny = 600
black = (0,0,0)
grey = (80,80,80)
white = (255,255,255)
black_transparent = (255,255,255,128)
red = (255,0,0)
BACKGROUNDCOLOR = (40,40,40)
#__ Elements __
sand = (255,160,50)
rock = (125,125,125)
bsand = (255,180,150)
brock = (180,180,180)
dirt = (110, 45, 0)
bdirt = (200, 90, 0)
water = (0, 150, 255)
bwater = (25, 200, 255)
wall = (100,100,100)
bwall = (140,140,140)
erase = False
Onbutton = False
color = sand
cubec = sand
wn = pygame.display.set_mode((wnx, wny))
wn.fill(white)
class Cube:
def __init__(self, color):
self.color = color
self.dir = 1
def cursor(cux,cuy,cuw):
boxc = pygame.draw.rect(wn, black, [cux, cuy, cuw, cuw], 1)
def message(Font,Size,colort,xt,yt,text):
font = pygame.font.SysFont('freepixelregular', Size, True)
text = font.render(text, True, colort)
wn.blit(text, (xt, yt))
def cube(cx,cy,cw,ch,cubec):
pygame.draw.rect(wn, cubec, [cx, cy, cw, ch])
def floor(fx,fy,fw,fh):
pygame.draw.rect(wn, grey, [fx, fy, fw, fh])
pygame.draw.line(wn, black, (150,504), (800, 504), 10)
def sidebar(sx,sy,sw,sh):
pygame.draw.rect(wn, grey, [0, 0, 150, 600])
pygame.draw.line(wn, black, (154,0), (154, 500), 10)
def button(bx, by, bw, bh, text, abcol, bcol, colorchange):
global color
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if bx+bw > mouse[0] > bx and by+bh > mouse[1] > by:
Onbutton = True
pygame.draw.rect(wn, abcol, [bx, by, bw, bh])
if click[0] == 1 and colorchange != None:
color = colorchange
else:
pygame.draw.rect(wn, bcol, [bx, by, bw, bh])
Onbutton = False
font = pygame.font.SysFont('freepixelregular', 25,True)
text = font.render(text, True, black)
wn.blit(text, (bx + (bw/14), by + (bh/4)))
def main():
number = 0
toggle_fast = False
erase = False
cubew = 10 #cube size
cubeh = cubew
pg_rect = pygame.Rect(160, 0, 650, 500)
pg_size = (pg_rect.width // cubew, pg_rect.height // cubeh)
pg_grid = [[None for i in range(pg_size[1])] for j in range(pg_size[0])]
floory = 500
gravity = (cubew*-1)
clickt = False
exit = False
while not exit:
#________________ QUIT ________________________________________
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
toggle_fast = not toggle_fast
if event.key == pygame.K_v:
erase = not erase
#_____________________ Click / spawn cube / erase cube _____________________________
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if toggle_fast == False:
if event.type == pygame.MOUSEBUTTONDOWN:
if mouse[1] < floory and mouse[0] >= 154:
i, j = ((mouse[0]-pg_rect.left) // cubew, (mouse[1]-pg_rect.top) // cubeh)
if not pg_grid[i][j]:
pg_grid[i][j] = Cube(color)
if click[0] == 1 and toggle_fast == True:
print(erase)
if mouse[1] < floory and mouse[0] >= 154:
i, j = ((mouse[0]-pg_rect.left) // cubew, (mouse[1]-pg_rect.top) // cubeh)
if not pg_grid[i][j]:
pg_grid[i][j] = Cube(color)
# update cubes
cubes = [(i, j) for i in range(pg_size[0]) for j in range(pg_size[1]-1, 0, -1) if pg_grid[i][j]]
for i, j in cubes:
fall_down = pg_grid[i][j].color != wall
is_water = pg_grid[i][j].color == water
if fall_down and j < pg_size[1]-1 and pg_grid[i][j+1] == None:
#_____________________ GRAVITY _____________________________
pg_grid[i][j+1] = pg_grid[i][j]
pg_grid[i][j] = None
elif is_water:
#________water physics___________
if pg_grid[i][j].dir < 0:
if i <= 0 or pg_grid[i-1][j]:
pg_grid[i][j].dir = 1
else:
pg_grid[i-1][j] = pg_grid[i][j]
pg_grid[i][j] = None
else:
if i >= pg_size[0]-1 or pg_grid[i+1][j]:
pg_grid[i][j].dir = -1
else:
pg_grid[i+1][j] = pg_grid[i][j]
pg_grid[i][j] = None
wn.fill(BACKGROUNDCOLOR)
floor(0,floory,800,100)
sidebar(0, 0, 150, 600)
# draw cubes
for i in range(pg_size[0]):
for j in range(pg_size[1]):
if pg_grid[i][j]:
pos = (pg_rect.left + i * cubew, pg_rect.top + j * cubeh)
cube(*pos, cubew, cubeh, pg_grid[i][j].color)
cursor(round((mouse[0]/cubew),0)*cubew, round((mouse[1]/cubew),0)*cubew, cubew,)
button(20, 40, 50, 40, 'RCK', brock, rock, (125,125,125))
button(20, 85, 50, 40, 'SND', bsand, sand, (255,160,50))
button(20, 130, 50, 40, 'DRT', bdirt, dirt, (110, 45, 2))
button(20, 175, 50, 40, 'WTR', bwater, water, (0, 150, 255))
button(20, 220, 50, 40, 'WLL', bwall, wall, (100,100,100))
#(Font,Size,colort,xt,yt,message):
message(None, 20, black, 10,400,('ERASE:'+str(erase)))
pygame.display.update()
clock.tick(fps)
main()
pygame.quit()
quit()

Related

Python Fatal error while creating a Sudoku game

I'm trying to create a Sudoku game in python with a solver included. First of all, for some reason, it doesn't show me the procedure of resolving, the window opens only when the board is solved and secondly when i close the window it returns me that python fatal error :Fatal Python error: pygame_parachute: (pygame parachute) Segmentation Fault
Python runtime state: initialized
That is my code :
import time
import pygame
from random import *
import numpy as np
pygame.init()
pygame.font.init()
LARGEUR, HAUTEUR = 550, 550
WIN = pygame.display.set_mode((LARGEUR, HAUTEUR))
pygame.display.set_caption('Sudoku Game')
Font1 = pygame.font.SysFont(None, 35)
clock = pygame.time.Clock()
BLANC = (255, 255, 255)
NOIR = (0, 0, 0)
BLEU = (0,0,255)
def gen_grille():
grille = [
[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,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,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
]
val_debut = 17
for n in range(val_debut):
lgn = randint(1, 8)
cl = randint(1, 8)
num = randint(1, 9)
while(not is_possible(grille,lgn,cl,num) or grille[lgn][cl] != 0):
lgn = randint(1, 8)
cl = randint(1, 8)
num = randint(1, 9)
grille[lgn][cl]= num;
return list(grille)
def is_possible(grille,lgn,cl,num):
statut = True
for a in range(9):
if (grille[a][cl] == num):
statut = False
for b in range(9):
if (grille[lgn][b] == num):
statut = False
zone_lgn = lgn // 3
zone_cl = cl // 3
for a in range(3):
for b in range(3):
if(grille[zone_lgn*3 + a][zone_cl*3 + b] == num):
statut = False
return statut
gen_grille()
grille = gen_grille()
grid_original = [[grille[x][y] for y in range(len(grille[0]))] for x in range(len(grille))]
def draw_new_vals(WIN, position):
x,y = position[0], position[1]
myfont = pygame.font.SysFont('Comic Sans MS', 35)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN:
if(grid_original[x-1][y-1] != 0):
return
if(event.key == 48):
grille[x-1][y-1] = event.key - 48
pygame.draw.rect(WIN, BLANC, (position[0]*50 + 5, position[0]*50+ 5, 40, 40))
pygame.display.update()
return
if(0 < event.key - 48 <10):
pygame.draw.rect(WIN, BLANC, (position[0]*50 + 5, position[1]*50+ 5, 40, 40))
value = myfont.render(str(event.key-48), True, (0,0,0))
WIN.blit(value, (position[0]*50 +15, position[1]*50))
grille[x-1][y-1] = event.key - 48
pygame.display.update()
return
return
def draw_strt_vals():
for x in range(9):
for y in range(9):
if(0 < grille[x][y] < 10):
num = Font1.render(str(grille[x][y]), True, BLEU)
WIN.blit(num, ((x+1)*50 + 15, (y+1)*50 + 15))
def draw_all():
WIN.fill(BLANC)
draw_grille()
draw_strt_vals()
pygame.display.update()
def draw_grille():
for x in range(10):
pygame.draw.line(WIN, (NOIR), (50 + 50*x, 50), (50 + 50*x, 500), 2)
pygame.draw.line(WIN, (NOIR), (50, 50 + 50*x), (500, 50 + 50*x), 2)
for x in range(10):
if x % 3 == 0:
pygame.draw.line(WIN, (NOIR), (50 + 50*x, 50), (50 + 50*x, 500), 4)
pygame.draw.line(WIN, (NOIR), (50, 50 + 50*x), (500, 50 + 50*x), 4)
solved = 0
def solver(grille):
Font1 = pygame.font.SysFont(None, 35)
for lgn in range(9):
for cl in range(9):
if grille[lgn][cl] == 0:
for num in range(1,10):
if is_possible(grille, lgn, cl, num):
grille[lgn][cl] = num
pygame.draw.rect(WIN, BLANC, ((cl+1)*50 + 5, (lgn+1)*50+ 5,40 ,40))
value = Font1.render(str(num), True, (0,0,0))
WIN.blit(value, ((cl+1)*50 +15,(lgn+1)*50))
pygame.display.update()
solver(grille)
global solved
if(solved == 1):
return
grille[lgn][cl] = 0
pygame.draw.rect(WIN, BLANC, ((lgn+1)*50 + 5, (cl+1)*50+ 5,40 ,40))
pygame.display.update()
return
solved = 1
def main():
pygame.init()
clock.tick(60)
marche = True
for i in range(0, len(grille[0])):
for j in range(0, len(grille[0])):
if(0<grille[i][j]<10):
value = Font1.render(str(grille[i][j]), True, BLEU)
WIN.blit(value, ((j+1)*50 + 15, (i+1)*50 ))
pygame.display.update()
solver(grille)
while marche:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
m_pos = pygame.mouse.get_pos()
draw_new_vals(WIN, (m_pos[0]//50, m_pos[1]//50))
if event.type == pygame.QUIT:
pygame.quit()
return
draw_all()
main()
if __name__ == "__main__":
main()
main()

Get isometric tile mouse selection in Pygame

I'm not managing to get this math correct, and it's a little bit difficult to explain in words. I have managed to create a isometric grid, which you can select the tiles with the mouse perfectly, and I have managed to implement a camera movement using wasd keys and still get the tiles correctly selected, but there is a slightly bug which I can not figure out where is coming from.
This is what happens, but only sometimes, depend where the camera offset is:
when this happens, it is only on the x axis, and not in every tile.
I'm almost giving up on this cause I can't find the bug, thought of posting here to see if anyone had similar problem.
import time
import pygame
import sys
import math
from os import path
from settings import *
from sprites import *
# ------------------------- SETTINGS ---------------------------- #
# COLORS (r, g, b)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# game settings
WIDTH = 1024
HEIGHT = 768
FPS = 60
title = "Isometric-Based game"
BGCOLOUR = DARKGREY
TILE_X = 80
TILE_Y = 40
WORLD_X, WORLD_Y = 14, 10
ORIGIN_X, ORIGIN_Y = 5, 1
# Debug
pygame.init()
font = pygame.font.Font(None, 25)
CAMERA_SPEED = 300
def get_info(info_list):
display_surface = pygame.display.get_surface()
for i, key in enumerate(info_list):
text = font.render(str(key) + " : " + str(info_list[key]), True, (255, 255, 255), (0, 0, 0))
text_rect = text.get_rect()
text_rect.y = 20 * i
display_surface.blit(text, text_rect)
# ------------------------- SPRITES ---------------------------- #
class Camera:
def __init__(self, game, x, y):
self.game = game
self.x, self.y = self.game.to_screen(x, y)
self.vx, self.vy = 0, 0
def update(self):
self.get_keys()
self.x += self.vx * self.game.dt
self.y += self.vy * self.game.dt
def get_keys(self):
self.vx, self.vy = 0, 0
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.vy = -CAMERA_SPEED
if keys[pygame.K_s]:
self.vy = CAMERA_SPEED
if keys[pygame.K_a]:
self.vx = -CAMERA_SPEED
if keys[pygame.K_d]:
self.vx = CAMERA_SPEED
if self.vx != 0 and self.vy != 0:
self.vx *= 1.0
self.vy *= 0.50
class MouseSelection:
def __init__(self, game, image):
self.game = game
self.image = image
def update(self):
# get mouse x and y
self.mouse_x, self.mouse_y = pygame.mouse.get_pos()
# get the mouse offset position inside the tile
self.offset_x, self.offset_y = self.mouse_x % TILE_X, self.mouse_y % TILE_Y
self.offset_x += self.game.scroll_x % TILE_X # Add camera scroll to offset
self.offset_y += self.game.scroll_y % TILE_Y
# get the cell number
self.cell_x, self.cell_y = (self.mouse_x // TILE_X), (self.mouse_y // TILE_Y)
self.cell_x += int((self.game.scroll_x // TILE_X)) # Add camera scroll to cell
self.cell_y += int((self.game.scroll_y // TILE_Y))
# get the selected cell in iso grid
self.selected_x = (self.cell_y - ORIGIN_Y) + (self.cell_x - ORIGIN_X)
self.selected_y = (self.cell_y - ORIGIN_Y) - (self.cell_x - ORIGIN_X)
# height and width of a quarter of a tile, select the corner of the tile to nodge to a direction
h, w = TILE_Y / 2, TILE_X / 2
if self.offset_y < (h / w) * (w - self.offset_x):
self.selected_x -= 1
if self.offset_y > (h / w) * self.offset_x + h:
self.selected_y += 1
if self.offset_y < (h / w) * self.offset_x - h:
self.selected_y -= 1
if self.offset_y > (h / w) * (2 * w - self.offset_x) + h:
self.selected_x += 1
# translate the selected cell to world coordinate
self.selectedWorld_x, self.selectedWorld_y = self.game.to_screen(self.selected_x, self.selected_y)
def draw(self):
# Draw the selected tile with the camera scroll offset
self.game.screen.blit(self.image, (self.selectedWorld_x - self.game.scroll_x,
self.selectedWorld_y - self.game.scroll_y))
class SpriteSheet:
def __init__(self, image):
self.image = image
self.frames = []
def get_image(self):
for row in range(2):
for col in range(4):
if row == 0:
image = pygame.Surface((TILE_Y, TILE_Y / 2)).convert_alpha()
image.blit(self.image, (0, 0), (col * TILE_X / 2, row * TILE_Y / 2, TILE_X, TILE_Y))
image = pygame.transform.scale(image, (TILE_X, TILE_Y))
else:
image = pygame.Surface((TILE_Y, TILE_Y)).convert_alpha()
image.blit(self.image, (0, 0), (col * TILE_X / 2, row * TILE_Y / 2, TILE_X, TILE_Y * 2))
image = pygame.transform.scale(image, (TILE_X, TILE_Y * 2))
image.set_colorkey(WHITE)
self.frames.append(image)
return self.frames
# ------------------------- GAME LOOP ---------------------------- #
class Game:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(title)
self.clock = pygame.time.Clock()
pygame.key.set_repeat(400, 100)
self.debug = {}
self.sprite_sheet_image = pygame.image.load("isometric_whitebg - Copy.png")
self.index = 1
self.scroll_x, self.scroll_y = 0, 0
def new(self):
# initialize all variables and do all the setup for a new game
self.sprite_sheet = SpriteSheet(self.sprite_sheet_image)
self.tile_selected = self.sprite_sheet.get_image()[0]
self.tiles = self.sprite_sheet.get_image()
self.mouse_selection = MouseSelection(self, self.tile_selected)
self.camera = Camera(self, 1, 1)
def run(self):
# game loop - set self.playing = False to end the game
self.playing = True
while self.playing:
self.dt = self.clock.tick(FPS) / 1000
self.events()
self.update()
self.draw()
def quit(self):
pygame.quit()
sys.exit()
def update(self):
# update portion of the game loop
self.camera.update()
self.mouse_selection.update()
self.mx, self.my = pygame.mouse.get_pos()
# -------------------------------------------------- CAMERA SCROLLING ----------------------------------------#
if self.camera.x - self.scroll_x != WIDTH / 2:
self.scroll_x += (self.camera.x - (self.scroll_x + WIDTH / 2)) / 10
if self.camera.y - self.scroll_y != HEIGHT / 2:
self.scroll_y += (self.camera.y - (self.scroll_y + HEIGHT / 2)) / 10
# -------------------------------------------------- CAMERA SCROLLING ----------------------------------------#
self.debug_info()
def to_screen(self, x, y):
screen_x = (ORIGIN_X * TILE_X) + (x - y) * (TILE_X / 2)
screen_y = (ORIGIN_Y * TILE_Y) + (x + y) * (TILE_Y / 2)
return screen_x, screen_y
def draw_world(self):
for y in range(WORLD_Y):
for x in range(WORLD_X):
vWorld_x, vWorld_y = self.to_screen(x, y)
# Invisible tile
if self.index == 0:
self.screen.blit(self.tiles[1], (vWorld_x, vWorld_y))
# Grass
elif self.index == 1:
self.screen.blit(self.tiles[2], (vWorld_x - self.scroll_x, vWorld_y - self.scroll_y))
def draw(self):
self.screen.fill(BGCOLOUR)
self.draw_world()
self.mouse_selection.draw()
get_info(self.debug)
pygame.display.flip()
def debug_info(self):
self.debug["FPS"] = int(self.clock.get_fps())
self.debug["Cell"] = self.mouse_selection.cell_x, self.mouse_selection.cell_y
self.debug["Selected"] = int(self.mouse_selection.selected_x), int(self.mouse_selection.selected_y)
self.debug["Scroll"] = int(self.scroll_x), int(self.scroll_y)
self.debug["Mouse"] = int(self.mx), int(self.my)
self.debug["Mouse_offset"] = int(self.mouse_selection.offset_x), int(self.mouse_selection.offset_y)
def events(self):
# catch all events here
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
pass
game = Game()
while True:
game.new()
game.run()
Define the corner points of the map:
map_outline = [
pygame.math.Vector2(left_x, left_y),
pygame.math.Vector2(top_x, top_y),
pygame.math.Vector2(right_x, right_y,
pygame.math.Vector2(bottom_x, bottom_y)
]
With this information you can calculate the x and y axis of the map:
origin = map_outline[0]
x_axis = (map_outline[1] - map_outline[0]) / columns
y_axis = (map_outline[3] - map_outline[0]) / rows
You can use the x-axis and the y-axis to calculate a point in the map as a function of the row and column:
def transform(p, mat2x2):
x = p[0] * mat2x2[0][0] + p[1] * mat2x2[1][0]
y = p[0] * mat2x2[0][1] + p[1] * mat2x2[1][1]
return pygame.math.Vector2(x, y)
p_position = transform((column + 0.5, row + 0.5), (x_axis, y_axis)) + origin
If you want to get the row and column depending on the mouse cursor, you need to do the opposite. You need to calculate the inverse 2x2 matrix from the x and y axis. Using the inverse matrix, you can calculate the row and column as a function of a point on the map:
def inverseMat2x2(m):
a, b, c, d = m[0].x, m[0].y, m[1].x, m[1].y
det = 1 / (a*d - b*c)
return [(d*det, -b*det), (-c*det, a*det)]
m_pos = pygame.mouse.get_pos()
m_grid_pos = transform(pygame.math.Vector2(m_pos) - origin, point_to_grid)
m_col, m_row = int(m_grid_pos[0]), int(m_grid_pos[1])
Also see PyGameExamplesAndAnswers - Isometric
Minimal example:
replit.com/#Rabbid76/Pygame-IsometircMap
import pygame
pygame.init()
window = pygame.display.set_mode((500, 300))
clock = pygame.time.Clock()
colors = {'g': (40, 128, 40), 'd': (90, 60, 40)}
tilemap = [
'gdddg',
'dgddd',
'ggddg',
'ggddg',
'ddddg',
'dgggd'
]
columns, rows = len(tilemap[0]), len(tilemap)
isometric_tiles = {}
for key, color in colors.items():
tile_surf = pygame.Surface((50, 50), pygame.SRCALPHA)
tile_surf.fill(color)
tile_surf = pygame.transform.rotate(tile_surf, 45)
isometric_size = tile_surf.get_width()
tile_surf = pygame.transform.scale(tile_surf, (isometric_size, isometric_size//2))
isometric_tiles[key] = tile_surf
tile_size = (isometric_size, isometric_size//2)
def tileRect(column, row, tile_size):
x = (column + row) * tile_size[0] // 2
y = ((columns - column - 1) + row) * tile_size[1] // 2
return pygame.Rect(x, y, *tile_size)
game_map = pygame.Surface(((columns+rows) * isometric_size // 2, (columns+rows) * isometric_size // 4), pygame.SRCALPHA)
for column in range(columns):
for row in range(rows):
tile_surf = isometric_tiles[tilemap[row][column]]
tile_rect = tileRect(column, row, tile_size)
game_map.blit(tile_surf, tile_rect)
map_rect = game_map.get_rect(center = window.get_rect().center)
map_outline = [
pygame.math.Vector2(0, columns * isometric_size / 4),
pygame.math.Vector2(columns * isometric_size / 2, 0),
pygame.math.Vector2((columns+rows) * isometric_size // 2, rows * isometric_size / 4),
pygame.math.Vector2(rows * isometric_size / 2, (columns+rows) * isometric_size // 4)
]
for pt in map_outline:
pt += map_rect.topleft
origin = map_outline[0]
x_axis = (map_outline[1] - map_outline[0]) / columns
y_axis = (map_outline[3] - map_outline[0]) / rows
def inverseMat2x2(m):
a, b, c, d = m[0].x, m[0].y, m[1].x, m[1].y
det = 1 / (a*d - b*c)
return [(d*det, -b*det), (-c*det, a*det)]
point_to_grid = inverseMat2x2((x_axis, y_axis))
def transform(p, mat2x2):
x = p[0] * mat2x2[0][0] + p[1] * mat2x2[1][0]
y = p[0] * mat2x2[0][1] + p[1] * mat2x2[1][1]
return pygame.math.Vector2(x, y)
font = pygame.font.SysFont(None, 30)
textO = font.render("O", True, (255, 255, 255))
textX = font.render("X", True, (255, 0, 0))
textY = font.render("Y", True, (0, 255, 0))
p_col, p_row = 2, 2
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a and p_col > 0:
p_col -= 1
if event.key == pygame.K_d and p_col < columns-1:
p_col += 1
if event.key == pygame.K_w and p_row > 0:
p_row -= 1
if event.key == pygame.K_s and p_row < rows-1:
p_row += 1
p_position = transform((p_col + 0.5, p_row + 0.5), (x_axis, y_axis)) + origin
m_pos = pygame.mouse.get_pos()
m_grid_pos = transform(pygame.math.Vector2(m_pos) - origin, point_to_grid)
m_col, m_row = int(m_grid_pos[0]), int(m_grid_pos[1])
window.fill((0, 0, 0))
window.blit(game_map, map_rect)
pygame.draw.lines(window, (164, 164, 164), True, map_outline, 3)
pygame.draw.line(window, (255, 0, 0), origin, origin+x_axis, 3)
pygame.draw.line(window, (0, 255, 0), origin, origin+y_axis, 3)
pygame.draw.circle(window, (255, 255, 255), origin, 5)
pygame.draw.circle(window, (255, 0, 0), origin+x_axis, 5)
pygame.draw.circle(window, (0, 255, 0), origin+y_axis, 5)
window.blit(textO, textO.get_rect(topright = origin+(-5, 5)))
window.blit(textX, textX.get_rect(bottomright = origin+x_axis+(-5, -5)))
window.blit(textY, textX.get_rect(topright = origin+y_axis+(-5, 5)))
pygame.draw.ellipse(window, (255, 255, 0), (p_position[0]-16, p_position[1]-8, 32, 16))
if 0 <= m_grid_pos[0] < columns and 0 <= m_grid_pos[1] < rows:
tile_rect = tileRect(m_col, m_row, tile_size).move(map_rect.topleft)
pts = [tile_rect.midleft, tile_rect.midtop, tile_rect.midright, tile_rect.midbottom]
pygame.draw.lines(window, (255, 255, 255), True, pts, 4)
pygame.display.update()
pygame.quit()
exit()

Changing Selected Variables Chosen From Input()

I want to change different variables in my code while it's running, for example changing the variable speed = 1 to speed = 2 using the CMD. The variable I want to change is decided on the person running the code through an input(). They type in speed, and the variable speed changes to another number, also chosen by the person running the code through another input().
To change the values, you should need to-
.
Press Enter, to pause the game
Select the CMD window
Type 'setvar', then Enter
Type 'speed', then Enter
Type '5', then Enter
.
I want this to change speed = 1 to speed = 5, but I also want to be able to do this with every variable, being able to change the score variable, or anything else. So far, I have made it so you input the variable you want to change, and what you want to change it to. The code is slightly messy, but readable.
So far I have tried
exec("%s = %s" % (var,setTo))
and
exec(f"{var} = '{setTo}'")
But it hasn't worked, although speed = 5 does.
The code I want help with is near the bottom. The whole code is...
def RUN():
import pygame
import time
import random
import msvcrt as m
pygame.init()
dis_width = 800
dis_height = 600
score = 0
x = 375
y = 275
foodx = -100
foody = -100
speed = 1
stanima = 0
gotox = 200
gotoy = 200
gotoSet = []
goto = []
gotoSet.append(gotox)
gotoSet.append(gotoy)
goto.append(gotoSet)
people = []
numOfPeople = 1 # Number of people
foodEaten = True
foodRun = True
speedRunPlus = True
speedRunMinus = True
runningRun = True
clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 18)
dis = pygame.display.set_mode((dis_width, dis_height)) #screen stuff
pygame.display.set_caption('Game')
game_over = False
running = True
lightBlue = (50, 153, 213) #colors
red = (255, 100, 0)
yellow = (255, 255, 102)
blue = (70, 70, 255)
green1 = (0, 255, 0)
green2 = (0, 255, 25)
green3 = (0, 255, 50)
green4 = (0, 255, 75)
green5 = (0, 255, 100)
green6 = (0, 255, 125)
green7 = (0, 255, 150)
green8 = (0, 255, 175)
green9 = (0, 255, 200)
green10 = (0, 255, 225)
dis.fill(blue) #Backround
pygame.draw.rect(dis, lightBlue, [50, 50, 700, 500]) #Inner rectangle
def update_fps():
fps = str(int(clock.get_fps()))
fps = str("FPS: "+fps)
fps_text = font.render(fps, 1, pygame.Color("coral"))
return fps_text
def speedRender():
speed_str = str(speed)
speed_sentance = str("Average Speed: "+speed_str)
speed_text = font.render(speed_sentance, 1, pygame.Color("coral"))
return speed_text
def player(x, y, color, stamina): #Rectangle player
player = pygame.draw.rect(dis, color, [x, y, 25, 25])
if stanima == 1:
pygame.draw.rect(dis, red, [x+11, y+11, 3, 3])
elif stanima == 2:
pygame.draw.rect(dis, red, [x+10, y+10, 5, 5])
elif stanima == 3:
pygame.draw.rect(dis, red, [x+9, y+9, 7, 7])
elif stanima == 4:
pygame.draw.rect(dis, red, [x+8, y+8, 9, 9])
elif stanima == 5:
pygame.draw.rect(dis, red, [x+7, y+7, 11, 11])
elif stanima == 6:
pygame.draw.rect(dis, red, [x+6, y+6, 13, 13])
elif stanima == 7:
pygame.draw.rect(dis, red, [x+5, y+5, 15, 15])
elif stanima == 8:
pygame.draw.rect(dis, red, [x+4, y+4, 17, 17])
elif stanima == 9:
pygame.draw.rect(dis, red, [x+3, y+3, 19, 19])
def food(foodx, foody): #Rectangle food
food = pygame.draw.rect(dis, yellow, [foodx, foody, 10, 10])
for num1 in range(numOfPeople):
x = random.randint(300,400)
y = random.randint(300,400)
person = []
person.append(x)
person.append(y)
person.append(1)
person.append(goto)
person.append(score)
people.append(person)
while not game_over:
while running:
dis.fill(blue)
pygame.draw.rect(dis, lightBlue, [50, 50, 700, 500])
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
game_over = True
for num2 in range(numOfPeople):
x = people[0][0]
y = people[0][1]
#speed = people[0][2]
goto = people[0][3]
score = people[0][4]
del people[0]
if x+12 > foodx+5: # "AI"
x -= speed
elif x+12 < foodx+5:
x += speed
if y+12 > foody+5: # "AI"
y -= speed
elif y+12 < foody+5:
y += speed
if x > 725: #Creates Borders
x = 725
game_over = True
elif x < 50:
x = 50
game_over = True
if y > 525:
y = 525
game_over = True
elif y < 50:
y = 50
game_over = True
if x >= foodx-24 and x <= foodx+10:
if y >= foody-24 and y <= foody+10:
score += 1
foodEaten = True
#print("Score:", score)
person = []
person.append(x)
person.append(y)
person.append(1)
person.append(goto)
person.append(score)
people.append(person)
playerColor = green1
player(x, y, playerColor, stanima) #Creating Player
if foodEaten == True:
foodx = random.randint(90, 700)
foody = random.randint(90, 500)
stanima += 1
foodEaten = False
food(foodx, foody) #Creating Food
pressed = pygame.key.get_pressed() #Key Movement
if pressed[pygame.K_RCTRL]:
dis.blit(update_fps(), (10,0))
dis.blit(speedRender(), (100,0))
if pressed[pygame.K_SPACE]:
RUN()
if pressed[pygame.K_ESCAPE]:
running = False
game_over = True
if pressed[pygame.K_RSHIFT]:
if foodRun == True:
foodx = random.randint(90, 700)
foody = random.randint(90, 500)
stanima += 1
foodEaten = False
foodRun = False
else:
foodRun = True
if pressed[pygame.K_RETURN]:
if runningRun == True:
running = False
runningRun = False
print(" ")
else:
runningRun = True
if pressed[pygame.K_MINUS]:
if speedRunMinus == True:
speed -= 0.1
speedRunMinus = False
else:
speedRunMinus = True
if pressed[pygame.K_EQUALS]:
if speedRunPlus == True:
speed += 0.1
speedRunPlus = False
else:
speedRunPlus = True
pygame.display.flip() #updating screen
clock.tick()
if not game_over:
command = input(" :")
commandSplit = command.split(".")
#try:
if commandSplit[0] == "return":
var = input(" :")
if var in dir():
print(" :", eval(var), sep='')
else:
print(" :Variable Not Found")
elif commandSplit[0] == "run":
if commandSplit[1] == "exit":
running = False
game_over = True
elif commandSplit[0] == "setvar":
var = input(" :")
print("Var value now:", eval(var), sep='')
if var in locals():
setTo = input("Change variable to:") #Code I need help with -----------------------
print("Var value after:", eval(var), sep='')
else:
print(" :Invalid Syntax Error")
'''
except Exception:
print(" :Invalid Syntax Error")
pass
'''#to implement later
RUN()

Pygame - Fix issue with pause menu? [duplicate]

I've developed a Python code and am looking for improvements and how to add a pause option.
I repeat the exact same lines one after another although I don't know an easier way to do it.
import math, pygame, random, sys, turtle
from itertools import cycle
from datetime import datetime
from pygame import gfxdraw
from pygame.locals import *
def print_text(surface, font, text, surf_rect, x = 0, y = 0, center = False, color = (255,215,0)):
if not center:
textimage = font.render(text, True, color)
surface.blit(textimage, (x, y))
else:
textimage = font.render(text, True, color)
text_rect = textimage.get_rect()
x = (surf_rect.width // 2) - (text_rect.width // 2 )
surface.blit(textimage, (x, y))
def game_is_over(surface, font, ticks):
timer = ticks
surf_rect = surface.get_rect()
surf_height = surf_rect.height
surf_width = surf_rect.width
print_text(screen, font, "Y O U G O T Y E E T E D (Game Over)", surf_rect, y = 260,\
center = True)
pygame.display.update()
while True:
ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if ticks > timer + 3000:
break
def next_level(level):
level += 1
if level > 6:
level = 6
return level
#The Level Creator
def load_level(level):
invaders, colors = [], []
start_intx, end_intx, increment_intx = 85, 725, 40
start_inty, end_inty, increment_inty = 60, 60, 30
end_inty = end_inty + level * 30 # 30 being the number of rows / intruders
color_val = 256 / end_inty #For Colour Repetition
for x in range(start_intx, end_intx, increment_intx):
for y in range(start_inty, end_inty, increment_inty):
invaders.append(pygame.Rect(x, y, 30, 15))
colors.append(((x * 0.35) % 256, (y * color_val) % 256))
return invaders, colors, len(invaders)
def draw_title_invader():
rect = Rect(285,247,230,115)#INVATOR
rect2 = Rect(0,0,230,115)
rect3 = Rect(340,120,120,128)#TOP OF HAT
rect4 = Rect(300,200,200,48)#BOT OF HAT
rect5 = Rect(340,182,120,18)#LINE IN HAT
rect_width = 230
a = 175
b = 55
pygame.draw.rect(backbuffer, MGOLD,rect)
#The Left Eye in Title Screen
pygame.draw.circle(backbuffer,(0,255,255), (rect.x+46,rect.y+30), 23)
#The Right Eye in Title Screen
pygame.draw.circle(backbuffer,(0,255,255),(rect.x+rect_width-46,rect.y+30)\
,23)
#The Left Side Mouth in Title Screen
pygame.draw.line(backbuffer, RED, (rect.x+46, rect.y+92),\
(rect.x + 115, rect.y + 61), 2)
#The Right Side Mouth in Title Screen
pygame.draw.line(backbuffer, RED, (rect.x+rect_width-46,\
rect.y+92), (rect.x+rect_width-115,\
rect.y+61), 2)
#The Right Eye
pygame.draw.circle(backbuffer,RED,(rect.x+rect_width-115,rect.y+65)\
,23)
#The Hat
pygame.draw.rect(backbuffer, DIMGRAY,(340,120,120,128))
pygame.draw.rect(backbuffer, DIMGRAY,(300,200,200,48))
pygame.draw.rect(backbuffer, WHITE,(340,182,120,18))
def draw_bonus_invader(i, bonus_color, bx, bonus_x):
x, y = bonus_invader.x, bonus_invader.y
pygame.draw.circle(backbuffer, bonus_color, (x+bx, y+7), 2)
if i == 0:
pygame.draw.circle(backbuffer, bonus_color,
(bonus_invader.x+bx,bonus_invader.y+7),2)
if i == 1:
pygame.draw.circle(backbuffer, bonus_color,
(bonus_invader.x+bx,bonus_invader.y+7),2)
if i == 2:
pygame.draw.circle(backbuffer, bonus_color,
(bonus_invader.x+bx,bonus_invader.y+7),2)
if i == 3:
pygame.draw.circle(backbuffer, bonus_color,
(bonus_invader.x+bx,bonus_invader.y+7),2)
if i == 4:
pygame.draw.circle(backbuffer, bonus_color,
(bonus_invader.x+bx,bonus_invader.y+7),2)
if i == 5:
bx = next(bonus_x)
def draw_invader(backbuffer, rect, a, b, animate_invaders, ticks,\
animation_time):
invader_width = 30
#THe Intruder In Game
pygame.draw.rect(backbuffer, MGOLD, rect)
#CONSOLE GRAY
pygame.draw.rect(backbuffer, DIMGRAY,(0,510,800,110))
#Left Eye in game
pygame.gfxdraw.filled_circle(backbuffer, rect.x + 6, rect.y + 4, 3, \
RED)
#Right EYe in game
pygame.gfxdraw.filled_circle(backbuffer, rect.x + invader_width - 7,\
rect.y + 4, 3, RED)
#The draw animation (if needed)
if animate_invaders:
pygame.gfxdraw.filled_trigon(backbuffer, rect.x+6, rect.y + 12,\
rect.x + 14, rect.y + 4, rect.x +\
invader_width - 7, rect.y + 12, RED)
else:
#The Left Side of the mouth
pygame.gfxdraw.line(backbuffer, rect.x + 6, rect.y + 12,\
rect.x + 15, rect.y + 8, RED)
#The Right Side of the mouth
pygame.gfxdraw.line(backbuffer, rect.x + invader_width - 7,\
rect.y + 12, rect.x + invader_width - 15,\
rect.y + 8, RED)
if ticks > animation_time + 200:
animate_invaders = False
return animate_invaders
pygame.init()
pygame.mixer.init() # not always called by pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Yeet The Intruders")
fpsclock = pygame.time.Clock()
#get screen metrics
the_screen = screen.get_rect()
screen_width = the_screen.width
screen_height = the_screen.height
backbuffer = pygame.Surface((the_screen.width, the_screen.height))
# fonts
font1 = pygame.font.SysFont(None, 30)
font2 = pygame.font.SysFont("Impact", 54)
font3 = pygame.font.SysFont("Impact", 36)
# User event frequencies
RELOAD_SPEED = 400
MOVE_SIDEWAYS = 1000
MOVE_DOWN = 1000
BONUS_FREQ = 10000
INV_SHOOT_FREQ = 500
# create user events
move_invaders_sideways = pygame.USEREVENT + 1
move_invaders_down = pygame.USEREVENT + 2
reload = pygame.USEREVENT + 3
invader_shoot = pygame.USEREVENT + 4
bonus = pygame.USEREVENT + 5
# event timers
pygame.time.set_timer(move_invaders_down, 0)
pygame.time.set_timer(move_invaders_sideways, MOVE_SIDEWAYS)
pygame.time.set_timer(reload, RELOAD_SPEED)
pygame.time.set_timer(invader_shoot, INV_SHOOT_FREQ)
pygame.time.set_timer(bonus, BONUS_FREQ)
#List of Colours used
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
DIMGRAY = (105,105,105)
MGOLD = (212,175,55)
shots, invader_shots, inv_shot_colors, bonus_invaders = [], [], [], []
#MY Space Ship
player = Rect(380,578,42,20)
player_gun = Rect(player.x + 18,player.y - 4, 6, 4)
# make screen rect for purposes of text-centering etc
the_screen = screen.get_rect()
# invader animation variables
animation_time = 0
animate_invaders = False
invader_width = 30
invader_height = 15
# flashing text vars
the_text = cycle(["Press Enter To Play, Yeet Master...", ""])
insert = next(the_text)
flash_timer = 0
# flashing bonus item vars
y1,y2,y3,y4,y5,y6 = (255,255,0), (225,225,0), (195,195,0), (165,165,0),\
(135,135,0), (105,105,0)
bonus_colors = cycle([y1,y2,y3,y4,y5,y6])
bonus_color = next(bonus_colors)
bonus_x = cycle([4,11,18,25,32,39]) # change draw x coord
bonus_timer = 0 # used to control frequency of changes
# vars for moving invaders down
move_right, move_down, reloaded = True, True, True
vert_steps = 0
side_steps = 0
moved_down = False
invaders_paused = False
invaders = 0 # prevents error until list is created
initial_invaders = 0 # use to manage freq of inv shots as invaders removed
shoot_level = 1 # manage freq of shots
# various gameplay variables
game_over = True
score = 0
lives = 2
level = 0
playing = False
# event loop
while True:
ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYUP:
if event.key == pygame.K_1 and not game_over:
print("Next level")
if event.type == invader_shoot and not game_over:
i = random.randint(0, len(invaders)-1)
shot_from = invaders[i]
a, b = colors[i]
invader_fired = True
invader_shots.append(Rect(shot_from.x, shot_from.y, 5, 7))
inv_shot_colors.append(RED)
if event.type == reload and not game_over:
reloaded = True
pygame.time.set_timer(reload, 0)
if event.type == move_invaders_sideways and not game_over:
if move_right:
for invader in invaders: invader.move_ip(10,0)
side_steps += 1
else:
for invader in invaders: invader.move_ip(-10,0)
side_steps -= 1
if side_steps == 6 or side_steps == -6:
if vert_steps <= 31: # and not moved_down
pygame.time.set_timer(move_invaders_sideways, 0)
pygame.time.set_timer(move_invaders_down, MOVE_DOWN)
# keep invaders moving horizontally after 31 down movements
else: move_right = not move_right
if event.type == move_invaders_down and not game_over:
#for i in range(20): print("down event")
move_right = not move_right
animate_invaders = True
animation_time = ticks
# reset move_sideways timer
pygame.time.set_timer(move_invaders_sideways, MOVE_SIDEWAYS)
# cancel move_down timer
pygame.time.set_timer(move_invaders_down, 0)
for invader in invaders: invader.move_ip(0,10)
vert_steps += 1
if event.type == bonus and not game_over:
#a = Rect(769,20,45,15)
bonus_invaders.append(Rect(797,20,45,15))
# keyboard polling
pressed = pygame.key.get_pressed()
if pressed[K_ESCAPE]: pygame.quit(), sys.exit()
elif pressed[K_RETURN]:
if game_over: game_over = False
elif pressed[K_d] or pressed[K_RIGHT]:player.move_ip((8, 0))
#player_gun.move_ip((8,0))
elif pressed[K_a] or pressed[K_LEFT]: player.move_ip((-8, 0))
if pressed[K_SPACE]:
if reloaded:
reloaded = False
# create timeout of RELOAD_SPEED
pygame.time.set_timer(reload, RELOAD_SPEED)
# shrink copy of player rect to imitate a missile
missile = player.copy().inflate(-38, -10)
# spawn missile higher to ensure appears missile fired from 'gun'
# when the ship is moving horizontally
missile.y -= 9
shots.append(missile)
#missile_sound.play()
backbuffer.fill(BLACK)
if not game_over:
playing = True
if level == 0:
level = next_level(level)
invaders, colors, initial_invaders = load_level(level)
move_right, move_down, reloaded = True, True, True
vert_steps = 0
side_steps = 0
moved_down = False
invaders_paused = False
pygame.time.set_timer(invader_shoot, 500)
shoot_level = 1
for shot in invader_shots:
shot.move_ip((0,random.randint(5,11)))
if not backbuffer.get_rect().contains(shot):
i = invader_shots.index(shot)
del invader_shots[i]
del inv_shot_colors[i]
if shot.colliderect(player) and shot.y < the_screen.height -10:
lives -= 1
if lives < 0:
lives = 0
game_over = True
i = invader_shots.index(shot)
del invader_shots[i]
del inv_shot_colors[i]
for shot in shots:
shot.move_ip((0, -8))
for inv_shot in invader_shots:
if inv_shot.colliderect(shot):
shots.remove(shot)
i = invader_shots.index(inv_shot)
del invader_shots[i]
del inv_shot_colors[i]
for b_invader in bonus_invaders:
if b_invader.colliderect(shot):
shots.remove(shot)
i = bonus_invaders.index(b_invader)
del bonus_invaders[i]
score += 1
if not backbuffer.get_rect().contains(shot):
shots.remove(shot)
else:
hit = False
for invader in invaders:
if invader.colliderect(shot):
score += 1
hit = True
i = invaders.index(invader)
del invaders[i]
del colors[i]
if hit: shots.remove(shot)
# move bonus invader
for bonus_invader in bonus_invaders:
bonus_invader.move_ip((-4,0 ))
## if not screen.get_rect().contains(bonus_invader):
## bonus_invaders.remove(bonus_invader)
if bonus_invader.x < -55:
bonus_invaders.remove(bonus_invader)
# check if all invaders killed, if so, move to next level
if len(invaders) == 0:
level = next_level(level)
invaders, colors, initial_invaders = load_level(level)
move_right, move_down, reloaded = True, True, True
vert_steps = 0
side_steps = 0
moved_down = False
invaders_paused = False
pygame.time.set_timer(invader_shoot, 500)
shoot_level = 1
# adjust shot freq when invader numbers decrease
if len(invaders) < initial_invaders*.75 and shoot_level == 1:
pygame.time.set_timer(invader_shoot, 750)
shoot_level = 2
elif len(invaders) < initial_invaders*.5 and shoot_level == 2:
pygame.time.set_timer(invader_shoot, 1000)
shoot_level = 3
elif len(invaders) < initial_invaders*.25 and shoot_level == 3:
pygame.time.set_timer(invader_shoot, 1500)
shoot_level = 4
# draw invaders
for rect, (a, b) in zip(invaders, colors):
animate_invaders = draw_invader(backbuffer, rect, a, b,\
animate_invaders, ticks, \
animation_time)
# draw bonus invaders
if ticks > bonus_timer + 169:
bonus_timer = ticks # change colors every 169ms approx
for bonus_invader in bonus_invaders:
pygame.draw.rect(backbuffer, (0,0,0,0), bonus_invader)
pygame.draw.ellipse(backbuffer,MGOLD,bonus_invader)
for i in range(6):
bonus_color = next(bonus_colors)
bx = next(bonus_x)
draw_bonus_invader(i, bonus_color, bx, bonus_x)
# draw space ship shots
for shot in shots:
pygame.draw.rect(backbuffer, GREEN, shot)
# draw invader shots
for shot, color in zip(invader_shots, inv_shot_colors):
pygame.draw.rect(backbuffer, color, shot)
#update 'gun' position and draw ship/gun
#player_gun = Rect(player.x, player.y, 6, 4)
player_gun.x = player.x+18
pygame.draw.rect(backbuffer, (204,0,255), player)
pygame.draw.rect(backbuffer, (0,204,255), player_gun)
player.clamp_ip(backbuffer.get_rect())
print_text(backbuffer, font1, "Intruders Rekt#: {}".format(score),\
the_screen, x=0, y=520)
print_text(backbuffer, font1, "Hearts#: {}".format(lives), the_screen,\
x=0, y=550)
print_text(backbuffer, font1, "Round#: {}".format(level), the_screen,\
x=0, y=580)
if game_over:
if playing:
game_is_over(backbuffer, font2, ticks)
playing = False
level = 0
lives = 2
score = 0
shots, invader_shots, inv_shot_colors, bonus_invaders = [], [], [], []
print_text(backbuffer, font2, "_/¯Yeet The Intruders¯\_", the_screen, y=5,\
center=True)
draw_title_invader()
if ticks > flash_timer + 800: # "press to play" flashing text
insert = next(the_text)
flash_timer = ticks
print_text(backbuffer, font3, insert, the_screen, y =\
the_screen.height-40, center=True)
screen.blit(backbuffer, (0,0))
pygame.display.update()
fpsclock.tick(30)
Your code is quite large, but to pause the game is very general task:
Add a pause state.
Toggle the pause state on an certain event, e.g. when the p key is pressed.
Skip the game processing if pauseis stated.
e,.g.
pause = False # pause state
while True:
ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYUP:
if event.key == pygame.K_1 and not game_over:
print("Next level")
# toggle pause if "p" is pressed
if event.key == pygame.K_p:
pause = not pause
# [...]
if pause:
# [...] draw pause screen
pass
elif not game_over: # <--- elif is important
playing = True
# [...]
screen.blit(backbuffer, (0,0))
pygame.display.update()
fpsclock.tick(30)

How do I add a score tracker?

So I want it to count the score every time the snake eats a candy.
I haven't tried much, but I tried to find existing codes and adding them to mine but that just broke the game. I also tried to make my own score board by watching a tutorial, but I don't know where the code should go like at the beginning or end.
import pygame
import random
score = 0
welcome = ("Welcome to our snake game")
print(welcome)
class cube:
height = 20
w = 500
def __init__(movee,start,x=1,y=0,color=(0,0,0)):
movee.pos = start
movee.x = 1
movee.y = 0
movee.color = color
def move(movee, x, y):
movee.x = x
movee.y = y
movee.pos = (movee.pos[0] + movee.x, movee.pos[1] + movee.y)
def draw(movee, surface, eyes=False):
leng = movee.w // movee.height
i = movee.pos[0]
j = movee.pos[1]
pygame.draw.rect(surface, movee.color, (i*leng+1,j*leng+1, leng-2, leng-2))
class snake:
body = []
turns = {}
def __init__(movee, color, pos):
movee.color = color
movee.head = cube(pos)
movee.body.append(movee.head)
def move(movee):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed()
for key in keys:
if keys[pygame.K_LEFT]:
movee.x = -1
movee.y = 0
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_RIGHT]:
movee.x = 1
movee.y = 0
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_UP]:
movee.x = 0
movee.y = -1
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_DOWN]:
movee.x = 0
movee.y = 1
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
for i, c in enumerate(movee.body):
p = c.pos[:]
if p in movee.turns:
turn = movee.turns[p]
c.move(turn[0],turn[1])
if i == len(movee.body)-1:
movee.turns.pop(p)
else:
if c.x == -1 and c.pos[0] <= 0: c.pos = (c.height-1, c.pos[1])
elif c.x == 1 and c.pos[0] >= c.height-1: c.pos = (0,c.pos[1])
elif c.y == 1 and c.pos[1] >= c.height-1: c.pos = (c.pos[0], 0)
elif c.y == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.height-1)
else: c.move(c.x,c.y)
def add(movee):
tail = movee.body[-1]
dx, dy = tail.x, tail.y
if dx == 1 and dy == 0:
movee.body.append(cube((tail.pos[0]-1,tail.pos[1])))
elif dx == -1 and dy == 0:
movee.body.append(cube((tail.pos[0]+1,tail.pos[1])))
elif dx == 0 and dy == 1:
movee.body.append(cube((tail.pos[0],tail.pos[1]-1)))
elif dx == 0 and dy == -1:
movee.body.append(cube((tail.pos[0],tail.pos[1]+1)))
movee.body[-1].x = dx
movee.body[-1].y = dy
def draw(movee, surface):
for i, c in enumerate(movee.body):
if i ==0:
c.draw(surface, True)
else:
c.draw(surface)
def drawingAGrid(w, height, surface):
sizein = w // height
x = 0
y = 0
for l in range(height):
x = x + sizein
y = y + sizein
def redrawGrid(surface):
global height, width, s, snack
surface.fill((255,255,255))
s.draw(surface)
snack.draw(surface)
drawingAGrid(width, height, surface)
pygame.display.update()
def Candy(height, item):
positions = item.body
while True:
x = random.randrange(height)
y = random.randrange(height)
if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:
continue
else:
break
return (x,y)
def gameloop():
global width, height, s, snack, x_pos, y_pos, reset
width = 500
height = 20
win = pygame.display.set_mode((width, width))
s = snake((255, 0, 0), (10, 10))
snack = cube(Candy(height, s), color=(0, 0, 0))
flag = True
clock = pygame.time.Clock()
x_pos, y_pos = s.body[0].pos
while flag:
pygame.time.delay(50)
clock.tick(7)
s.move()
x, y = s.body[0].pos
if not -1 <= x - x_pos <= 1 or not -1 <= y - y_pos <= 1:
movee.reset((10,10))
x_pos, y_pos = s.body[0].pos
if s.body[0].pos == snack.pos:
s.add()
snack = cube(Candy(height, s), color=(0, 0, 0))
redrawGrid(win)
gameloop()
I just want like a scoreboard in any of the corners counting the score.
Use pygame.freetype to render text. e,g, crated a pygame.freetype.SysFont object:
import pygame.freetype
pygame.init()
font = pygame.freetype.SysFont('Times New Roman', 30)
The score is the number of body parts. Use str to convert a number to a text and .render() to render a text to a pygame.Surface object:
score = len(s.body)
text_surf, text_rect = font.render(str(score), (255, 0, 0), size=30)
Define a margin to the border of the window, calculate the text position (e.g. bottom right) and .blit the text to the window surfrace:
margin = 10
text_pos = (width - text_rect.width - margin, width - text_rect.height - margin)
surface.blit(text_surf, text_pos)
Function redrawGrid:
def redrawGrid(surface):
global height, width, s, snack
surface.fill((255,255,255))
s.draw(surface)
snack.draw(surface)
drawingAGrid(width, height, surface)
score = len(s.body)
text_surf, text_rect = font.render(str(score), (255, 0, 0), size=30)
margin = 10
text_pos = (width - text_rect.width - margin, width - text_rect.height - margin)
surface.blit(text_surf, text_pos)
pygame.display.update()

Categories

Resources