python – Erro em movimento de objeto pygame

O segundo dado não to "move".

class dice (pygame.sprite.Sprite):
def init(self):
pygame.sprite.Sprite.init(self)

    self.images = (pygame.image.load('dice1.png'),
                   pygame.image.load('dice2.png'),
                   pygame.image.load('dice3.png'),
                   pygame.image.load('dice4.png'),
                   pygame.image.load('dice5.png'),
                   pygame.image.load('dice6.png'))

    self.current_image = 0

    self.image = pygame.image.load('dice1.png')
    self.mask = pygame.mask.from_surface(self.image)
    self.rect = self.image.get_rect()
    self.rect(0) = 100
    self.rect(1) = 150

def update(self):
    self.current_image = (self.current_image + 1) % 6
    self.image = self.images(self.current_image)

Dice2 class (pygame.sprite.Sprite):
def init(self):
pygame.sprite.Sprite.init(self)

    self.images = (pygame.image.load('dice1.png'),
                   pygame.image.load('dice2.png'),
                   pygame.image.load('dice3.png'),
                   pygame.image.load('dice4.png'),
                   pygame.image.load('dice5.png'),
                   pygame.image.load('dice6.png'))

    self.current_image = 0

    self.image = pygame.image.load('dice1.png')
    self.mask = pygame.mask.from_surface(self.image)
    self.rect = self.image.get_rect()
    self.rect(0) = 240
    self.rect(1) = 150

def update(self):
    self.current_image = (self.current_image + 1) % 6
    self.image = self.images(self.current_image)

dice_group = pygame.sprite.Group ()
dice = dice ()
dice_group.add (dice)

dice_group2 = pygame.sprite.Group ()
dice2 = dice2 ()
dice_group2.add (dice2)

Python pong with Pygame

Hi, I wrote the following code in Python.

Currently facing some problems

  • The ball sometimes gets stuck in a racket (occurs when the ball hits the top
    or at the bottom of the paddle)
  • The ball should be reflected at wider angles when it moves in the same direction as the ball, but moves more slowly than the initial angle, unlike narrower angles when 39; it moves in the opposite direction but moves faster. (Would it be possible to do this without using a random or hard-coded number? It may not be possible, but I'm curious because I tried to figure it out)

Reflection of the balloon against the paddle (I do not take the credit of this image)
(I do not take any credit for this image)
Any improvement of my code will be appreciated because it is my first shot on pygame!

import pygame, sys
import random
from math import degrees, radians, sin, cos

pygame.init()

# Create a screen
win = pygame.display.set_mode((800,700))
win_info = pygame.display.Info()
win_w, win_h = win_info.current_w, win_info.current_h
pygame.display.set_caption("Pong")
pad_colour = (255,255,255) #White colour

pad_distance = 50
speed = 10
running = True
fps = 30

#############################################################################

class border(pygame.sprite.Sprite):
    width = win_w
    height = 10

    def __init__(self,width, height, colour):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface((width,height))
        self.image.fill(colour)

        self.rect = self.image.get_rect()

    def draw(self):
        win.blit(self.image, self.rect)

#############################################################################


class paddle(pygame.sprite.Sprite):
    """left arg refer to top left corner coordinate of paddle
    """

    def __init__(self,width, height, speed, colour):
        pygame.sprite.Sprite.__init__(self)

        self.width = width
        self.height = height

        self.image = pygame.Surface((width, height))
        self.image.fill(colour)

        self.speed = speed
        self.vel_x = 0
        self.vel_y = 0

        # Size of rectangle
        self.rect = self.image.get_rect()


    def move(self, x, y):
        self.rect.move_ip(x,y)

    def moveTo(self, x, y):
        self.rect.topleft = (x,y)

    def draw(self):
        win.blit(self.image, (self.rect.x,self.rect.y))


#############################################################################

class ball(pygame.sprite.Sprite):
    """ Facing takes 1 or -1 to determine direction of movement
    """
    def __init__(self, radius, factor, colour):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface((radius*2, radius*2))
        pygame.draw.circle(self.image, colour, (radius,radius), radius)

        self.rect = self.image.get_rect()
        # Replace facing when finalising implementation of ball
        self.facing = -1
        self.factor = factor
        self.vel_x, self.vel_y = self.randomMovement(factor)

    def move(self, x,y):
        self.rect.move_ip(x,y)

    def moveTo(self, x, y):
        self.rect.center = (x,y)

    def collidePad(self):
        self.vel_x = self.vel_x * -1

    def draw(self):
        win.blit(self.image, (self.rect))

    def randomMovement(self,factor=None):
        #unit vector
        if factor == None:
            # Used for all calls after ball instance is initialised
            factor = self.factor
        angle = radians(random.randint(30,80))
        rand_y = random.randrange(-1,2,2)
        y = sin(angle)
        x = cos(angle)
        """ How to get over the use of int and rounding errors. Using int the line before causes the vector to be 0,0 as the numbers after 0 are truncated"""
        self.vel_x, self.vel_y = (int(x*factor),int(y*factor)*rand_y)
        #print(x, y)
        return self.vel_x, self.vel_y


#############################################################################


# Main Game Loop
def main():
    white = (255,255,255)
    border_height = 10
    pad_width = int(win_w/50)
    pad_height = int(win_h/6)
    pad_left = paddle(pad_width, pad_height, speed, white)
    pad_right = paddle(pad_width, pad_height, speed, white)

    # Set X and Y of left pad
    pad_left.rect.topleft = (pad_distance, int((win_h-pad_height)/2))

    # Set X and Y of right pad
    pad_right.rect.topleft = ((win_w-pad_distance-pad_width), int((win_h-pad_height)/2))

    top_border = border(win_w, border_height, white)
    top_border.rect.topleft = (0, 0)
    bottom_border = border(win_w, border_height, white)
    bottom_border.rect.topleft = (0, win_h-border_height)
    gameBall = ball(10, 10, white)
    gameBall.rect.center = (int(win_w/2), int(win_h/2))

    to_draw = (pad_left, pad_right, top_border, bottom_border, gameBall)
    redrawGameWin(to_draw)

    backGround = pygame.Surface((win_w,win_h))
    backGround.fill(white)

    clock = pygame.time.Clock()

    # Game Loop
    while running:
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.display.quit()
                pygame.quit()
                sys.exit()

        keys = pygame.key.get_pressed()
        # Left pad moving up with top boundary collision
        if keys(pygame.K_s) and pad_left.rect.y > 0:
            if pad_left.rect.y - top_border.height - pad_left.speed <= 0 :
                pad_left.vel_y = 0
                pad_left.moveTo(pad_distance, top_border.height)
            else:
                pad_left.vel_y = -pad_left.speed
                pad_left.move(0, pad_left.vel_y)

        # Left pad moving down with bottom boundary collision
        if keys(pygame.K_x):
            if pad_left.rect.y + pad_left.height + pad_left.speed + bottom_border.height >= win_h:
                pad_left.vel_y = 0
                pad_left.moveTo(pad_distance, win_h-pad_left.height-bottom_border.height)
            else:
                pad_left.vel_y = pad_left.speed
                pad_left.move(0, pad_left.speed)

        if not keys(pygame.K_s) and not keys(pygame.K_x):
            pad_left.vel_x, pad_left.vel_y = 0,0

        # Right pad moving up with top boundary collision
        if keys(pygame.K_k):
            if pad_right.rect.y - top_border.height - pad_right.speed <= 0:
                pad_right.vel_y = 0
                pad_right.moveTo(win_w-pad_distance-pad_right.width, top_border.height)
            else:
                pad_right.vel_y = -pad_right.speed
                pad_right.move(0, pad_right.vel_y)

        # Right pad moving down with bottom boundary collision
        if keys(pygame.K_m):
            if pad_right.rect.y + pad_right.height + pad_right.speed + bottom_border.height >= win_h:
                pad_right.vel_y = 0
                pad_right.moveTo(win_w-pad_distance-pad_right.width, win_h-pad_right.height-bottom_border.height)
            else:
                pad_right.vel_y = pad_right.speed
                pad_right.move(0, pad_right.vel_y)

        if not keys(pygame.K_k) and not keys(pygame.K_m):
            pad_right.vel_x, pad_right.vel_y = 0,0

        # Ball bouncing off top border
        if gameBall.rect.colliderect(top_border.rect) or gameBall.rect.colliderect(bottom_border.rect):
            gameBall.vel_y = gameBall.vel_y*-1

        # Ball bouncing off right pad
        if gameBall.rect.colliderect(pad_right.rect):
            gameBall.vel_x = -(gameBall.vel_x + pad_right.vel_x)
            gameBall.vel_y = gameBall.vel_y + pad_right.vel_y

        # Ball bouncing off left pad
        if gameBall.rect.colliderect(pad_left.rect):
            gameBall.vel_x = -(gameBall.vel_x + pad_left.vel_x)
            gameBall.vel_y = gameBall.vel_y + pad_left.vel_y

        # Ball moving by velocity vector
        gameBall.move(gameBall.vel_x, gameBall.vel_y)

        # Ball moves off screem
        if gameBall.rect.left >= win_w or gameBall.rect.right <=0:
            gameBall.randomMovement()
            gameBall.moveTo(int(win_w/2), int(win_h/2))


        redrawGameWin(to_draw)    

#############################################################################


def redrawGameWin(shapes):
    #global dirty_rects
    win.fill((0,0,0))
    for shape in shapes:
        shape.draw()

    pygame.display.flip()


#############################################################################

if __name__ == "__main__":
    main()


sprites – How to make a smooth animation with images of different sizes in pygame?

I have an animation where my player swings his sword, with 5 pygame images. The normal idle image is 14×22 and the others are 13×23, 21×23, 18×23 and 18×23. I'm having problems with my character & # 39; Jumping & # 39; when he swings his sword, because the size of my image is constantly changing. Could someone help me with this?

Here is my code for animation

elif keys(pg.K_SPACE):
            now = pg.time.get_ticks()
            try:
                if now - self.last_update > self.frame_rate:
                    if self.direction == 'left':
                        self.game.player_img = self.game.playerattackleft(self.frame)
                        self.frame += 1
                        self.last_update = now
            except IndexError:
                self.frame = 0

Thank you.

python – Error importing pygame into Pycharm

Hello, I'm here only because it's been a week since I try to install pygame in pycharm in any way and take a beating … I tried it from the command line, and in several ways … When I can install, an error appears. The error that appears when I get to install is as follows: (d: build libmpg123 mpg123-1.25.10 src libmpg123 id3.c: 482) error: no comment text / description valid?

The other error that appears and does not allow installation is as follows: Traceback (last most recent call):
File "C: /Users/Rafael/PycharmProjects/exercicios/ex021.py", line 1, in
import pygame
ModuleNotFoundError: no module named & # 39; pygame & # 39;

I'm just doing a simple exercise where I want to play an mp3 file. Here is the code:

import pygame
pygame.init ()
pygame.mixer.music.load (& # 39; ex021.mp3 & # 39;)
pygame.mixer.music.play ()
pygame.event.wait ()

I tried it by pip install pygame, I tried it by clicking on the red light directly on the pycharm itself, I tried it by parameters – project interpreter, in short, I think this is a version mismatch. I am using Windows, Python 3.8.2 PIP 20.0.2 and the pygame I am trying to install is pygame 1.9.6 Can anyone help me, help me out 39; you like?

2d – I want to create a game like Undertale using Python with Pygame, is it good enough in terms of performance?

I have heard that python with pygame is slow. If I create a 2D game in the same style as the famous Undertale, does it matter? Is it so slow? Should I go with something else?

I have never played a game before but I have experience developing regular python software. That's why I ask.

How to stop the stuttering of the snake game? pygame

I have the following code and it seems to work quite well except that from time to time the program stutters and the snake teleports in front of a few spaces. I cannot say what this is related to.

import numpy as np
from collections import deque
import pygame
import time
import random

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


class Snake:
    actions = (np.array((-1, 0)), np.array((1, 0)), np.array((0, -1)), np.array((0, 1)))

    def __init__(self, start_position, start_direction_idx):
        """

        :type start_position: 2x1 numpy Array
        """
        self.startPosition = None
        self.alive = True
        self.direction = start_direction_idx
        self.length = 1
        self.currentPosition = start_position
        self.blocks = deque((start_position.copy()))
        self.blockAtEndofTail = None

    def isMovingBackwards(self, action):
        if self.direction == 0 and action == 1:
            return True
        elif self.direction == 1 and action == 0:
            return True
        elif self.direction == 2 and action == 3:
            return True
        elif self.direction == 3 and action == 2:
            return True

    def move(self, action):
        if self.isMovingBackwards(action):
            action = self.direction

        else:
            self.direction = action

        self.currentPosition += self.actions(self.direction)
        self.blocks.append(self.currentPosition.copy())
        self.blockAtEndofTail = self.blocks.popleft()

    def eat(self):
        self.blocks.appendleft(self.blockAtEndofTail)  # If current position is an apple eat

    def die(self):
        pass

    def draw(self, screen, blockDim):

        for i, block in enumerate(self.blocks):
            pygame.draw.rect(screen, GREEN, (blockDim * block(0), blockDim * block(1), blockDim, blockDim))


class Environment:
    def __init__(self, rows, screenSize, startX, startY):
        self.rows = rows
        self.screenSize = screenSize

        pygame.init()
        self.gameDisplay = pygame.display.set_mode((screenSize, screenSize))
        pygame.display.set_caption('Snake')

        self.blockSize = screenSize / rows

        self.grid = np.zeros((rows, rows))
        self.snake = Snake(np.array((startX, startY)), 1)
        self.apple = Apple(np.array((3, 4)))

    def reset(self):
        pass

    def render(self):
        self.gameDisplay.fill(BLACK)
        self.snake.draw(self.gameDisplay, self.blockSize)
        self.apple.draw(self.gameDisplay, self.blockSize)
        pygame.display.update()

    def step(self, action):
        self.snake.move(action)
        if self.snake.currentPosition(0) == self.apple.position(0) and self.snake.currentPosition(1) == 
                self.apple.position(1):
            self.snake.eat()

            self.apple.reset(random.choice(self.getEmptySquares()))

    def isOffGrid(self):
        if self.snake.currentPosition(0) * self.blockSize < 0 or self.snake.currentPosition(0) * (
                self.blockSize) > self.screenSize - self.blockSize:
            print(self.snake.currentPosition(0) * self.screenSize, self.snake.currentPosition(1) * self.screenSize)
            return True
        if self.snake.currentPosition(1) * self.blockSize < 0 or self.snake.currentPosition(1) * (
                self.blockSize) > self.screenSize - self.blockSize:
            print(self.snake.currentPosition(0) * self.screenSize, self.snake.currentPosition(1) * self.screenSize)
            return True
        else:
            return False

    def getEmptySquares(self):
        emptySquares = deque(())
        for i in range(self.grid.shape(0)):
            for j in range(self.grid.shape(1)):
                array = np.array((i, j))
                if all((array != elem).all() for elem in self.snake.blocks):
                    emptySquares.append(array)
        return emptySquares


class Apple:
    def __init__(self, position):
        self.size = 20
        self.position = position

    def draw(self, screen, blockDim):
        pygame.draw.rect(screen, RED, (blockDim * self.position(0), blockDim * self.position(1), blockDim, blockDim))

    def reset(self, newPosition):
        self.position = newPosition

def main():

    env = Environment(20, 500, 10, 10)
    finished = False
    action = env.snake.direction
    clock = pygame.time.Clock()
    while not finished:
        time.sleep(0.1)
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                finished = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    action = 1
                if event.key == pygame.K_LEFT:
                    action = 0
                if event.key == pygame.K_UP:
                    action = 2
                if event.key == pygame.K_DOWN:
                    action = 3
        env.step(action)
        if env.isOffGrid():
            pygame.quit()
            quit()

        print(clock.get_fps())
        env.render()
        clock.tick(144)

By the way, are there any bad practices that you can spot that I find? Someone mentioned that I shouldn't be using numpy arrays but I don't see the problem with that.

Any help would be highly appreciated

python – Problem to insert an image in pygame

So I try to insert an image using pygame, I use time.sleep () as a delay and then I insert another image:

x = 0
y = 0

image = pygame.image.load("ex02.png")
ecra.blit(image, (0, 0))

time.sleep(20)

image2 = pygame.image.load("ex03.jpg")
ecra.blit(image2, (x, y))

the problem is that by doing this, it simply ignores tim.sleep () and inserts the second image on top of the first. Does anyone know why this is happening?

python – Automatic image rotation in pygame

I can't rotate the image and position myself in coordinates that are not. This same rotation code, in a separate window, works perfectly.

                if len(self.player_group) == 0:   

                    self.surf = pg.image.load("resources/nave/nave.png").convert_alpha()
                    self.current_angle = 0
                    self.rect = self.surf.get_rect(center=(700, 300))

                   if self.current_angle <= 180:    
                      self.current_angle += 0.02

                  self.texto.screen.blit(self.rot_center(self.surf,self.current_angle), self.rect)

         pg.display.flip()

         pg.display.update()



 def rot_center(self,image, angle):
     orig_rect = image.get_rect()
     rot_image = pg.transform.rotate(image, angle)
     rot_rect = orig_rect.copy()
     rot_rect.center = rot_image.get_rect().center
     rot_image = rot_image.subsurface(rot_rect).copy()
     return rot_image

python – Game with error that nothing appears Pygame

The objective of the game is to type as many countries as possible on the screen (obviously without spelling errors), the work in terms of configuration and screen is for the most part done, my part is to complete the game functions which validate the number of points that a word can type well, remove it from the screen when you have already typed it and update it consecutively. The point is, everything I do doesn't show anything on the screen, even when I update the positions and the list of countries that should actually appear on the screen. Anyway, I leave the link with everything I have done, if you find the error I am having, let me see why I don't see it! Thanks in advance!

python – Trying to get a rotary encoder to manipulate a variable such as speed in Pygame

I don't know if I can even go anywhere with this, but what I'm trying to do is use a rotary encoder as an input to change the speed of 39; a pygame car.

So far, the code that I got for the encoder to modify a variable is (I run it on a pi):

from RPi import GPIO
from time import sleep

clk = 21
dt = 20
GPIO.setmode(GPIO.BCM)
GPIO.setup(clk, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(dt, GPIO.IN, pull_up_down=GPIO.PUD_UP)
counter = 0
clkLastState = GPIO.input(clk)
try:
        while True:
                clkState = GPIO.input(clk)
                if clkState != clkLastState:
                        dtState = GPIO.input(dt)
                        if dtState != clkState:
                                counter += 1
                        else:
                                counter -= 1
                        print (counter)
                clkLastState = clkState
                # sleep(0.01)
finally:
        GPIO.cleanup()

The game code is as follows:


import pygame
import time
import random

pygame.init()

display_width = 800
display_height = 600

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

block_color = (53,115,255)

car_width = 73

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()

carImg = pygame.image.load('racecar.png')


def things_dodged(count):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Dodged: "+str(count), True, black)
    gameDisplay.blit(text,(0,0))

def things(thingx, thingy, thingw, thingh, color):
    pygame.draw.rect(gameDisplay, color, (thingx, thingy, thingw, thingh))

def car(x,y):
    gameDisplay.blit(carImg,(x,y))

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    pygame.display.update()

    time.sleep(2)

    game_loop()



def crash():
    message_display('You Crashed')

def game_loop():
    x = (display_width * 0.45)
    y = (display_height * 0.8)

    x_change = 0

    thing_startx = random.randrange(0, display_width)
    thing_starty = -600
    thing_speed = 2
    thing_width = 100
    thing_height = 100

    thingCount = 1

    dodged = 0

    gameExit = False

    while not gameExit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5
                if event.key == pygame.K_RIGHT:
                    x_change = 5

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        x += x_change
        gameDisplay.fill(white)

        # things(thingx, thingy, thingw, thingh, color)
        things(thing_startx, thing_starty, thing_width, thing_height, block_color)



        thing_starty += thing_speed
        car(x,y)
        things_dodged(dodged)

        if x > display_width - car_width or x < 0:
            crash()

        if thing_starty > display_height:
            thing_starty = 0 - thing_height
            thing_startx = random.randrange(0,display_width)


            thing_width += (dodged * 1.2)

        if y < thing_starty+thing_height:
            print('y crossover')

            if x > thing_startx and x < thing_startx + thing_width or x+car_width > thing_startx and x + car_width < thing_startx+thing_width:
                print('x crossover')
                crash()

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

game_loop()
pygame.quit()
quit()

The car currently has a defined speed of 2, under thing_speed but i don't know if i can influence it using rotary encoder, does it want to be inside game_loop():?

They both work, but I'm just trying to bring the two together if that makes sense. Is it really possible or am I going crazy?

Thank you