/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

22,762 Subscribers

6

Optimizing image loading.

Its taking 9.16s for my game to load assets on launch (i5 4440).

6.4s of those are used executing python.image.load. Im loading around 400 640x800 jfif images, around 110kb each (its a card game).

is this performance expected ? its there something else i can do to optimize it further without implementing a resource manager ? (I already optimized the grayscale convertion).

def load_image(image_path, width, height, type):

image_index = image_path + type

if image_index not in image_cache:

if type == "grayscale":

image_cache[image_index] = convert_to_grayscale(image_path)

else:

converted_image = pygame.image.load(image_path).convert()

image_cache[image_index] = pygame.transform.smoothscale(converted_image , (width, height))

return image_cache[image_index]

5 Comments
2024/12/02
04:57 UTC

2

"import pygame" Doesn't Work Even With Python and Pygame Downloaded

When I try importing pygame into VSCode with "import pygame" the output says:

Traceback (most recent call last):
  File "/Users/Germosen/Desktop/5games/Space Shooter/code/main.py", line 1, in <module>
    import pygame
ImportError: No module named pygame

When I run."pip3 install pygame" in the terminal (and VS terminal) in says the requirement is already satisfied, and when I run "python3 —version" in terminal to see if python is downloaded, it says "Python 3.13.0" meaning it is. I've tried solving this for two hours straight but nothing's working.

1 Comment
2024/12/02
02:00 UTC

4

How to add title/image as the title screen.

Hello!

So as the title states, I'm trying to import a custom image I created to be used for my Pygame project, which then I'll import text and button commands later on in the development of the project. However, I'm having difficulties with properly displaying the image, as everything I've tried doesn't actually show the image.

This is the code I have now:

import sys, pygame, os
pygame.init()

titledest = '/Users/urmemhay/Documents/Python Projects/finalprojectprogramming2/TitleScreen.png'
size = width, height = 1280, 1040
screen = pygame.display.set_mode(size)
title = pygame.image.load(titledest)

pygame.display.(title, (0,0))
pygame.display.update()

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

For some reason, all I get is a black screen, but want to actually--for now--display the image I loaded. Any advice would be appreciated!

3 Comments
2024/11/30
23:25 UTC

0

I'm trying to make Risk of Rain returns in Pygame. Would that be possible and if so what advice would you give? (this is for non-commercial use so im not making money off of this)

I plan to take the games sprites and animations to shorten dev time but how would I get enemy AI to work and randomly spawn enemies as well as the time = difficulty aspect of the game not to mention interactables such as the chests as well as procedural generation (i found a piece of code to do that for me but what about collision on map geometry etc)

3 Comments
2024/11/30
17:25 UTC

3

self.kill

i thought self.kill would remove a single sprite but it does not.

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill(white)
        self.rect = self.image.get_rect(center=(x, y))
        self.speed = 5
        self.font: pygame.Font = pygame.font.SysFont("arial", 15)
        self.hp: int = 100
        self.enemies: int = 0
        self.health_surface: pygame.Surface = pygame.Surface((0, 0))
        self.enemy_surface: pygame.Surface = pygame.Surface((0, 0))

        self.render_surfaces()

    def render_surfaces(self):
        self.health_surface = self.font.render(f"Health: {self.hp}", True, "gold")
        self.enemy_surface = self.font.render(f"Enemies: {self.enemies}", True, "white")

    def display(self, surface: pygame.Surface) -> None:
        surface.blit(self.health_surface, (735, 60))
        surface.blit(self.enemy_surface, (0, 0))

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            self.rect.x -= self.speed
        if keys[pygame.K_d]:
            self.rect.x += self.speed
        if keys[pygame.K_w]:
            self.rect.y -= self.speed
        if keys[pygame.K_s]:
            self.rect.y += self.speed

        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > screen_width:
            self.rect.right = screen_width
        if self.rect.top < 0:
            self.rect.top = 0
        if self.rect.bottom > screen_height:
            self.rect.bottom = screen_height

        if pygame.sprite.spritecollide(self, enemies, False):
            self.hp -= 1
            grunt.play()
            print('collide detected!')

        if self.hp <= 0:
            self.hp = 0
            self.kill()

  
9 Comments
2024/11/30
02:38 UTC

207

Made in Pygame --- My Keyboard is Full of Ants (1st Place Overall, Ludum Dare 56)

12 Comments
2024/11/29
18:52 UTC

6

Basic networking of simple multiplayer game

I want to create a distributed systems project: a multiplayer game inspired by Overcooked, where 1 to 4 players collaborate to cook. I plan to use Python with Pygame and socket(i heard also about Twisted is good). However, I have some doubts: which architecture would be better for this project, peer-to-peer, client-server or something else? UDP or TCP? Are there any useful packages, tools, or frameworks I should consider? Any reccomandations are welcomed!

9 Comments
2024/11/29
12:35 UTC

3

Help with pygame code

I've been following the tutorial series made by KidsCanCode but after episode 6 of the tile-based game my code isn't working the same as his. I have the exact same code as him but I don't know if its because the video is 8 years old or if its because he is using Atom Editor and I'm using VS Code. This is the code used.

https://reddit.com/link/1h2ejnb/video/pn8qq4rlzr3e1/player

3 Comments
2024/11/29
05:22 UTC

1

Space Invaders Enemy Movement

How can I move my space invader where there is a break each time the character moves.

I posted a link to show an example of what I am looking for

https://www.google.com/url?sa=i&url=https%3A%2F%2Fdribbble.com%2Fshots%2F4933082-Space-Invaders&psig=AOvVaw3gxvWinsNnMfbcqPHLVyy9&ust=1732937569342000&source=images&cd=vfe&opi=89978449&ved=0CBMQjRxqFwoTCLCzzdTNgIoDFQAAAAAdAAAAABBd

2nd FILE

def enemy1(self):
    evil = pygame.transform.scale(pygame.image.load(self.red), (self.width, self.height))
    return evil

def enemy2(self):
    evil = pygame.transform.scale(pygame.image.load(self.yellow), (self.width, self.height))
    return evil

def enemy3(self):
    evil = pygame.transform.scale(pygame.image.load(self.green), (self.width, self.height))
    return evil

def update_enemy_position(self, enemy_velocity):
    self.y_pos += enemy_velocity

1st FILE 

enemy1 = Enemy(50, 50, 260, 42)
enemy2 = Enemy(50, 50, 316, 42)
enemy3 = Enemy(50, 50, 370, 42)

enemy_velocity = 0.5

# Enemy Movement
enemy1.update_enemy_position(enemy_velocity)
enemy2.update_enemy_position(enemy_velocity)
enemy3.update_enemy_position(enemy_velocity)
1 Comment
2024/11/29
03:36 UTC

3

[Help] Finding clicked Tile with Isometric Grid & Partial Tiles

I have a 40x40 grid made up of 32x32 tiles. The tiles are technically 32x32, but the actual content (the surface) is of a different size as 32 pixels are not entirely taken by content:

upper part is transparent, lower is just a 3D effect

I managed to figure out how to line them up visually (visual content ends up being 16x16), and that's working properly. I can even blit a coloured surface with a button, and have it line up perfectly. However, it is too expensive to use this approach for all 1600 tiles so I have been trying to use maths to figure out based on coordinates.

I have failed miserably. The column and row are off, most of the time. For the record, I was able to work out these issues when building a top down grid.

Below is a simplified version of the code, perhaps someone can help. I tried Gemini and ChatGPT and no luck.

How the tiles are generated:

def square_to_iso(self, tile_pos: TilePosType) -> Coordinates:
        x,y = tile_pos
     
        x_iso = x - y
        y_iso = (x + y) / 2
        adjusted_height = self.TILE_SIZE // 2
        adjusted_width = self.TILE_SIZE // 2

        screen_x = (x_iso * adjusted_width) + self.GRID_OFFSET
        screen_y = (y_iso * adjusted_height) + self.GRID_OFFSET // 10

        return (screen_x, screen_y)

    
def create_tile(self, x:int, y:int, col:int, row:int) -> GridInfoType:
        top_left = (x, y)
        top_right = (x + self.TILE_SIZE, y)
        bottom_left = (x, y + self.TILE_SIZE)
        bottom_right = (x + self.TILE_SIZE, y + self.TILE_SIZE)

        return {
            "vertices": (top_left, top_right, bottom_left, bottom_right)
        }
        
    
def create_grid_map(self) -> GridConfState:
        grid_ref = {}
   
        for row, rows in enumerate(self.layout_path):
            for col, col_type in enumerate(rows):
                x_iso, y_iso = self.square_to_iso((col, row))
                grid_ref[(col, row)] = self.create_tile(x_iso, y_iso, col, row, col_type)

        return grid_ref 

How I'm trying to match up the click to a given tile:

def isometric_to_square(self, screen_x: int, screen_y: int) -> TilePosType:
        adjusted_x = screen_x - MapGrid.GRID_OFFSET
        adjusted_y = screen_y - (MapGrid.GRID_OFFSET // 10)

        x_iso = adjusted_x / (MapGrid.TILE_SIZE / 2)
        y_iso = adjusted_y / (MapGrid.TILE_SIZE / 2)

        x = int((x_iso + y_iso) / 2)
        y = int((y_iso - x_iso) / 2)

        return (x, y)
    
    def handle_click(self, mouse_pos: tuple[int, int]) -> bool:
            tile = self.isometric_to_square(mouse_pos[0], mouse_pos[1])
            if tile[0] > -1 and tile[1] > -1:
                self.selected_pawn.move_to_tile(tile)

        return clicked_on_ui_elem 

Thanks in advance to any potential helpers.

2 Comments
2024/11/28
17:00 UTC

3

Converted .py --> .exe | Windows 11 Deletes File

Hey everyone,

I am experiencing some issues when converting / running a basic .py file into a .exe file. Each time the executable file is created, and I try to run it, it just disappears. I thought I was making mistakes during the conversion process, but this happens also when I use 'non-manual' solutions like auto-py-to-exe and similar.

What should I check?

I know you may be thinking it's an Antivirus problem, and indeed it was at the beginning: Malwarebytes was detecting as a threat the .exe file, but even putting that in a whitelist hasn't really solved the problem.

Suggestions?

6 Comments
2024/11/28
15:51 UTC

23

2.5 Car Game Completed

https://dinnerbone2718.github.io/gameDownloads/

https://reddit.com/link/1h1nxv1/video/9wbwbs8plk3e1/player

This took about a month - 2 months to make. First fully finished game I have ever made. I only really gave up at the end to burnout ngl. The github link is there to a download of the game. If you want the code just contact me or something. Github was making it hard to upload being that its over 100 files (It took me liike an hour to figure out how to do it with the download exe for the game and I dont feel like doing it again). But please like let me know what I can change on future projects. I am probably done with this one for now.

8 Comments
2024/11/28
04:36 UTC

3

Sticks and Stones: Survival Game Projectile & Shoot Mechanics Test

Welcome to our latest survival game test! In this video, we dive deep into the projectile and shoot mechanics of our upcoming game, 'Sticks and Stones.' Watch as we put the game's mechanics to the ultimate test, showcasing how players can effectively use projectiles and shooting to survive in a harsh, unforgiving environment. Whether you're a game developer, a survival game enthusiast, or just curious about the behind-the-scenes of game mechanics, this video is for you! Don't forget to like, comment, and subscribe for more gaming content!

Will be swapped with fully animated spites, this is mostly a mechanics test :)
Full View Version with debug print etc:

https://youtu.be/K258JT_gZ3o

Mobile Version:

https://youtube.com/shorts/WSr4jcuJFHM

Other socials if you are interested in checking out the development phase:

https://x.com/SASSPvP

https://discord.com/invite/skyMbz869K

1 Comment
2024/11/28
01:52 UTC

2

Help with projectiles

I’ve made a space invader clone, but can only fire a single stream of lasers from the middle of my ship.

My spaceship sprite that I made has guns on each wing, so I want to figure out how to fire twin lasers from the sides of the sprite rather than firing a single shot from the center. Any advice?

6 Comments
2024/11/28
01:27 UTC

4

pygame-ce freetype?

I switched from pygame to pygame-ce and am now getting an error with my import pygame.freetype "could not be resolved in pylance". does pygame-ce not have freetype?

11 Comments
2024/11/28
00:45 UTC

1

Posted events never trigger?

I am working on a simple imlementation of Snake in pygame as a timepasser on my phone, and I can't wrap my head around why keyboard events never trigger. I am on android, so when the android keyboard never worked, I was unsurprised since Pygame was not written with it in mind. But, despite intepreting touches correctly as mouse events and triggering code in corresponding functions, posted events never go off so I can't seem to get generated events to work.

Here is my full code, posted to pastebin to make it easier to read:

https://pastebin.com/pEmtmLJJ

If anyone has any suggestions, please let me know.

3 Comments
2024/11/27
02:30 UTC

2

An Update to Simple_Events: Pygbag Support

I recently released my event handling library, simple_events, and was asked if it supported pygbag conversion. It did not, and this was a problem given how important pygbag is for distribution these days.

So, I set out to rectify that, and rectify it I have!

Today, I release version 1.1.0, now with async-aware support for working with tools like pygbag.

So for anyone who might have been interested but needed pygbag, you should consider checking it out again.

Links

You can find the project page here.

The project's Github can be found here.

####Sincerely, The Better Built Fool

3 Comments
2024/11/26
17:48 UTC

11

Pygame that uses basic matrices and basic local network multiplayer

This game "Glid" is inspired by chain reaction, Game of Life and othello/reversi game. Though chain reaction was not really part of it. In this game I also implemented basic client and server to enable local network multiplayer. It was fun making the multiplayer and I have learned alot.

github link: https://github.com/Swif7ify/Clashing-Grid-Pygame.git

I'd appreciate any feedback on how I can further improve the code.

3 Comments
2024/11/26
16:17 UTC

Back To Top