pygame – How do I click on specific text in an array of text?

I am trying to click on a specific word in an array but I can’t think of how.

This is what I have:

  for x in range(0, len(names)):
    templine = font.render(names(x), True, WHITE)
    tempRect = templine.get_rect()
    tempRect.midleft = (50, (170+30*x))
    if mouse012(0) == True and tempRect.collidepoint(mouseXY):
      state = AppState.STATS

      detailsName = names(x)
    screen.blit(templine, tempRect)

platformer – Pygame Platform & Player collisions

I am trying to create a platform game where a player jumps between platforms horizontally (using a projectile curve). Currently, I have a class that blits platforms and a background, as well as the player. However, I cannot get it to detect when a platform and the player collide. I have used actual images and then done self.rect = self.image.get_rect() for both the platform and the character. My question is have I done something wrong with my theory or have I just not coded it correctly.

imagen – Imprimir en pantalla imágenes, según pulsación de teclas (pygame)

¡Hola amigos!
Estoy con un proyecto de robótica, con una pantalla como interface de los datos del robot.
Me gustaría hacer en pygame el siguiente pseudocódigo:

-Carga imagen 1
-Carga imagen 2

-Si pulsamos “W” (por ejemplo) en pantalla aparece imagen 1
-Si pulsamos “Q” (por ejemplo) en pantalla aparece imagen 2

Se trata no para un juego, sino para un proyecto de robótica.
Os estaría muy-muy agredecido!

¿Cómo podría hacerlo?
¡Gracias!

python – Física de Colisão de Círculos no Pygame

Estou tendo problemas com um projeto em pygame, preciso realizar a colisão entre dois objetos circulares, no caso dois “peoes”, o único problema é que parece que a colisão só está funcionando em certas direções. Por exemplo se um circulo vier se movimentando da direita pra esquerda nada acontece quando se colidem, na direção contraria funciona perfeitamente. Alguém tem alguma ideia de solução ?

    def colisao(self, obj1, obj2):
        dx = obj1.x -obj2.x
        dy = obj1.y - obj2.y

        distancia = math.hypot(dx, dy)
        if distancia < 60:
            return True
        else:
            return False

    def colisao_peoes(self, peao1, peao2):
        dx = peao1.x - peao2.x
        dy = peao1.y - peao2.y
        if self.colisao(peao1, peao2):
            tangente = math.atan2(dy, dx)
            angulo = 0.5 * math.pi + tangente

            peao1.angulo = 2 * tangente - peao1.angulo
            peao2.angulo = 2 * tangente - peao2.angulo

            (peao1.velocidade, peao2.velocidade) = (peao2.velocidade, peao1.velocidade)

            peao1.velocidade *= 0.8
            peao2.velocidade *= 0.8

            peao1.x += math.sin(angulo)
            peao1.y -= math.cos(angulo)
            peao2.x -= math.sin(angulo)
            peao2.y += math.cos(angulo)

Talvez o problema esteja na forma que mova os círculos também.

 def move(self):
        self.__velocidade -= self.__atrito
        if self.__velocidade <= 0:
            self.__velocidade = 0
        self.__x = self.__x + self.__velocidade * cos(radians(self.__angulo))
        self.__y = self.__y + self.__velocidade * sin(radians(self.__angulo))

python – Changing background color of image pygame

I’m trying to change my background image color, but somehow it doesn’t work, I was googling and asking and I’m new with this, so I hope you will be able to tell me how, and explain me why it doesn’t work.


class Wooden_Boy:

    def __init__(self, win_game):

        self.screen = win_game.screen
        self.screen_rect = win_game.screen.get_rect()

        self.image = pygame.image.load("alien_invasion/images/wooden_boy.png").convert()
        self.image.set_colorkey((0, 0, 255))
        self.rect = self.image.get_rect()

        self.rect.center = self.screen_rect.center

    def blitme(self):
        self.screen.blit(self.image, self.rect)```

This is my second code which is connected with wodden boy:

```import sys

import pygame

from wooden_boy import Wooden_Boy

class Window:


    def __init__(self):

        pygame.init()

        self.screen = pygame.display.set_mode((1200, 800))
        pygame.display.set_caption("Pygame Window")

        self.boy = Wooden_Boy(self)

        self.bg_color = (0, 0, 255)


    def run_window(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            self.screen.fill(self.bg_color)
            self.boy.blitme()

            pygame.display.flip()


if __name__ == "__main__":
    win = Window()
    win.run_window()```

diagonal movement to a enemy in pygame

I spent a long time trying to make the diagonal movement in the form of code but I don’t know how to write it. the code I have so far is almost complete but it is missing the pixelart that I will add later

import pygame

class game():
    def __init__(self):
        self.screen = pygame.display.set_mode((600, 600))
        self.square = pygame.Rect((250, 250), (100, 100))
        self.leftframe = pygame.Rect((40, 40), (10, 510))
        self.rightframe = pygame.Rect((550, 40), (10, 520))
        self.frameup = pygame.Rect((40, 40), (520, 10))
        self.framedown = pygame.Rect((40, 550), (510, 10))

        self.enemy = pygame.Rect((100, 100), (50, 50))
        self.enemy2 = pygame.Rect((450, 300), (50, 50))
        self.enemy3 = pygame.Rect((300, 500), (50, 50))
        self.directionenemy = 1
        self.directionememy2 = 1
        self.directionenemy3 = 1

    def play(self):
        self.clean_screen()
        self.draw_borders()
        self.hear_events()
        self.draw_square()
        self.move_and_draw_enemy()
        self.move_and_draw_enemy2()
        self.move_and_draw_enemy3()
        self.check_for_contact()
        self.check_for_contact2()
        self.check_for_contact3()
        self.update_screen()

    def move_and_draw_enemy(self):
        self.enemy.move_ip(self.directionenemy, 0)

        if self.enemy.colliderect(self.rightframe):
            self.directionenemy = -1
        
        if self.enemy.colliderect(self.leftframe):
            self.directionenemy = 1

        pygame.draw.rect(self.screen, (255, 0, 0), self.enemy)
    
    def move_and_draw_enemy2(self):
        self.enemy2.move_ip(0, self.directionememy2)

        if self.enemy2.colliderect(self.frameup):
            self.directionememy2 = 1

        if self.enemy2.colliderect(self.framedown):
            self.directionememy2 = -1
        
        pygame.draw.rect(self.screen, (10, 50, 255), self.enemy2)


    def move_and_draw_enemy3(self):

        pygame.draw.rect(self.screen, (50, 50, 50), self.enemy3)


    def check_for_contact(self):
        if self.square.colliderect(self.enemy):
            self.directionenemy = 0
        elif self.directionenemy == 0 and not self.square.colliderect(self.enemy):
            self.directionenemy = 1

    def check_for_contact2(self):
        if self.square.colliderect(self.enemy2):
            self.directionememy2 = 0
        elif self.directionememy2 == 0 and not self.square.colliderect(self.enemy2):
            self.directionememy2 = 1

    def check_for_contact3(self):
        if self.square.colliderect(self.enemy3):
            self.directionenemy3 = 0
        elif self.directionenemy3 == 0 and not self.square.colliderect(self.enemy3):
            self.directionenemy3 = 1

    def clean_screen(self):
        self.screen.fill((255, 255, 255))

    def draw_borders(self):
        pygame.draw.rect(self.screen, (72, 47, 125), self.leftframe)
        pygame.draw.rect(self.screen, (72, 47, 125), self.rightframe)
        pygame.draw.rect(self.screen, (72, 47, 125), self.framedown)
        pygame.draw.rect(self.screen, (72, 47, 125), self.frameup)

    def hear_events(self):    
        for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    self.move_and_draw_square(e.key)

    def move_and_draw_square(self, key):
        if key == pygame.K_LEFT:
            self.move_square(-1, 0)
            if self.square.colliderect(self.leftframe):
                self.move_square(1, 0)

        elif key == pygame.K_RIGHT:
            self.move_square(1, 0)
            if self.square.colliderect(self.rightframe):
                self.move_square(-1, 0)

        elif key == pygame.K_UP:
            self.move_square(0, -1)
            if self.square.colliderect(self.frameup):
                self.move_square(0, 1)

        elif key == pygame.K_DOWN:
            self.move_square(0, 1)
            if self.square.colliderect(self.framedown):
                self.move_square(0, -1)

        elif key == pygame.K_ESCAPE:
            pygame.quit()

    def move_square(self, x, y):
        self.square.move_ip(x * 10, y * 10)

    def draw_square(self):
        pygame.draw.rect(self.screen, (0, 204, 0), self.square)

    def update_screen(self):
        pygame.display.update()

pygame.init()
game = game()

while True:
  game.play()
```

Erro ao importar o Pygame e o neat no VS Code

Estou tentando importar o pygame e o neat no VS Code mas ao digitar ambos demonstram os seguintes erros:

Pygame

inserir a descrição da imagem aqui

neat

inserir a descrição da imagem aqui

obs: ambos já foram instalados

gostaria de saber como resolver esse problema para iniciar um novo projeto!

chrome dino game jumping twice per click in pygame

hello i am currently trying to make a jumping game in pygame a lot like the chrome dino game. i have made some simple code to draw a square and make it jump. i will my code dow n bellow. my problem is with the jumping part. whenever i press w wichis the the jump button the square jumps multiple times(usauly 2 times). good people of stack overflow please help a man in need.
here is my code

import pygame

pygame.init()

screen_width = 500
screen_height = 400
isJump = False
y = 350
x = 50
BLUE=(0,0,255)
run = True

screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill((0,0,0))
pygame.display.set_caption("syoma n9ot intelent")
pygame.draw.rect(screen,BLUE,(x,y,50,50))

while run:
  pygame.display.flip()
  for event in pygame.event.get():
      keys = pygame.key.get_pressed()
      if keys(pygame.K_w):
        for a in range (1,250): 
          y -= .5
          screen.fill((0,0,0))
          pygame.draw.rect(screen,BLUE,(x,y,50,50))
          pygame.display.flip()

          
        for a in range (1,250):
          y += .5
          screen.fill((0,0,0))
          pygame.draw.rect(screen,BLUE,(x,y,50,50))
          pygame.display.flip()


          
        
        
 
      if event.type == pygame.QUIT:
       run = False
pygame.quit() 

python – Obtener todos los colores en una superficie Pygame

¡Hola, comunidad de StackOverflow! C:
¿Hay alguna forma en Pygame de obtener todos los colores presentes en una superficie?
Sé que es posible hacer un bucle for obteniendo el color de cada píxel. Sin embargo, quería saber si existe una forma mejor y más rápida de hacer lo mismo.

PYGAME – Sprite movement seize to function when entire X and Y span is reviewed

I’ve created an sprite class that has a detection radius checking if the player enters the zone. If yes, the sprite moves towards the player. It works perfectly fine when the sprite checks for three directions (X is greater, X is lower, Y is greater/lower), in other words, the sprite only moves up and down if all four directions are enabled..

Here is my code for the move function:

def move(self):
        target_x, target_y = self.target.pos

        if self.mob_wc + 1 <= 24:
                           
                if self.pos_x < target_x:
                    self.vel += vec(self.speed, 0)
                    self.image = self.game.orc_mob_walkRight(self.mob_wc//6)
                    self.mob_wc += 1
                    
                elif self.pos_x > target_x:
                    self.vel = vec(-self.speed, 0)
                    self.image = self.game.orc_mob_walkLeft(self.mob_wc//6)
                    self.mob_wc += 1

                if self.pos_y > target_y:
                    self.vel = vec(0, -self.speed)
                    self.mob_wc += 1

                elif self.pos_y < target_y:                   <-- if this condition is disabled
                    self.vel = vec(0, self.speed)                 The sprites move perfectly upwards
                    self.mob_wc += 1                              towards the player, shifting between
                                                                  moving On X and moving on Y.
        else:                                                     However, if it is enabled, the 
            self.mob_wc = 0                                       sprites ONLY move on the Y field
                

Here is my code for the update function:

    def update(self):
        self.rect = self.image.get_rect()
        self.rect.center = self.pos
        self.pos += self.vel * self.game.dt
        
        self.pos_x, self.pos_y = self.pos
        
        target_dist = self.target.pos - self.pos
        

        if target_dist.length_squared() < self.detect_radi**2:
            self.move()    
        else:
            self.vel = vec(0,0)
            self.image = self.game.orc_mob_img

For the way they move i followed this post.
I am aware my build differs due to the use of vectors, which is something that i’m suspecting may be the cause of the issue. If anyone have any idea or tips to why this issue may occur, please tell me cause i’ve been sitting trying to fix this for 3+ hours now..