在 PYGAME 中单击图像时如何移动图像?

How to move an image when clicked on it in PYGAME?

基本上,当我单击图像时,我希望图像移动到新的不同位置。当我再次点击时,它应该会再次移动。

import pygame
import random

pygame.init()

screen = pygame.display.set_mode((1420, 750))

pygame.display.set_caption("Soccer Game")
icon = pygame.image.load('soccer-ball-variant.png')
pygame.display.set_icon(icon)


ball = pygame.image.load('soccer2.png')
ballrect = ball.get_rect()

X = random.randrange(0, 1100)
Y = random.randrange(0, 600)

def player():
    screen.blit(ball, (X, Y))

run = True
while run:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            if ball.get_rect().collidepoint(x, y):
                X = random.randrange(0, 1100)
                Y = random.randrange(0, 600)
                player()



    screen.fill((255, 255, 255))
    player()

    pygame.display.update()

问题是这个程序只有在我点击屏幕的左上角时才有效,而不是在球上。我是 pygame 模块的 biginner,但我认为问题是这个 if 语句:

if ball.get_rect().collidepoint(x, y):
    X = random.randrange(0, 1100)
    Y = random.randrange(0, 600)
    player()

pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. A Surface is blit at a position on the screen. The position of the rectangle can be specified by a keyword argument. For example, the top leftof the rectangle can be specified with the keyword argument topleft. These keyword argument are applied to the attributes of the pygame.Rect before it is returned (see pygame.Rect 关键字参数的完整列表)。

if ball.get_rect().collidepoint(x, y):

if ball.get_rect(topleft = (X, Y)).collidepoint(x, y):

但是,我建议删除 XY 变量,而是使用 ballrect

ballrect = ball.get_rect()
ballrect.x = random.randrange(0, 1100)
ballrect.y = random.randrange(0, 600)

def player():
    screen.blit(ball, ballrect)
if ballrect.collidepoint(event.pos):
    ballrect.x = random.randrange(0, 1100)
    ballrect.y = random.randrange(0, 600)

完整示例:

import pygame
import random

pygame.init()
screen = pygame.display.set_mode((1420, 750))
pygame.display.set_caption("Soccer Game")
icon = pygame.image.load('soccer-ball-variant.png')
pygame.display.set_icon(icon)

ball = pygame.image.load('soccer2.png')
ballrect = ball.get_rect()
ballrect.x = random.randrange(0, 1100)
ballrect.y = random.randrange(0, 600)

def player():
    screen.blit(ball, ballrect)

run = True
while run: 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            if ballrect.collidepoint(event.pos):
                ballrect.x = random.randrange(0, 1100)
                ballrect.y = random.randrange(0, 600)

    screen.fill((255, 255, 255))
    player()
    pygame.display.update()