/r/pygame

Photograph via snooOG

Welcome to /r/PyGame!

What is PyGame?

Pygame is a set of Python modules designed for writing games.

Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language.

Pygame is highly portable and runs on nearly every platform and operating system.

Posting Guidelines

Despite the name, content related to other Python game libraries (pyglet, panda3d, etc.) is also welcome.

If asking for help with your code, please provide a link to the entire code and resources if possible. Consider making a Github account if you don't have one already.

How to Post Code

In Python indentation is part of the language syntax and as such is extremely important. When posting code every line must be indented an additional four spaces. You can indent the code in a text editor before pasting, or after pasting into reddit, highlight the text and press the editor button that looks like this <>.

You can also place small amounts of code inline by surrounding it with ticks:

`like this`

If you have a large amount of code to share it would be best use a third party site for posting code. Gist is a really good choice. For code that relies on external resources like images please create a repo on github or similar.

Posting Links

When posting links please provide a brief description in the comments of the thread. Failure to do so may result in post removal.

Installation

Installation notes for Microsoft Windows users

It is easier to install python32 and pygame32 even if you are running a 64-bit version of Microsoft Windows.

Useful links

Related Subreddits

/r/pygame

23,374 Subscribers

1

ive been making a tetris like game and i cant seem to add a rect to a list of rects

i have the command player.collidelistall(copyblock) where copyblock is a list of rects and player is one rect and when i put the command : copyblock.append(pygame.Rect(x*72, y*72, 72 ,72)) they show up on the screen but when the player goes next to them it doesnt do anything and the player just goes through them

3 Comments
2025/02/02
14:27 UTC

1

ive been making a tetris like game and i cant seem to add a rect to a list of rects

i have the command player.collidelistall(copyblock) where copyblock is a list of rects and player is one rect and when i put the command : copyblock.append(pygame.Rect(x*72, y*72, 72 ,72)) they show up on the screen but when the player goes next to them it doesnt do anything and the player just goes through them

0 Comments
2025/02/02
14:27 UTC

1

Enemy list -Pain for all!

Finally I could know how to wor with list in pygame, so I create a list of all enemys and a second list for their rectangle versions. Pygame check the list of the rectangled enemys who are avaible to get hurt by the "beans" I shoot to the enemy. Before I use much of code for every enemy! My Problem seems know that with my created code all enemy in the list got damage if I hit just one, I tried to get another list to append the enemys who got hurt but it it doesnt work, programm close bc of error. May be somebody knows to handle with my code giving me the improved version.

#List of enemys rectangled: self.enemy_list_rect = [self.iponashi.img_rect,self.oni_chan.img_rect, self.oni_chan_2.img_rect]

#List of enemys not rectangled :
self.enemy_list = [self.iponashi,self.oni_chan,self.oni_chan_2]

#checking collision with my list def collision(self): #if self.beans_img_rect.colliderect(self.game.iponashi.iponashi_img_rect): for i in self.game.enemy_list_rect: if self.beans_img_rect.colliderect(i): print("Ja") self.is_fired = False #print(self.game.enemy_list[0]) for u in self.game.enemy_list: if u.untoucheabel == "no": u.hp -= self.attack_damage u.untoucheabel = "yes" u.got_pain = "yes"

##But with my code all enemys got damage, how to give the damage only to the enemy who got hit by "beans"?

Thank you very much and happy Setsubun Day if you life in Japan.

2 Comments
2025/02/02
05:23 UTC

2

Help me.

I am making a pygame survival game and i just noticed a bug where my character moves faster while moving left or up only whenever the players speed variable is a decimal. this is really strange and doesnt make any sense to me. ( Also ignore the spaghetti code pls)

https://reddit.com/link/1ifoktq/video/afjwbb08fnge1/player

6 Comments
2025/02/02
03:53 UTC

1

Collision issue with moving platform

I am creating a simple 2d platformer using pygame. I've created a collision logic that works for static objects, but when i introduced a moving platform, there's a weird issue. If i stand on top of a moving vertical platform, i get transported to it's bottom. Similar case with the right and left of a horizontal moving platform. What could be the issue?

This is my collision logic:

def collision(self,axis):         for sprite in self.collision_sprites:             if sprite.rect.colliderect(self.rect):                 if axis == 'horizontal':                     if self.rect.left <= sprite.rect.right and int(self.old_rect.left) >= int(sprite.old_rect.right):                         self.rect.left = sprite.rect.right                      if self.rect.right >= sprite.rect.left and int(self.old_rect.right) <= int(sprite.old_rect.left):                         self.rect.right = sprite.rect.left                  else: #vertical                     if 
self.rect.top
 <= sprite.rect.bottom  and int(self.old_rect.top) >= int(sprite.old_rect.bottom):                         
self.rect.top
 = sprite.rect.bottom                      elif self.rect.bottom >= 
sprite.rect.top
  and int(self.old_rect.bottom) <= int(sprite.old_rect.top):                         self.rect.bottom = 
sprite.rect.top
                     self.direction.y=0 

Is there a noticeable issue here? Is there anything else i need to share?

9 Comments
2025/02/01
19:56 UTC

5

Why does pygame.FULLSCREEN get minimized when it loses focus?

Is there a way for a pygame app to always be full screen? My pygame app gets minimized whenever it loses focus.

1 Comment
2025/02/01
16:03 UTC

5

Feedback on my (missed) game jam project?

I attempted my first game jam over the past two weeks, Pirate Software Game Jam 16. Unfortunately, I didn't pay enough attention to the actual due time for submission, so I missed it by several hours when I went to submit after work yesterday. Not a mistake I'll make twice, though.

That said, I would definitely appreciate if anyone would be willing to give it a go and give me feedback!

Here's my itch.io page for the game.

It's unpolished, and the art is very rough (The assets I made, at least. The open assets are fine). But ultimately I feel the concept was realized well enough for the scale of a game jam. Other than missing the submission time, I feel like I had planned out my development milestones pretty well, and only had to make a few cutbacks for time.

Feedback I'm especially interested in:

  • Control feel. Is it intuitive?
  • Level design. The levels were intended to let the player figure out mechanics on their own with minimal explicit guidance. Did that work our?
  • Level difficulty. No one other than me has played these levels as of posting, so I have no idea if the levels are too easy, too hard, swing wildly in difficulty, etc.

Thank you very much for your consideration!

6 Comments
2025/02/01
14:49 UTC

4

How can I check if mouse position is in a Polygon shape?

4 Comments
2025/02/01
09:18 UTC

7

Tools for creating pixel art

Hi, I'm learning pygame. I would like to know about tools for creating my own sprites, fonts and maps. Also, what are good sources for free arts as well? Thanks in advance.

11 Comments
2025/01/31
17:52 UTC

3

Collision from diffrent sides

Hello dear comunity, now I am creating objects like trees, bambo in my game. The main character (girl) should be notable to pass this obstacles. After a lot of try and error I could find some working code wich allow me to stop my maincharcter trough obstacles.

def bounce(self, source, target):
    if not source.colliderect(target): return
    overlap = source.clip(target)

    if overlap.width > overlap.height:
        if source.y < target.y:
            source.bottom = target.top
            self.game.girl.y = self.game.girl.y - 7
            print("oben wand")
        else:
            source.top = target.bottom
            self.game.girl.y = self.game.girl.y + 7
            print("unten Wand")

    else:
        if source.x < target.x:
            source.right = target.left
            self.game.girl.x = self.game.girl.x -7
            print("links Wand")
        else:
            source.left = target.right
            self.game.girl.x = self.game.girl.x + 7
            print("rechts Wand")

############################# call this usefull function self.game.funktionen.bounce(self.game.girl.girl_img_rect, self.snowman_rect)

I tried many times to change this function so even enemy or other moving objects wont be able to pass but I couldnt find a good solution yet. Just copy and paste and creating the same function for other characters, but I suppose there is a more better way.

Thank you!

3 Comments
2025/01/31
15:46 UTC

1

car racing game colision handling help

for my car to rotate in game i made the function:
def rotate_car(game, image, top_left, angle):rotated_image = pygame.transform.rotate(image, angle)

new_rect = rotated_image.get_rect(center=image.get_rect(topleft=top_left).center)

game.blit(rotated_image, new_rect.topleft)

and it works good but it doesnt rotate the mask, i didnt notice it because i hade an outline between the track and the border and only discovered it while making a new track without it.

rotating the mask of the car is easy and i did it not problem but i faced a new problem that the static mask saved me from which is rotating the car into a border and get stuck because the image is 19x38, so i made it that the car cannot rotate into border but then i get a new problem considering i have drift in the game i can by mistake collide from the center (for imagination door location on real car) and then i cant move.

im seeking help in creative ideas to fix it, handle it better or change it completly if i dont have any way of fixing it i might have to compromise on making it so that collision will make the player lose, and not handle that with physics changes.

game example of getting stuck with blocked rotation into wall

car.python code:

import math

import pygame

from pygame.math import Vector2

from Constants import *

class Car(pygame.sprite.Sprite):

def __init__(self, x, y, car_color="Red"):

super().__init__()

self.position = Vector2(x, y)

self.previous_position = Vector2(x, y)

self.previous_angle = 0

self.car_color = car_color

self.img = pygame.image.load(CAR_COLORS[car_color]).convert_alpha()

self.image = pygame.transform.scale(self.img, (19, 38))

self.original_image = self.image

self.rect = self.image.get_rect(center=self.position)

self.mask = pygame.mask.from_surface(self.image)

self.max_velocity = MAXSPEED

self.velocity = 0

self.rotation_velocity = ROTATESPEED

self.angle = 0

self.acceleration = ACCELERATION

self.drift_angle = 0

self.drift_momentum = 0

self.drift_factor = 0.1

self.drift_friction = 0.87

self.grip = 0.95

self.recovery_slowdown = 0.6

self.collision_recovery_factor = 0.8

def rotate(self, left=False, right=False):

self.previous_angle = self.angle

if left:

self.angle += self.rotation_velocity

if abs(self.velocity) > self.max_velocity * 0.5:

self.drift_momentum -= self.velocity * self.drift_factor

elif right:

self.angle -= self.rotation_velocity

if abs(self.velocity) > self.max_velocity * 0.5:

self.drift_momentum += self.velocity * self.drift_factor

self.image = pygame.transform.rotate(self.original_image, self.angle)

self.rect = self.image.get_rect(center=self.rect.center)

self.mask = pygame.mask.from_surface(self.image)

def move(self):

self.previous_position = Vector2(self.position)

self.previous_angle = self.angle

radians = math.radians(self.angle + self.drift_angle)

direction = Vector2(math.sin(radians), math.cos(radians))

perp_direction = Vector2(math.cos(radians), -math.sin(radians))

movement = direction * self.velocity + perp_direction * self.drift_momentum

self.position -= movement

self.rect.center = self.position

self.drift_momentum *= self.drift_friction

self.drift_angle *= self.drift_friction

def handle_border_collision(self):

self.position = Vector2(self.previous_position)

self.angle = self.previous_angle

self.image = pygame.transform.rotate(self.original_image, self.angle)

self.rect = self.image.get_rect(center=self.position)

self.mask = pygame.mask.from_surface(self.image)

self.velocity *= -self.recovery_slowdown * self.collision_recovery_factor

self.drift_momentum *= -self.recovery_slowdown * self.collision_recovery_factor

self.drift_angle *= self.collision_recovery_factor

def check_and_handle_rotation_collision(self, mask, offset_pos=(0, 0)):

rotated_mask = pygame.mask.from_surface(self.image)

if offset_pos == (0, 0):

offset = (int(self.rect.left), int(self.rect.top))

else:

offset = (int(self.rect.left - offset_pos[0]),

int(self.rect.top - offset_pos[1]))

if mask.overlap(rotated_mask, offset):

if offset_pos != (0, 0):

overlap_area = mask.overlap_area(rotated_mask, offset)

if overlap_area <= 5:

self._restore_previous_rotation()

return True

return False

else:

self._restore_previous_rotation()

return True

return False

def _restore_previous_rotation(self):

self.angle = self.previous_angle

self.image = pygame.transform.rotate(self.original_image, self.angle)

self.rect = self.image.get_rect(center=self.position)

self.mask = pygame.mask.from_surface(self.image)

def accelerate(self, forward=True):

if forward:

self.velocity = min(self.velocity + self.acceleration, self.max_velocity)

else:

self.velocity = max(self.velocity - self.acceleration, -self.max_velocity / 2)

self.drift_momentum *= self.grip

self.move()

def reduce_speed(self):

if self.velocity > 0:

self.velocity = max(self.velocity - self.acceleration * 0.3, 0)

elif self.velocity < 0:

self.velocity = min(self.velocity + self.acceleration * 0.3, 0)

self.move()

def reset(self, x=None, y=None):

if x is not None and y is not None:

self.position = Vector2(x, y)

self.velocity = 0

self.angle = 0

self.drift_momentum = 0

self.drift_angle = 0

self.rect.center = self.position

self.image = pygame.transform.rotate(self.original_image, self.angle)

self.rect = self.image.get_rect(center=self.position)

self.mask = pygame.mask.from_surface(self.image)

4 Comments
2025/01/30
21:54 UTC

6

Help me please

Guys help me with this code ( its my first please dont judge me XD )

import pygame import sys

Initialize Pygame

pygame.init()

Set up display

width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("Move the Red Box")

Define colors

red = (255, 0, 0) black = (0, 0, 0)

Box properties

box_width, box_height = 50, 50 box_x = width // 2 • box_width // 2 box_y = height // 2 • box_height // 2 box_speed = 5

Game loop

while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()

# Get keys pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:  # Move left
    box_x -= box_speed
if keys[pygame.K_d]:  # Move right
    box_x += box_speed

# Fill the background
screen.fill(black)

# Draw the red box
pygame.draw.rect(screen, red, (box_x, box_y, box_width, box_height))

# Update the display
pygame.display.flip()

# Frame rate
pygame.time.Clock().tick(60)
9 Comments
2025/01/30
11:58 UTC

3

3d Perspective Moving

I followed a tutorial up to here. I understand the core concept as to whats at play. I also understand matrix multiplication a little. I just need to figure out on how to move the camera based on where the camera is at if that makes sense, Also the tutorial never covered this.

mport pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

vertices = ((1, -1, -1),
(1,1,-1),
(-1, 1, -1),
(-1, -1, -1),
(1, -1, 1),
(1, 1, 1),
(-1, -1, 1),
(-1 , 1, 1)

)

edges = (
(0, 1),
(0, 3),
(0, 4),
(2, 1),
(2, 3),
(2, 7),
(6, 3),
(6, 4),
(6, 7),
(5, 1),
(5, 4),
(5,7)
)

def Cube():
glBegin(GL_LINES)

for edge in edges:
for vertex in edge:
#Function draws vertex
glVertex3fv(vertices[vertex])

glEnd()

def handle_movement():
key = pygame.key.get_pressed()
if key[pygame.K_w]:
glTranslatef(0.0, 0.0, 0.01)
if key[pygame.K_s]:
glTranslatef(0.0, 0.0, -0.01)
if key[pygame.K_a]:
glTranslatef(0.01, 0.0, 0.0)
if key[pygame.K_d]:
glTranslatef(-0.01, 0.0, 0.0)

glRotatef(400-pygame.mouse.get_pos()[0], 0, 10 ,0)
pygame.mouse.set_pos((400, 300))

def main():
pygame.init()
pygame.display.set_mode((800, 600), DOUBLEBUF|OPENGL)

#Sets up perspective
gluPerspective(45, (800/600), 0.1, 40.0)
glTranslatef(0.0, 0.0, -5)
glRotatef(0, 0, 0, 0)

clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

handle_movement()

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

Cube()

pygame.display.flip()
clock.tick(60)

main()

0 Comments
2025/01/30
01:15 UTC

0

I need help to separate a code.

Hello,

Maybe I was naive, but I wanted to create a video game with ChatGPT to see how far we could go. At some point, I ended up with 3,000 lines of code and got limited due to OpenAI's token restrictions. So, I'm trying to split the code, but I'm struggling with it. I don't know if it's possible. If you have any advice, that would be great.
I uploaded the code for download on Itch.io at the link.

Thank very much

11 Comments
2025/01/29
12:54 UTC

1

Game slowing down over time

I am making my 1'st game (snake). When I try playing it at fisrt it is perfect, then as times go on it goes slower and slower to the point of crush. What I can do fix this

import random
import pygame
from sys import exit

pygame.init()   #Initiate pygame (always include)
screen = pygame.display.set_mode((720,480))
pygame.display.set_caption("Barczi_Snake")
clock = pygame.time.Clock()


#visual background
background = pygame.Surface((720,480))
background.fill("Black")
frontground = pygame.Surface((460,460))
frontground.fill("White")
font = pygame.font.Font(None, 50)   #(type, size)
text = font.render("Snake", True, "white")


#Objects
snakehead = pygame.Surface((18,18))
snakehead.fill("black")

snakebody = pygame.Surface((16,16))
snakebody.fill("black")

apple = pygame.Surface((14,14))
apple.fill("red")



x_snake = 240
y_snake = 220
x_tail=[x_snake-40, x_snake-20, x_snake]
y_tail=[y_snake, y_snake, y_snake]
x_apple = 460
y_apple = 220

score=0
tick=0
lastpress="right"


while True:     #draw scene/update

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()      #end .py script



        #Button presses
        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT] and x_snake+20!=x_tail[-2]:
            lastpress="right"
        if keys[pygame.K_LEFT] and x_snake-20!=x_tail[-2]:
            lastpress="left"
        if keys[pygame.K_UP] and y_snake-20!=y_tail[-2]:
            lastpress="up"
        if keys[pygame.K_DOWN] and y_snake+20!=y_tail[-2]:
            lastpress="down"



    #Background
    screen.blit(background,(0,0))
    screen.blit(frontground,(130,10))
    screen.blit(text,(600, 10))



    #Head drawing
    if lastpress=="right":
        screen.blit(snakehead, (x_snake,y_snake+1))
    elif lastpress=="left":
        screen.blit(snakehead, (x_snake+2,y_snake+1))
    elif lastpress=="up":
        screen.blit(snakehead, (x_snake+1,y_snake+2))
    elif lastpress=="down":
       screen.blit(snakehead, (x_snake+1,y_snake))


  
    #Tail drawing
    for i in range(len(x_tail)):
        if i==len(x_tail)-1:
            if x_snake-20==x_tail[i]:
               screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
               screen.blit(snakebody, (x_tail[i]+6, y_tail[i]+2))
            elif x_snake+20==x_tail[i]:
                screen.blit(snakebody, (x_tail[i]-2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
            elif y_snake-20==y_tail[i]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+6))
            elif y_snake+20==y_tail[i]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]-2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
        else:
            if x_tail[i]+20==x_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+6, y_tail[i]+2))
            elif x_tail[i]-20==x_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]-2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
            elif y_tail[i]+20==y_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+6))
            elif y_tail[i]-20==y_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]-2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))



    #Apple
    screen.blit(apple,(x_apple+2, y_apple+2))



    tick=tick+1
    if tick == 5:
        tick=0
        


        #Head position
        if lastpress=="right":
            x_snake = x_snake+20
        if lastpress=="left":
            x_snake = x_snake-20
        if lastpress=="up":
            y_snake = y_snake-20
        if lastpress=="down":
            y_snake = y_snake+20
                
                

        #Lose detection
        if x_snake>=580 or x_snake<=120 or y_snake>=460 or y_snake<=10:
            pygame.quit()
            exit()
        for i in range(len(x_tail)):
            if x_snake == x_tail[i] and y_snake == y_tail[i]:
                pygame.quit()
                exit()



        #Tail position
        x_tail.append(x_snake)
        y_tail.append(y_snake)



        #Apple detection
        if x_snake == x_apple and y_snake == y_apple:
            score=score+1
            print(score)

            m=0
            while m==0:
                x_apple = 120+random.randint(1,22)*20
                y_apple = random.randint(1,22)*20
            
                if x_apple!=x_snake or y_apple!=y_snake:
                    if x_apple in x_tail:
                        if y_apple == y_tail[x_tail.index(x_apple)]:
                            pass
                    elif y_apple in y_tail:
                        if x_apple == x_tail[y_tail.index(y_apple)]:
                            pass
                    else:
                        m=1

        else:
            x_tail.pop(0)
            y_tail.pop(0)
        


    pygame.display.update()
    clock.tick(30)
import random
import pygame
from sys import exit


pygame.init()   #Initiate pygame (always include)
screen = pygame.display.set_mode((720,480))
pygame.display.set_caption("Barczi_Snake")
clock = pygame.time.Clock()



#visual background
background = pygame.Surface((720,480))
background.fill("Black")
frontground = pygame.Surface((460,460))
frontground.fill("White")
font = pygame.font.Font(None, 50)   #(type, size)
text = font.render("Snake", True, "white")



#Objects
snakehead = pygame.Surface((18,18))
snakehead.fill("black")


snakebody = pygame.Surface((16,16))
snakebody.fill("black")


apple = pygame.Surface((14,14))
apple.fill("red")




x_snake = 240
y_snake = 220
x_tail=[x_snake-40, x_snake-20, x_snake]
y_tail=[y_snake, y_snake, y_snake]
x_apple = 460
y_apple = 220


score=0
tick=0
lastpress="right"



while True:     #draw scene/update


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()      #end .py script




        #Button presses
        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT] and x_snake+20!=x_tail[-2]:
            lastpress="right"
        if keys[pygame.K_LEFT] and x_snake-20!=x_tail[-2]:
            lastpress="left"
        if keys[pygame.K_UP] and y_snake-20!=y_tail[-2]:
            lastpress="up"
        if keys[pygame.K_DOWN] and y_snake+20!=y_tail[-2]:
            lastpress="down"




    #Background
    screen.blit(background,(0,0))
    screen.blit(frontground,(130,10))
    screen.blit(text,(600, 10))




    #Head drawing
    if lastpress=="right":
        screen.blit(snakehead, (x_snake,y_snake+1))
    elif lastpress=="left":
        screen.blit(snakehead, (x_snake+2,y_snake+1))
    elif lastpress=="up":
        screen.blit(snakehead, (x_snake+1,y_snake+2))
    elif lastpress=="down":
       screen.blit(snakehead, (x_snake+1,y_snake))



  
    #Tail drawing
    for i in range(len(x_tail)):
        if i==len(x_tail)-1:
            if x_snake-20==x_tail[i]:
               screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
               screen.blit(snakebody, (x_tail[i]+6, y_tail[i]+2))
            elif x_snake+20==x_tail[i]:
                screen.blit(snakebody, (x_tail[i]-2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
            elif y_snake-20==y_tail[i]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+6))
            elif y_snake+20==y_tail[i]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]-2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
        else:
            if x_tail[i]+20==x_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+6, y_tail[i]+2))
            elif x_tail[i]-20==x_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]-2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
            elif y_tail[i]+20==y_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+6))
            elif y_tail[i]-20==y_tail[i+1]:
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]-2))
                screen.blit(snakebody, (x_tail[i]+2, y_tail[i]+2))




    #Apple
    screen.blit(apple,(x_apple+2, y_apple+2))




    tick=tick+1
    if tick == 5:
        tick=0
        



        #Head position
        if lastpress=="right":
            x_snake = x_snake+20
        if lastpress=="left":
            x_snake = x_snake-20
        if lastpress=="up":
            y_snake = y_snake-20
        if lastpress=="down":
            y_snake = y_snake+20
                
                


        #Lose detection
        if x_snake>=580 or x_snake<=120 or y_snake>=460 or y_snake<=10:
            pygame.quit()
            exit()
        for i in range(len(x_tail)):
            if x_snake == x_tail[i] and y_snake == y_tail[i]:
                pygame.quit()
                exit()




        #Tail position
        x_tail.append(x_snake)
        y_tail.append(y_snake)




        #Apple detection
        if x_snake == x_apple and y_snake == y_apple:
            score=score+1
            print(score)


            m=0
            while m==0:
                x_apple = 120+random.randint(1,22)*20
                y_apple = random.randint(1,22)*20
            
                if x_apple!=x_snake or y_apple!=y_snake:
                    if x_apple in x_tail:
                        if y_apple == y_tail[x_tail.index(x_apple)]:
                            pass
                    elif y_apple in y_tail:
                        if x_apple == x_tail[y_tail.index(y_apple)]:
                            pass
                    else:
                        m=1


        else:
            x_tail.pop(0)
            y_tail.pop(0)
        



    pygame.display.update()
    clock.tick(30)
7 Comments
2025/01/28
21:33 UTC

2

Which one is better for performance?

Lets say we have a huge list of classes, and each class has a list of coordinates that has to be followed, my question is, is it better to preprocess all of the classes lists at the beggining of the program, or process them at runtime?

5 Comments
2025/01/28
21:02 UTC

0 Comments
2025/01/28
20:06 UTC

1

how do i draw multiple circles at once

im making a physics sim but idk how to draw multiple circles and i need to do that so no flickering occurs

8 Comments
2025/01/28
19:23 UTC

1

BUG: the mystery of unequal movement

EDIT this is solved. It was an issue with floats and integers as described in the comments.

I programmed my game following tutorials such as this great one by Matt Owen. Also it's not my first pygame rodeo. However, I recently decided to double the resolution of my game so I could implement characters moving at different speeds and have a greater range between the slowest and fastest. (having a very low resolution and characters moving at one pixel per frame gave me quite a high minimum speed).

Anyway, since I started tinkering with the resolution, now my player character has started to behave oddly. When moving down or to the right (that is, adding to his x or y coordinates) he moves slower than he does when moving up or to the left (that is, subtracting from his x or y coordinates). This occurs whether I run in window or at full screen.

At this stage I've been through the code line by line and also redone the whole physics by going back to the tutorials to make sure I didn't put the wrong operator somewhere or miss out a key line, but it is still a mystery and the bug is still there.

I also tried to debug by putting all the attributes: vel, acc, fric, total change to x and total change to y, on screen, but when moving left or up, the character somehow keeps moving even once these values have all dropped to zero. Somehow somewhere there is extra value being applied to the minus direction, and not the plus.

Has anyone else had this and been able to resolve it?

    self.speed = 60
    self.force = 2000
    self.acc = vec()
    self.vel = vec()
    self.changex = vec()
    self.changey = vec()
    self.fric = -15

def movement(self):
    if INPUTS['left']:
        self.acc.x = -self.force
    elif INPUTS['right']:
        self.acc.x = self.force
    else:
        self.acc.x = 0

    if INPUTS['up']:
        self.acc.y = -self.force
    elif INPUTS['down']:
        self.acc.y = self.force
    else:
        self.acc.y = 0

def physics(self, dt):
    self.acc.x += self.vel.x * self.fric
    self.vel.x += self.acc.x * dt
    self.changex = self.vel.x * dt + (self.vel.x/2) * dt
    self.rect.centerx += self.changex
    self.hitbox.centerx = self.rect.centerx
    self.collisions('x', self.current_scene.block_sprites)

    self.acc.y += self.vel.y * self.fric
    self.vel.y += self.acc.y * dt
    self.changey = self.vel.y * dt + (self.vel.y/2) * dt
    self.rect.centery += self.changey
    self.hitbox.centery = self.rect.centery
    self.collisions('y', self.current_scene.block_sprites)
10 Comments
2025/01/28
18:37 UTC

6

Using time in a simple way

Hello everybody I am still new to pygame and my english is not the best.

I am programing a game wich is zelda (a link to the past/links awakening), when the enemy hits the player I want to use a timer to of 3 seconds, to give the player the status not attackable for 3 seconds.

I tried some code it works for the first encounter with the enemy the player lose one hp heart and got a break (3 seconds), but when I touch the emy after break the second time break seems to be skipped and player got damage up to 50+ .

My code:

Enemy touch player:

if self.iponashi_img_rect.colliderect(self.game.girl.girl_img_rect):
    if self.game.girl.untoucheabel == "no":
        print("Fuck")
        self.game.girl.hp -= self.attack_damage
        self.game.girl.untoucheabel = "yes"
        print(self.game.girl.untoucheabel)
        self.game.girl.say = "shit"
        self.game.zeit.got_pain  = "yes" #hier wird die unverwunbarkeit aktiviert!
        print("self.attack_damage")

after he touch enemy can`t make damage anymore.

I try to set the timer (next example) so he is able to make her damage again:

class Zeit:
    def __init__(self, game, x=0, y=0):
        self.game = game
        self.startzeit = pygame.time.get_ticks()  # Meine Zeit
############
        self.start_pain = pygame.time.get_ticks()  # Zeit von der das Mädchen verletzt wurde
        self.got_pain = "no"       #Gegner aktiviert bei berührung Yes
        self.no_damage_timer = 0
#Startzeiten von verschiedenen Timern (oben)
#unverwundbarkeitstimer, eventimer Tageszeit timer, pflanzen timer, wetter timmer
#testet ob diese funktion aktiviert wurde, oder schon schon aktiv ist/ durch anderen gegner Angriff im Gange ist
    # und
    def pain_time(self):
        if self.got_pain == "yes":
            self.no_damage_timer = (pygame.time.get_ticks() - self.start_pain) // 3000
            if self.no_damage_timer >= 3:
                self.game.girl.untoucheabel = "no"
                self.no_damage_timer = 0
                if self.game.girl.say == "shit":
                    self.game.girl.say = "nothing"

first round timer works for 3 seconds/ no damage and after 3 seconds enemy could make damage again.

BUT no break of 3 seconds any more, as you can see I tried to set the timer to 0, but it doesn`t had an impact.

If you find my mistake or have more better / easy way to solve this problem let me know.

Also I have interesst to use mulitple timer for growing plants, day and night time, or events.

Thank you for your time and advices

2 Comments
2025/01/28
08:19 UTC

3

How do people make these bouncing ball videos?

6 Comments
2025/01/28
01:22 UTC

1

how to create a pop-up box in pygame

Hello I am a beginner to pygame and I am creating a tower defense game similar to bloon tower defence and i am stuck on implementing pop-up box to select the difficulty and maps.Currently to select maps i am just drawing buttons on a separate tab/window/canvas.

If anyone is more experienced in pygame please say or link some code on how to make a pop-up box?????

2 Comments
2025/01/27
21:52 UTC

2

3D camera rotation

I am working on a 3D game and I want the camera to have aeroplane-like movement. The best way I can describe this is that I want the camera to always rotate around its relative axis and not the world’s axis. So far I have only managed to make camera movement like the one in Minecraft where if you look straight up and then move your mouse to one side the camera spins on the spot. I apologise if my explanations are not the best. Could someone please help me with achieving what I want, especially with the maths behind it.

Thank you in advance.

3 Comments
2025/01/27
18:23 UTC

Back To Top