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

时间:2021-05-07 12:17:04

标签: python pygame pygame-surface

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

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 模块中的大人物,但我认为问题在于 if 语句:

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

1 个答案:

答案 0 :(得分:2)

pygame.Surface.get_rect.get_rect() 返回一个具有 Surface 对象大小的矩形,该矩形总是从 (0, 0) 开始,因为 Surface 对象没有位置。 表面 blit 位于屏幕上的某个位置。矩形的位置可以通过关键字参数指定。例如,矩形的左上角可以用关键字参数 topleft 指定。这些关键字参数在返回之前应用于 pygame.Rect 的属性(有关关键字参数的完整列表,请参阅 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()
相关问题