Pygame矩形和鼠标位置碰撞点不工作

2024-09-29 21:39:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个基本的游戏,我有一个表面,每次我点击表面它移动5个像素的权利。程序在没有checkCollide(event)函数的情况下运行得很好,但是当我设置这个条件时,它不会移动。怎么了?在

我现在的密码是

import pygame, sys
from pygame.locals import *

pygame.init()

DISPLAYSURF = pygame.display.set_mode((300,300))

def checkCollide(event):
    k = 0
    a,b = event.pos
    x = P1[0].get_rect()
    if x.collidepoint(a,b):
        return True
    return False

CP1 = [(150, 150)
      ,(155, 150)
      ,(160, 150)
      ,(165, 150)
      ,(170, 150)
      ,(175, 150)
      ,(180, 150)
      ,(185, 150)
      ,(190, 150)]

statp1_1 = 0

WHITE = (255,255,255)
DISPLAYSURF.fill(WHITE)

while True: # the main game loop
    P1 = [pygame.image.load('PAzul.png'),CP1[statp1_1],statp1_1]
    DISPLAYSURF.blit(P1[0], P1[1])
    e = pygame.event.get()
    for event in e:
        if event.type == MOUSEBUTTONUP:
            a = checkCollide(event)
            if a:
                DISPLAYSURF.fill(WHITE)
                statp1_1 +=1

        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

谢谢你


Tags: importeventtruegetreturnifdisplaysys
3条回答

我才意识到怎么了。当我做x = P1[0].get_rect()时,它将创建一个上左上角为(0,0)的曲面。 我需要做的是使用x.topleft = P1[1]更改矩形的位置

我有一些建议给你。首先将rect存储在P1列表中(在下面的示例中,它只包含图像和rect,但是您也可以向其添加statp1_1索引)。现在我们可以移动这个rect,如果用户单击它(在这个例子中,我将topleft属性设置为下一个点)。阅读评论了解更多提示。需要解决的一件事是防止游戏在statp1_1索引太大时崩溃。在

import sys
import pygame


pygame.init()

DISPLAYSURF = pygame.display.set_mode((300, 300))

WHITE = (255, 255, 255)
# Don't load images in your while loop, otherwise they have to
# be loaded again and again from your hard drive.
# Also, convert loaded images to improve the performance.
P1_IMAGE = pygame.image.load('PAzul.png').convert()  # or .convert_alpha()

# Look up `list comprehension` if you don't know what this is.
CP1 = [(150+x, 150) for x in range(0, 41, 5)]

statp1_1 = 0
# Now P1 just contains the image and the rect which stores the position.
P1 = [P1_IMAGE, P1_IMAGE.get_rect(topleft=CP1[statp1_1])]

clock = pygame.time.Clock()  # Use this clock to limit the frame rate.

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONUP:
            if P1[1].collidepoint(event.pos):
                print('clicked')
                statp1_1 += 1
                # Set the rect.topleft attribute to CP1[statp1_1].
                P1[1].topleft = CP1[statp1_1]

    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(P1[0], P1[1])  # Blit image at rect.topleft.

    pygame.display.update()
    clock.tick(30)  # Limit frame rate to 30 fps.

在以下函数行中检查逻辑:

x = P1[0][0].get_rect()
if x.collidepoint(a,b):
    return True
return False

你的代码取决于这一点:

^{pr2}$

所以你永远不会认为这篇文章是真的。在

相关问题 更多 >

    热门问题