【问题标题】:pygame.mouse.get_pos() failing when function called调用函数时 pygame.mouse.get_pos() 失败
【发布时间】:2014-04-07 12:51:42
【问题描述】:

问题: 当调用“战斗”功能时,鼠标位置基本上锁定在原地而不会更新。

尝试的修复: 1. 我尝试将获取鼠标位置及其相关代码移动到函数的不同区域。
2. 我也试过让函数自己生成一个新的“指针”实例。

显然这些都失败了,下面的代码只是我最近尝试让它工作的尝试之一。

有人可以解释为什么会这样吗?

import pygame
from pygame.locals import *
pygame.init()

size = [900, 845]
screen = pygame.display.set_mode(size)

class Pointer(pygame.sprite.Sprite):

 def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.image.load("mouse.png").convert_alpha()
    self.rect = self.image.get_rect()
    self.rect.x=5
    self.rect.y=5

all_sprites_list = pygame.sprite.Group()        
pointer = Pointer()
all_sprites_list.add(pointer)

player=5
enemy=5

def Combat():          

    while True:
        pygame.display.flip()
        if player == 0:
            print("GAME OVER")
            break
        elif enemy == 0:
            print("victory!")
            break
        else:            
            mx,my = pygame.mouse.get_pos()      
            pointer.rect.x=mx
            pointer.rect.y=my
            print(mx,my)

done = False
clock = pygame.time.Clock()

while done ==False:

    clock.tick(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            done = True


    mx,my = pygame.mouse.get_pos()
    print(mx,my)
    screen.fill((200,200,200))
    pointer.rect.x=mx
    pointer.rect.y=my  
    all_sprites_list.draw(screen)
    Combat()

    pygame.display.flip()

pygame.quit()

【问题讨论】:

  • 你想要做什么
  • 战斗功能将生成一个带有碰撞检测/鼠标按下的小侧面菜单供用户输入。我刚刚删除了所有额外的游戏代码以便于查看。现在我只想在调用函数时正确更新鼠标。
  • 你为什么不直接使用for event in pygame.event.get() \n if event.type in (MOUSEMOTION, MOUSEBUTTONDOWN, MOUSEBUTTONUP): \n mx,my = event.pos

标签: function python-3.x pygame mouse


【解决方案1】:

Combat() 函数正在阻塞您的系统,而不是处理新事件。

您应该添加clock.tick() 并投票事件:

def Combat():          

    while True:
        clock.tick(30)
        pygame.event.poll()
        ...

【讨论】:

    猜你喜欢
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 2021-09-16
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多