/r/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.
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.
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.
When posting links please provide a brief description in the comments of the thread. Failure to do so may result in post removal.
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.
/r/pygame
Pygame-ce, the modern of pygame, has released a new version (last week, but nobody posted it here yet!)
Installation--
โ๏ธ๐๐ป๐ธ๏ธ๐ท๏ธ๐ง๐งโโ๏ธ๐งโโ๏ธ๐งโโ๏ธ๐ฏ๏ธ๐ชฆ๐ฌ๐ญ๐ซโ ๏ธโฐ๏ธ๐ฎ๐งน๐๐โโฌ๐ฆ๐pip uninstall pygame
ย (if previously installed, to avoid package conflicts)pip install pygame-ce --upgrade
โ๏ธ๐๐ป๐ธ๏ธ๐ท๏ธ๐ง๐งโโ๏ธ๐งโโ๏ธ๐งโโ๏ธ๐ฏ๏ธ๐ชฆ๐ฌ๐ญ๐ซโ ๏ธโฐ๏ธ๐ฎ๐งน๐๐โโฌ๐ฆ๐
pygame.Window
has left experimental status and now been declared public API. This release sees two new additions: Window.flash
method and Window.focused
property.pygame.typing
pygame.geometry
APItransform.solid_overlay
functiondesktop
argument to mouse.get_pos
and mouse.get_pressed
pygame.Sound
alias to denote pygame.mixer.Sound
+ Plenty of other enhancements and fixes.
For the full release notes see our GitHub page: https://github.com/pygame-community/pygame-ce/releases/tag/2.5.2
We would appreciate reports of any regressions or ideas for the project-- either on this post, on the pygame community discord, or on GitHub. Have fun pygame-ing!
Hello, I am in a first semester engineering course and have a python class. I have an assignment where I am supposed to recreate a game from scratch.
Me and my friends ended um choosing to recreate HeadSoccer, at the beginning it was all fun and games but it is starting to get harder.
I was wondering if someone could refer me to a guide or tell me what would be the best way to create ball physics for the game.
I was able to create the ball and have it react with the players but it only stays on the floor.
Hope someone can help me out! Thanks!
I am fairly new to pygame, and am trying to figure out how to create hit boxes for more accurate collision logic. For the most part, the inflate option provides a close to good enough solution for almost all sprites and their respective frames.
However, this approach provides a less than desirable outcomes when the player is mounted on a wall, stationing the player within the terrain. For this particular state, the sprite is attached to the edge of a 32x32 px frame white the rest are roughly centered.
I've made varying attempts to define state-specific hit boxes, but my solutions have each induced sporadic behavior, causing the program to fluctuate between a wall slide animation and the next-best state given the conflicting logic.
What would be a more viable approach to communicate the different hit box needs programmatically?
Edit: Including code to provide added context (Apologies in advance, also new to posting on reddit):
def move(self, dt):
# horizontal
self.rect.x += self.direction.x * self.speed * dt
self.collision('horizontal')
# vertical
if not self.on_surface['floor'] and any((self.on_surface['left'], self.on_surface['right'])) and not self.timers['wall slide delay'].active:
self.direction.y = 0
self.rect.y += self.gravity / 10 * dt
else:
self.direction.y += self.gravity / 2 * dt
self.rect.y += self.direction.y * dt
self.direction.y += self.gravity / 2 * dt
if self.jumping:
if self.on_surface['floor']:
self.frame_index = 0
self.direction.y = -self.jump_height
self.timers['double jump delay'].activate()
self.timers['double jump window'].activate()
self.rect.bottom -= 1
elif any((self.on_surface['left'], self.on_surface['right'])) and not self.timers['wall slide delay'].active:
self.timers['wall jump'].activate()
self.direction.x = 1 if self.on_surface['left'] else -1
self.jumping = False
self.collision('vertical')
def check_contact(self):
floor_rect = pygame.Rect(self.rect.bottomleft, (self.rect.width, 2))
right_rect = pygame.Rect(self.rect.topright + vector(0, self.rect.height / 4), (2, self.rect.height / 2))
left_rect = pygame.Rect(self.rect.topleft + vector(-2, self.rect.height / 4), (2, self.rect.height / 2))
collide_rects = [sprite.rect for sprite in self._collision_sprites]
self.on_surface['floor'] = True if floor_rect.collidelist(collide_rects) >= 0 else False
self.on_surface['left'] = True if left_rect.collidelist(collide_rects) >= 0 else False
self.on_surface['right'] = True if right_rect.collidelist(collide_rects) >= 0 else False
def collision(self, axis):
for sprite in self._collision_sprites:
if sprite.rect.colliderect(self.rect):
if axis == 'horizontal':
# left collision
if self.rect.left <= sprite.rect.right and int(self.old_rect.left) >= int(sprite.old_rect.right):
self.rect.left = sprite.rect.right
# right collision
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
# top collision
if self.rect.top <= sprite.rect.bottom and int(self.old_rect.top) >= int(sprite.old_rect.bottom):
self.rect.top = sprite.rect.bottom
# bottom collision
if 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
x
Hi,
How can I be making camera zoom to where my mouse is pointing to? I tried to do it, but when I zoom in or out it steps a little from the original position.
I'll leave full code:
import pygame, sys, time
from World import world
from Camera import camera
pygame.init()
# Window
window_size = (800, 600)
window = pygame.display.set_mode(window_size, pygame.RESIZABLE | pygame.DOUBLEBUF)
# Clock
clock = pygame.time.Clock()
FPS = 60
last_time = time.time()
world = world()
camera = camera(world)
# Running
running = True
# Loop
while running:
dt = time.time() - last_time
last_time = time.time()
clock.tick(FPS)
pygame.display.set_caption(f'FPS = {round(clock.get_fps())}')
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEWHEEL:
camera.scrolling = True
camera.initial_zoom -= event.y
camera.update(dt)
pygame.quit()
sys.exit()
import pygame
# class world is the class that determines the world surface
class world:
def __init__(self):
self.size = (16 * 100, 16 * 100)
self.tile_size = (8, 8)
self.surface = pygame.Surface(self.size)
self.rect = self.surface.get_rect()
self.draw()
def draw(self):
num_tiles = (self.size[0] // self.tile_size[0], self.size[1] // self.tile_size[1])
for row in range(num_tiles[0]):
for col in range(num_tiles[1]):
pygame.draw.rect(self.surface, 'darkgreen' if (col + row) % 2 == 0 else 'forestgreen', pygame.Rect(
row * self.tile_size[0], col * self.tile_size[1], self.tile_size[0], self.tile_size[1]))
import pygame
from pygame import mouse
class camera:
def __init__(self, world):
self.screen = pygame.display.get_surface()
self.world = world
# Basic Settings
self.initial_zoom = 16
self.size = (16 * self.initial_zoom, 16 * self.initial_zoom)
self.direction = pygame.Vector2(0, 0)
self.pos = [0, 0]
self.speed = 100
# Camera Rect
self.rect = pygame.Rect(self.pos, self.size)
self.rect.center = self.world.rect.center
self.pos = [self.rect.x, self.rect.y]
self.world_mouse_pos = None
# Scrolling
self.scrolling = False
self.distance = None
def get_mouse_pos(self):
# Mouse position
self.screen_mouse_pos = pygame.mouse.get_pos()
# Get mouse pos only when value is higher than 0
if self.screen_mouse_pos[0] and self.screen_mouse_pos[1] > 0:
# Convert mouse pos from screen to camera
self.world_mouse_pos = (((self.size[0] * self.screen_mouse_pos[0]) // self.screen.get_size()[0]),
(self.size[1] * self.screen_mouse_pos[1] // self.screen.get_size()[1]))
# Add the distance from world to camera
self.world_mouse_pos = (self.world_mouse_pos[0] + self.rect.x, self.world_mouse_pos[1] + self.rect.y)
# Turn vector
self.world_mouse_pos = pygame.Vector2(self.world_mouse_pos)
return self.world_mouse_pos
def move(self, dt):
# Track Keys
keys = pygame.key.get_pressed()
# Clamp camera pos into world bounds
self.pos[0] = (max(0, min(self.pos[0], 16 * 100 - self.size[0])))
self.pos[1] = (max(0, min(self.pos[1], 16 * 100 - self.size[1])))
# Adjust speed if Shift is held
self.speed = 200 if keys[pygame.K_LSHIFT] else 100
# Get direction
self.direction[0] = keys[pygame.K_d] - keys[pygame.K_a] # Horizontal
self.direction[1] = keys[pygame.K_s] - keys[pygame.K_w] # Vertical
# Normalize vector, so it won't be faster while moving to the corners (horizontal + vertical)
if self.direction.magnitude() > 0:
self.direction = self.direction.normalize()
# Calculate position with speed and delta time
self.pos[0] += self.direction[0] * self.speed * dt
self.pos[1] += self.direction[1] * self.speed * dt
# Update rect pos and clamp camera inside world rect
self.rect.topleft = self.pos
self.rect = self.rect.clamp(self.world.rect)
def zoom(self):
if self.scrolling:
# Clamp zoom
self.initial_zoom = max(16, min(self.initial_zoom, self.world.size[1] // 16))
camera_center = pygame.Vector2(self.rect.center)
# Update size and rect
self.size = (16 * self.initial_zoom, 16 * self.initial_zoom)
self.rect = pygame.Rect(self.pos, self.size)
self.distance = self.world_mouse_pos - camera_center
self.rect.center = self.distance + camera_center
# Update position based on new center of rect
self.pos = [self.rect.x, self.rect.y]
# Clamp the camera inside world rect
self.rect = self.rect.clamp(self.world.rect)
# Reset scrolling
self.scrolling = False
print(self.world_mouse_pos, self.distance, self.rect.center)
if mouse.get_pressed()[0]:
pygame.draw.circle(self.world.surface, 'black', self.world_mouse_pos, 5)
def update_surface(self, screen):
# Create and update camera surface
self.surface = pygame.Surface.subsurface(self.world.surface, self.rect)
# Scale camera
self.surface = pygame.transform.scale(self.surface, screen.get_size())
# Blit into screen and update
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
def update(self, dt):
self.get_mouse_pos()
self.move(dt)
self.zoom()
self.update_surface(self.screen)
I've notices the github issues page seems to be filled with random code snippits that seem to just exist. Some are even labeled as enhancements or bugs with no report or explanation. Any ideas what's up with that? or is that just how it is? I rarely need to look into pygame issues so I'm really not sure if that's just normal in the community. Really makes it a pain to look through issues though.
my current code still scrolls left or right when the player is at the top or bottom of the screen, how do I make it go up or down?
I got the code from here: https://youtu.be/6gLeplbqtqg?si=5j7gn5RRHnyDqIwk&t=4952
I was able to change it so that the background moves when the player is at the top or bottom of the screen, but it still moves left or right, how would I make it go up and down?
Here is the rest of this code: https://pastebin.com/4jXe1xsK
ย def main_2(window):
offset_y = 0
scroll_area_width = 200 #how close to edge for scrolling background
ย ย ย
while run:
if ((player.rect.top - offset_y >= HEIGHT - scroll_area_width) and player.y_vel > 0) or (
ย ย ย ย ย ย ย ย (player.rect.bottom - offset_y <= scroll_area_width) and player.y_vel < 0):
ย ย ย ย ย ย offset_y += player.y_vel
I am making a 2d naval piracy and trading game and during initial testing it runs great at 100 fps. When I try to implement a map made with the Tiled software the frame rate plummets to 2-3. I am at work without the code available but I am hoping you all can help me spitball ideas on how to resolve it.
Before I implemented the Tiled map the game was generating a 10000x10000 pixel map with some poorly drawn islands and with the Tiled map it's trying to run 2500x2500.
I think a major problem would be the game spawns roughly 100 ships that check with the Tiled map each frame to check for collisions.
Also each ship does appear to be checking every frame if they are in range to fire on any other ship.
The program only draws a ship if they are within 1000 pixels of the player.
Is there anything j can do to try to make this more efficient?
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = player_img
self.direction = True
def flip(self):
self.direction = False
self.image = pygame.transform.flip(self.image, True, False)
screen.blit(self.image, (self.rect.x, self.rect.y))
i was trying to figure out why it isnt flipping. so i got the player at player = Player() and at
player = pygame.sprite.GroupSingle(player)
player.update()
player.draw(screen)
can someone help me with this one? it just didnt work last time.
Hey, I created the following code by my own, that is the camera of my game, that is based on a subsurface from world, so it do automatically dirty clean.
I'm scaling the camera surface to the size of the screen ('window'), so when I rezise window, it rezise camera too.But I feel that have a little distortion by doing that, also when I move by x direction, is faster than when I move to y direction, due the distortion caused.
There is the code. Take a look:
import pygame
class camera:
def __init__(self, world):
self.screen = pygame.display.get_surface()
= world
# Basic Settings
self.initial_zoom = 16
self.size = (16 * self.initial_zoom, 16 * self.initial_zoom)
self.direction = pygame.Vector2(0, 0)
self.pos = [0, 0]
self.speed = 100
# Camera Rect
self.rect = pygame.Rect(self.pos, self.size)
self.rect.center = self.world.rect.center
self.pos = [self.rect.x, self.rect.y]
def move(self, dt):
# Track Keys
keys = pygame.key.get_pressed()
# Clamp camera pos into world bounds
self.pos[0] = (max(0, min(self.pos[0], 16 * 100 - self.size[0])))
self.pos[1] = (max(0, min(self.pos[1], 16 * 100 - self.size[1])))
if keys[pygame.K_LSHIFT]:
self.speed = 100 # it was 200...
else:
self.speed = 100
# Get direction
self.direction[0] = keys[pygame.K_d] - keys[pygame.K_a] # Horizontal
self.direction[1] = keys[pygame.K_s] - keys[pygame.K_w] # Vertical
# Normalize vector, so it won't be faster while moving to the corners (horizontal + vertical)
if self.direction.magnitude() > 0:
self.direction = self.direction.normalize()
# Calculate position with speed and delta time
self.pos[0] += self.direction[0] * self.speed * dt
self.pos[1] += self.direction[1] * self.speed * dt
# Update rect pos and clamp camera inside world rect
self.rect.topleft = self.pos
self.rect = self.rect.clamp(self.world.rect)
def zoom(self):
# Clamp zoom
self.initial_zoom = max(16, min(self.initial_zoom, self.world.size[0] // 16))
# Store center
center =
# Update size and rect
self.size = (16 * self.initial_zoom, 16 * self.initial_zoom)
self.rect = pygame.Rect(self.pos, self.size)
# Reuse center to always zoom to the center of camera
= center
# Update position based on new center of rect
self.pos = [self.rect.x, self.rect.y]
# Clamp the camera inside world rect
self.rect = self.rect.clamp(self.world.rect)
def update_surface(self, screen):
# Create and update camera surface
self.surface = pygame.Surface.subsurface(self.world.surface, self.rect)
# Scale camera
self.surface = pygame.transform.scale(self.surface, screen.get_size())
# Blit into screen and update
self.screen.blit(self.surface, (0, 0))
pygame.display.update()
def update(self, dt):
self.move(dt)
self.zoom()
self.update_surface(self.screen)self.worldself.rect.centerself.rect.center
Also if u want full code, I can give.
https://reddit.com/link/1gfitd6/video/pt7hmdkd8vxd1/player
I updated my game with more fighters and a selection menu. Now the game feels fuller. I've released the update and I hope you guys will show some love to my first game, it's free to download.
HERE: https://aaditya-upreti.itch.io/forest-fury
Below is a link to my game developed in pygame that runs in the browser with touch input for smart phones in portrait mode (640ร720).
Got it pretty well optimized so it does not lag to much. Let me know what you think ๐
import sys
import pygame
from pygame.constants import K_SPACE
import spritesheet
import random
pygame.init()
WIDTH = 750
HEIGHT = 750
win = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
attack_sheet = pygame.image.load("NewPiskel12-ezgif.com-crop (2) (2).png").convert_alpha()
sprite_image = pygame.image.load("NewPiskel12-ezgif.com-gif-to-sprite-converter (2).png").convert_alpha()
sprite_image_Left = pygame.image.load("NewPiskel12-ezgif.com-gif-to-sprite-converter (1) (1) (1).png").convert_alpha()
sprite_attack_left = pygame.image.load("NewPiskel12-ezgif.com-crop (2) (1) (1).png").convert_alpha()
ennemy_image = pygame.image.load("NewPiskel1-ezgif.com-gif-to-sprite-converter (2).png")
sprite_sheet = spritesheet.SpriteSheet(sprite_image)
sprite_sheet2 = spritesheet.SpriteSheet(attack_sheet)
sprite_sheet_Left = spritesheet.SpriteSheet(sprite_image_Left)
sprite_sheet3 = spritesheet.SpriteSheet(sprite_attack_left)
sheet_enemy = spritesheet.SpriteSheet(ennemy_image)
black = (0, 0, 0)
animation_steps = [3, 1, 15, 3, 1, 15]
animation_list = [
[sprite_sheet.get_image(0, 32, 32, 3, black),
sprite_sheet.get_image(1, 32, 32, 3, black),
sprite_sheet.get_image(2, 32, 32, 3, black)],
[sprite_sheet.get_image(3, 32, 32, 3, black)],
[sprite_sheet2.get_image(0, 32, 32, 3, black),
sprite_sheet2.get_image(1, 32, 32, 3, black),
sprite_sheet2.get_image(2, 32, 32, 3, black),
sprite_sheet2.get_image(3, 32, 32, 3, black),
sprite_sheet2.get_image(4, 32, 32, 3, black),
sprite_sheet2.get_image(5, 32, 32, 3, black),
sprite_sheet2.get_image(6, 32, 32, 3, black),
sprite_sheet2.get_image(7, 32, 32, 3, black),
sprite_sheet2.get_image(8, 32, 32, 3, black),
sprite_sheet2.get_image(9, 32, 32, 3, black),
sprite_sheet2.get_image(10, 32, 32, 3, black),
sprite_sheet2.get_image(11, 32, 32, 3, black),
sprite_sheet2.get_image(12, 32, 32, 3, black),
sprite_sheet2.get_image(13, 32, 32, 3, black),
sprite_sheet2.get_image(14, 32, 32, 3, black)],
[sprite_sheet_Left.get_image(0, 32, 32, 3, black),
sprite_sheet_Left.get_image(1, 32, 32, 3, black),
sprite_sheet_Left.get_image(2, 32, 32, 3, black)],
[sprite_sheet_Left.get_image(3, 32, 32, 3, black)],
[sprite_sheet3.get_image(0, 32, 32, 3, black),
sprite_sheet3.get_image(1, 32, 32, 3, black),
sprite_sheet3.get_image(2, 32, 32, 3, black),
sprite_sheet3.get_image(3, 32, 32, 3, black),
sprite_sheet3.get_image(4, 32, 32, 3, black),
sprite_sheet3.get_image(5, 32, 32, 3, black),
sprite_sheet3.get_image(6, 32, 32, 3, black),
sprite_sheet3.get_image(7, 32, 32, 3, black),
sprite_sheet3.get_image(8, 32, 32, 3, black),
sprite_sheet3.get_image(9, 32, 32, 3, black),
sprite_sheet3.get_image(10, 32, 32, 3, black),
sprite_sheet3.get_image(11, 32, 32, 3, black),
sprite_sheet3.get_image(12, 32, 32, 3, black),
sprite_sheet3.get_image(13, 32, 32, 3, black),
sprite_sheet3.get_image(14, 32, 32, 3, black)],
]
animation_cooldown = 100
attackAnimation_cooldown = 20
action = 0
frame = 0
last_update = pygame.time.get_ticks()
border_rect = pygame.Rect(0, 0, 750, 750)
character_color = (0, 0, 0)
character_size = 4
class Enemy:
def __init__(self, x, y):
self.x = x
self.y = y
self.rect = pygame.Rect(self.x, self.y, 50, 50)
self.sheet_enemy = sheet_enemy
self.velx = 0
self.vely = 0
self.speed = 1
self.animation_cooldown = 100
self.last_update = pygame.time.get_ticks()
self.frame = 0
self.animation_list = [
self.sheet_enemy.get_image(0, 32, 32, 3, black), # Frame 0
self.sheet_enemy.get_image(1, 32, 32, 3, black), # Frame 1
self.sheet_enemy.get_image(2, 32, 32, 3, black), # Frame 2
self.sheet_enemy.get_image(3, 32, 32, 3, black), # Frame 3
self.sheet_enemy.get_image(4, 32, 32, 3, black), # Frame 4
self.sheet_enemy.get_image(5, 32, 32, 3, black), # Frame 5
self.sheet_enemy.get_image(6, 32, 32, 3, black), # Frame 6
self.sheet_enemy.get_image(7, 32, 32, 3, black), # Frame 7
self.sheet_enemy.get_image(8, 32, 32, 3, black), # Frame 8
]
def draw(self, win):
win.blit(self.animation_list[self.frame], self.rect)
def update(self):
dx = player.x - self.x
dy = player.y - self.y
distance = (dx**2 + dy**2)**0.5
if distance > 0:
dx /= distance
dy /= distance
self.velx = dx * self.speed
self.vely = dy * self.speed
self.x += self.velx
self.y += self.vely
self.rect.center = (int(self.x), int(self.y))
current_time = pygame.time.get_ticks()
if current_time - self.last_update >= self.animation_cooldown:
self.frame += 1
self.last_update = current_time
if self.frame >= len(self.animation_list):
self.frame = 0
if self.x + self.velx < border_rect.left + self.rect.width / 2:
self.x = border_rect.left + self.rect.width / 2
elif self.x + self.velx > border_rect.right - self.rect.width / 2:
self.x = border_rect.right - self.rect.width / 2
if self.y + self.vely < border_rect.top + self.rect.height / 2:
self.y = border_rect.top + self.rect.height / 2
elif self.y + self.vely > border_rect.bottom - self.rect.height / 2:
self.y = border_rect.bottom - self.rect.height / 2
class Player:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
self.rect = pygame.Rect(self.x, self.y, 75, 75)
self.velx = 0
self.vely = 0
self.up_pressed = False
self.down_pressed = False
self.left_pressed = False
self.right_pressed = False
self.space_pressed = False
self.speed = 2
self.action = 0
self.frame = 0
self.animation_cooldown = animation_cooldown
self.attackAnimation_cooldown = attackAnimation_cooldown
self.last_update = pygame.time.get_ticks()
self.animation_list = animation_list
self.attack_started = False
self.facing_left = False
self.facing_Right = False
def draw(self, win):
pygame.draw.rect(win, (0, 255, 0), border_rect, 2)
pygame.draw.rect(win, (12, 24, 36), self.rect)
win.blit(self.animation_list[self.action][self.frame], self.rect)
def update(self):
self.velx = 0
self.vely = 0
if self.left_pressed and not self.right_pressed:
self.velx = -self.speed
self.facing_left = True
self.facing_Right = False
if self.right_pressed and not self.left_pressed:
self.velx = self.speed
self.facing_left = False
self.facing_Right = True
if self.space_pressed and not self.left_pressed and not self.right_pressed and not self.attack_started:
if self.facing_Right:
self.facing_Right = False
self.facing_left = False
self.action = 2
self.frame = 0
self.attack_started = True
self.last_update = pygame.time.get_ticks()
if self.facing_left:
self.facing_Right = False
self.facing_left = False
self.action = 5
self.frame = 0
self.attack_started = True
self.last_update = pygame.time.get_ticks()
if self.up_pressed and not self.down_pressed:
self.vely = -self.speed
if self.down_pressed and not self.up_pressed:
self.vely = self.speed
self.last_update = pygame.time.get_ticks()
if self.x + self.velx < border_rect.left + self.rect.width / 2:
self.x = border_rect.left + self.rect.width / 2
elif self.x + self.velx > border_rect.right - self.rect.width / 2:
self.x = border_rect.right - self.rect.width / 2
if self.y + self.vely < border_rect.top + self.rect.height / 2:
self.y = border_rect.top + self.rect.height / 2
elif self.y + self.vely > border_rect.bottom - self.rect.height / 2:
self.y = border_rect.bottom - self.rect.height / 2
self.y += self.vely
self.x += self.velx
self.rect.center = (int(self.x), int(self.y))
if self.facing_Right:
self.action = 0
current_time = pygame.time.get_ticks()
if current_time - self.last_update >= self.animation_cooldown:
self.frame += 1
self.last_update = current_time
if self.frame >= len(self.animation_list[self.action]):
self.frame = 0
if self.facing_left:
self.action = 3
current_time = pygame.time.get_ticks()
if current_time - self.last_update >= self.animation_cooldown:
self.frame += 1
self.last_update = current_time
if self.frame >= len(self.animation_list[self.action]):
self.frame = 0
if self.velx == 0 and not self.attack_started:
if self.facing_left:
self.action = 3
else:
self.action = 1
self.frame = 0
if self.attack_started:
current_time = pygame.time.get_ticks()
if current_time - self.last_update >= self.attackAnimation_cooldown:
self.frame += 1
self.last_update = current_time
if self.frame >= len(self.animation_list[self.action]):
self.attack_started = False
self.frame = 0
run = True
player = Player(WIDTH / 2, HEIGHT / 2)
enemy = Enemy(WIDTH / 2, HEIGHT / 2)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player.left_pressed = True
if event.key == pygame.K_d:
player.right_pressed = True
if event.key == pygame.K_SPACE:
player.space_pressed = True
if event.key == pygame.K_w:
player.up_pressed = True
if event.key == pygame.K_s:
player.down_pressed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player.left_pressed = False
if event.key == pygame.K_d:
player.right_pressed = False
if event.key == pygame.K_SPACE:
player.space_pressed = False
if event.key == pygame.K_w:
player.up_pressed = False
if event.key == pygame.K_s:
player.down_pressed = False
win.fill((12, 24, 36))
player.draw(win)
player.update()
enemy.draw(win)
enemy.update()
pygame.display.flip()
clock.tick(120)
My spritesheet.py:
import pygame
class SpriteSheet():
def __init__(self, image):
self.sheet = image
def get_image(self,frame,width,height,scale,colour):
image = pygame.Surface((width,height)).convert_alpha()
image.blit(self.sheet,(0,0),((frame * width),0,width,height))
image = pygame.transform.scale(image, (width*scale,height*scale))
image.set_colorkey(colour)
return image
Hello blokes,
I have a school project where we use a RasPi and some sensors (Ultrasonic, possibly Camera) to make a radar. I thaught that I use pygame to create a UI, that displays a radar and (If I get there in half a year) also pictures from the radars perspective.
Is pygame the right choice for this or are there other librarys that I could use?
(SOLVED) Hello all, For a very start I'm a beginner and not used to pygame. I want to create a game really similar to Super Mario but the fact being I have a different version of my sprites. I have created my sprites which are apparently animated version in motion. I want to use them but any suggestion how I can do that?? Ur help would really be appreciated
EDIT: I have been trying everything I tried using a spritesheet as well as a gif but I don't know why it appears as a blurred white box in the final output. As as far as imitated version I mean it's an existing game but I'm trying modifying the characters into my coded version of game.
The last network test I did was a success with the server staying up most of the time with only 2 crashes for over a week!
I hope some of you want to come and play some games on the new testing round.
-To unlock the new playable vehicle you have to complete 1 game with the tank
possibly relevent code:
def main_1(window):
while run
for event in pygame.event.get():
if player.rect.y > HEIGHT: ย #if off window
ย ย ย ย ย ย ย ย run = False
ย ย ย ย ย ย ย ย main_1(window) ย ย ย ย ย #reset level
ย ย ย ย ย ย ย ย
ย ย ย ย ย ย ย ย #something like this?
ย ย ย ย ย ย ย ย #player = Player(100, 650, 50, 50) #(x, y, width, height) x, y = spawn location
Right now the timer continues to count up after the player is dead, I want it to pause until the player restarts.
timer code:
FONT = pygame.freetype.Font("assets\Menu\Text\pixeloid-font\PixeloidMono-d94EV.ttf", 20)
time_text = FONT.render(f"Time: 0s", "black")
if player.healthbar.health > 0: ย
ย ย time_text = FONT.render(f"Time: {round(elapsed_time)}s", "black")
window.blit(time_text[0], (10, 60))
def main_1(window):
start_time = time.time()
while run:
elapsed_time = time.time() - start_time # seconds since while loop started
restart level code:
def main_1(window):
while run:
for event in pygame.event.get(): ย ย ย ย ย
if player.healthbar.health <= 0: ย ย ย ย ย ย ย ย #if dead
ย ย ย ย ย ย if pygame.key.get_pressed()[pygame.K_r]: ย ย #restart_level
ย ย ย ย ย ย ย ย ย ย main_1(window)
ย ย ย ย ย ย ย ย if pygame.key.get_pressed()[pygame.K_ESCAPE]: ย #close window
ย ย ย ย ย ย ย ย ย ย run = False
[Solved] when i press esc this window closes and my actual game opens up what is this?
Edit: got it to work, I needed to reupload the picture with the specified RGBA values, I thought it would do it automatically. User error ๐ญ. Being a new programmer is suffering.
Hello I am losing my mind please someone help. I'm trying to get a custom sprite generator but am having trouble getting the transparency from the accessory item to not attach to the first image. Im using a cat and a hat for testing purposes. I tried using the .convert_alpha() function instead of .convert() and even with .set_colorkey but nothing is working. if you have a second please look over the code. I used paint .net to get the transparency not sure if that makes a difference.
import pygame
clock = pygame.time.Clock()
# Initialize Pygame
pygame.init()
# Set up the display
screen = pygame.display.set_mode((800, 600))
# Load images
character_image = pygame.image.load('cat.png').convert() # Base character
hat_image = pygame.image.load('cap.png').convert() # Accessory
hat_image.set_colorkey((255, 0, 199))
print('test')
# Create a composite surface
composite_surface = pygame.Surface((character_image.get_width(), character_image.get_height()), pygame.SRCALPHA)
composite_surface.fill((0, 0, 0, 0))
# Blit the images onto the composite surface
composite_surface.blit(character_image, (0, 0)) # Draw character
composite_surface.blit(hat_image, (500, 100)) # Draw hat (on top)
# Save the composite sprite as a PNG
output_file_path = r'C:\Users\Artem\Desktop\composite_sprite.png' # Specify your output path
pygame.image.save(composite_surface, output_file_path)
# Main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Clear the screen
screen.fill((255, 255, 255))
# Draw the composite sprite
screen.blit(composite_surface, (100, 100))
# Update the display
pygame.display.flip()
# Quit Pygame
pygame.quit()
Can anyone please help me or tell me how i can include a character selection menu that comes after the main menu, where both p1 and p2 can select their characters and play. I've tried so much but only things I've done is get a million errors.
Code: https://pastebin.com/JGU7XgGh