transforming images in pygame
Tag : python , By : user152319
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I'm trying to resize an image in pygame. I want my background image to fill the entire screen. I'd like to setup the entire screen based on the new (stretched) dimensions of the background. The following isn't working and I'm trying to figure out why. #pygame.transform.scale(background, (1200,800)) #or some size x,y here.
background = pygame.transform.scale(background, (1200,800))
|
Strange timing issues in PyGame when animating bouncing balls
Tag : python , By : user119985
Date : March 29 2020, 07:55 AM
may help you . I am programming a game in PyGame and believe the code to be consistent for all the bouncing balls. However, after a while the balls bounce at different velocities. , Take a look at what happens here when y_s1 becomes > 370: y_s1 = y_s1 + sphere_vel # 1
if y_s1 > 370:
sphere_vel = sphere_vel * -1 # 2
if y_s1 < 0:
sphere_vel = sphere_vel * -1
y_s2 = y_s2 + sphere_vel # 3
if y_s2 > 370:
sphere_vel = sphere_vel * -1
if y_s2 < 0:
sphere_vel = sphere_vel * -1 # 4
# The IMPOSIBLE GAME
import random
import pygame
from pygame.color import Color
from pygame.surface import Surface
from pygame.sprite import Sprite, Group
pygame.init()
# note how pygame defines a lot of colors already for you
colour_list = [Color('Black'), Color('White'), Color('Red'), Color('Blue'), Color('Green')]
# we use a dict to keep a simple 'What Key Moves In Which Direction'-map
keys = {pygame.K_UP: ( 0, -3),
pygame.K_DOWN: ( 0, 3),
pygame.K_LEFT: (-3, 0),
pygame.K_RIGHT: ( 3, 0)}
# using sprites will make your live easy
# e.g. you don't need to handle drawing yourself
class Player(Sprite):
def __init__(self):
Sprite.__init__(self)
# we create a simple rectangular surface
self.image = Surface((30, 30))
self.rect = self.image.get_rect()
self.image.fill(Color('Black'))
# we set a colorkey so we can create a mask
# this mask is used for pixel perfect collision
# which will come in handy not only for circles
# but if you extend your game to other shape
self.image.set_colorkey(Color('Purple'))
self.mask = pygame.mask.from_surface(self.image)
self.deaths = 0
def update(self):
# use a random color from the list
self.image.fill(random.choice(colour_list))
# check which keys are pressed
pressed = pygame.key.get_pressed()
for key, movement in keys.iteritems():
if pressed[key]:
# and move our rect in that direction
# note how we don't need extra variables
# the rect is enough
self.rect.move_ip(movement)
# we use the clamp_ip function to ensure your rect
# does not get out of screeen.
self.rect.clamp_ip(pygame.display.get_surface().get_rect())
# check if we collide with any object in the objects group
# we use pygame.sprite.collide_mask to have a pixel perfect
# collision detection
# objects is a global variable, which may bother, but we could
# simply pass it through the update function instead
if pygame.sprite.spritecollide(self, objects, False, pygame.sprite.collide_mask):
self.deaths += 1
self.rect.topleft = (0, 0)
class Circle(Sprite):
def __init__(self, start_x, speed):
Sprite.__init__(self)
# same as the in the Player class
# we create a simple Surface
self.image = Surface((30, 30))
self.rect = self.image.get_rect(x=start_x, y=100)
self.image.fill(Color('Purple'))
self.image.set_colorkey(Color('Purple'))
pygame.draw.ellipse(self.image, Color('Blue'), (0, 0, 30, 30), 0)
self.mask = pygame.mask.from_surface(self.image)
self.y_vel = speed
def update(self):
# we create a rect which will tell us
# were we would move
target = self.rect.move(0, self.y_vel)
# and if we would go out of screen
if not pygame.display.get_surface().get_rect().contains(target):
# we simply change direction
self.y_vel *= -1
# then acutally move
self.rect.move_ip(0, self.y_vel)
screen = pygame.display.set_mode((700, 400))
clock = pygame.time.Clock()
done = False
# When creating the circles, we can specify the start position and speed
objects = Group((Circle(x+100, 5) for x in xrange(0, 500, 100)))
# use a Group to handle updating and drawing
all_group = Group(*objects)
all_group.add(Player())
# your main loop is as easy as this
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
all_group.update()
screen.fill(Color('White'))
all_group.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
|
`pygame`: on Ubuntu, using `pygame.image.save` to save PNG causes `pygame.error: SavePNG: could not create png write str
Tag : python , By : ChristianM
Date : March 29 2020, 07:55 AM
around this issue This problem was caused because I installed my Python stack using Anaconda, but then installed pygame using the build+install instructions for Ubuntu on pygame's documentation page. This caused there to be conflicting libraries of libpng, I think, somewhere, somehow. ======================================================================
FAIL: BaseModuleTest.test_get_error
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/brian/anaconda2/lib/python2.7/site-packages/pygame/tests/base_test.py", line 569, in test_get_error
e)
AssertionError: Failed to access the SoundFont /usr/share/sounds/sf2/FluidR3_GM.sf2
======================================================================
FAIL: BaseModuleTest.test_set_error
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/brian/anaconda2/lib/python2.7/site-packages/pygame/tests/base_test.py", line 586, in test_set_error
e)
AssertionError: Failed to access the SoundFont /usr/share/sounds/sf2/FluidR3_GM.sf2
|
Animating Pygame Rects to move up the Screen
Date : March 29 2020, 07:55 AM
Hope this helps Unless I'm very much mistaken about how pygame works, you've misunderstood how it works. For oygamr to work it needs a 'render loop', a loop of code in which you repeatedly move the object, draw it with something like pygame.draw.rect, and then flip the display with pygame.display.flip. You keep doing this until you're done animating. So, you need to make a bunch of changes.
|
When I am trying to pass an image through pygame, it keeps saying 'pygame.Surface' has no attribute
Tag : python , By : user185949
Date : March 29 2020, 07:55 AM
it should still fix some issue When you have an instance and call one of its methods, the instance gets automatically passed as the first argument, self. So if you have a class MyClass and an instance my_instance and you call its handle_event method, it's the same as calling MyClass.handle_event(my_instance). In your program you never create an instance of the player class and so you're passing the screen as the self argument directly to the class (the screen is actually a pygame.Surface). That means the self in the handle_event method actually refers to the screen surface and since surfaces don't have an image_down attribute, Python raises an error when the self.image_down.get_rect() part is reached. player_instance = player(x_position, y_position)
while True:
player_instance.handle_event()
import pygame
pygame.init()
WINDOWWIDTH = 900
WINDOWHEIGHT = 400
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
FPS = 40
clock = pygame.time.Clock()
# Load images once globally and reuse them in the program.
background = pygame.image.load("bedroom.jpg").convert()
background = pygame.transform.scale(background, (WINDOWWIDTH, WINDOWHEIGHT))
temp_image = pygame.image.load("stand_down.png").convert_alpha()
image_down = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standleft.png").convert_alpha()
image_left = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standright.png").convert_alpha()
image_right = pygame.transform.scale(temp_image, (100, 200))
class player(pygame.sprite.Sprite):
def __init__(self, x, y):
super(player, self).__init__()
self.image_down = image_down
self.image_left = image_left
self.image_right = image_right
self.image = self.image_down
# keep position and size in pygame.Rect()
# to use it in collision checking
self.rect = self.image.get_rect(x=x, y=y)
# You don't have to pass x and y, since you already
# use the `self.rect` as the blit position.
def draw(self, screen):
screen.blit(self.image, self.rect)
def handle_event(self):
# These two lines don't make sense.
#self.image = self.image_down.get_rect()
#self.image = pygame.Surface((x, y))
# I guess you want to switch back to image_down.
self.image = self.image_down
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.rect.x -= 5
self.image = self.image_left
if key[pygame.K_RIGHT]:
self.rect.x += 5
self.image = self.image_right
class room1():
def __init__(self):
self.x, self.y = 16, WINDOWHEIGHT/2
# Reference to the background image.
self.background = background
def draw(self, screen): # Pass the screen.
screen.blit(self.background, (0, 0))
def main():
# Create player and room instances.
player_instance = player(200, 150)
room1_instance = room1()
while True:
for event in pygame.event.get():
# Users can press the "X" button to quit.
if event.type == pygame.QUIT:
return
player_instance.handle_event()
room1_instance.draw(screen)
player_instance.draw(screen)
# You don't need both update and flip.
# pygame.display.update()
pygame.display.flip()
clock.tick(FPS)
main()
pygame.quit()
|