logo
down
shadow

Pygame animating image by transforming it


Pygame animating image by transforming it

Content Index :

Pygame animating image by transforming it
Tag : development , By : robinator
Date : November 26 2020, 03:01 PM

Hope that helps The simplest solution would be to call extend or contract once per frame, but then the animation would be frame rate bound.
import pygame


class Muscle(pygame.sprite.Sprite):
    def __init__(self, screen, posX=200, posY=200, contraction=0.5,
                 extension=1.5, length=40, thickness=20, min_len=0.2,max_len=1.5, power=20):
        super(Muscle, self).__init__()
        self.screen = screen
        self.contracting = False  # To check if the muscle is contracting or extending.
        self.contraction = contraction
        self.relaxation = 1
        self.length = length
        self.thickness = thickness
        if power < 1:
            self.power = 1
            power = 1
        else:
            self.power = power
        self.image = pygame.Surface((length, thickness))
        color_index = 5 * power
        self.image.fill((255, color_index, color_index))
        self.rect = self.image.get_rect()
        self.rect.x = posX
        self.rect.y = posY

    # This method gets called every frame.
    def update(self):
        if self.contracting:
            self.contract()
        else:
            self.extend()

    def render(self):
        self.screen.blit(self.image, (self.rect.x, self.rect.y))

    def contract(self):
        expected_width = self.length * self.contraction
        counter = 0
        if self.image.get_width() > expected_width:
            self.image = pygame.transform.scale(self.image, (self.rect.width, self.image.get_height()))
            self.rect.x += 1
            self.rect.width -= 2
            self.render()
            counter += 1

    def extend(self):
        expected_width = self.length * self.relaxation
        counter = 0
        if self.image.get_width() < expected_width:
            self.image = pygame.transform.scale(self.image, (self.rect.width, self.image.get_height()))
            self.rect.x -= 1
            self.rect.width += 2
            self.render()
            counter += 1


def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    muscle = Muscle(screen)
    all_sprites = pygame.sprite.Group(muscle)

    done = False

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            # Change the state of the muscle.
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    muscle.contracting = True
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_c:
                    muscle.contracting = False

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

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


if __name__ == '__main__':
    pygame.init()
    main()
    pygame.quit()

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

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


Tag : development , By : user177910
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()
Related Posts Related QUESTIONS :
  • How to use someClass.android.ts and someClass.ios.ts without errors
  • ADB Connection to Samsung smart tv
  • is there a way to 2 create multiple command files in cypress
  • Best way to filter DBpedia results and return a specific results using SPARQL
  • Is it possible to use unicode combining characters to combine arbitrary characters?
  • Antlr4 extremely simple grammar failing
  • Neighbor of 10 wrong answer?
  • PDFlib - setting stroke and fill opacity (transparency)
  • AWS Lambda + Serverless, where/how to deploy js module that couldn't be bundled?
  • how to place mobile call from PWA
  • How to get connected clients and client certificate in node-opcua server
  • Passing dictionary from one template to another in Helm
  • Kivy. Position of GridLayout inside ScrollView
  • How can I try to place a pending order every X minutes till it's successfull?
  • Is there a way to download the SonarLint report generated in Eclipse IDE?
  • How to Open Port in Windows Firewall using C++ Builder?
  • How to put "OR" operator in Karate API assertion statement
  • Get .model.json as String
  • Proof Process busy on combine_split
  • Does memoization work on smple .select with strings?
  • Check if movement ended
  • Determine If a String Is Present in a List or Map?
  • Shortest_Path Interpretation of Edge Weight
  • Azure Pipelines - What's the difference between a Pipeline artifact and a Build artifact?
  • How to save content of bilion websites found by search engine (how google is doing it)
  • dynamodb index does not return all data
  • Either scp or roles claim need to be present in the token using when application permissions to read sharepoint sites
  • how to speed up sympy-matrix of matrics calculation runtime
  • SNMP Walk and Get / GetNext for MIBs that are not supported by agent
  • Using Puppeteer, how to get Chrome DevTools' "Network" tab's timing information?
  • Twig uses htmlspecialchars internally for escaping. How do I pass ENT_NOQUOTES?
  • How to use @pnp/sp to retrieve users for a People Picker
  • How to find the last letter of a line with TUSTEP
  • SwiftUI: What is the Proper Logic Statement to Prevent Views From Disappearing While Using a Custom Slider
  • alfresco start workflow directly from document library
  • How to migrate Bot Services to framework 4.3 ussing AppSettings
  • How to make a window always appear at specified location?
  • M3 Java: How to check that a class implements a function from an interface
  • Handling routing_key for topic routing
  • Gremlin Java 3.4 withRemote deprecated
  • Libtorch: cannot load traced lstm scriptmodel
  • Correct HAR format for sendHarRequest
  • If statement in Robot
  • How to set STUN servers in JsSIP 3.3.0
  • Delete large amount of Vertexs from the Cosmos Db using Gremlin queries
  • How to see details about user, even if they're not registered?
  • How to apply scrollbar-primary to a div?
  • Spark: How to aggregate/reduce records based on time difference?
  • Can I query the list of variables and types
  • Use case for "sets of tuple data" in Pyomo
  • how to separate columns in hive
  • Matching borrowed enum - why is this syntax equivalent?
  • How to Query Realm DB Browser?
  • Cannot access font awesome in custom Liferay 7.1 theme
  • how to create a custom login page in salesforce.com?
  • Why does MPI_Init accept pointers to argc and argv?
  • How to create a Turing machine that takes a single digit decimal number from 0 - 9 and output the cube
  • Windbg + IDA: calculate an address in a module
  • Swing Panel Question
  • Spring-ws client from WSDL
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com