Python / Pygame鼠标位置不更新(blit函数)

时间:2014-09-19 02:24:09

标签: python pygame

我正在尝试使用Pygame制作一个简单的菜单,但我发现每当我使用pygame.mouse.get_position时,它确实是我想要的但是我必须继续移动鼠标以使我的图片保持blitting。

import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('cursor test')

cursorPng = pygame.image.load('resources/images/cursor.png')
start = pygame.image.load('resources/images/menuStart.jpg')
enemy = pygame.image.load('resources/images/enemy-1.png')

white = (255,255,255)
black = (0,0,0)

clock = pygame.time.Clock()
FPS = 60

while True:
    screen.fill(white)
    pygame.mouse.set_visible(False)

    x,y = pygame.mouse.get_pos()
    x = x - cursorPng.get_width()/2
    y = y - cursorPng.get_height()/2
    screen.blit(cursorPng,(x,y))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

        elif event.type == pygame.MOUSEMOTION:
            if x < 50 and y < 250:
                screen.blit(enemy,(100,100))

    clock.tick(FPS)
    pygame.display.update()

出了什么问题?

2 个答案:

答案 0 :(得分:0)

看看你的代码:

for event in pygame.event.get():
    ...
    elif event.type == pygame.MOUSEMOTION:
        if x < 50 and y < 250:
            screen.blit(enemy,(100,100))

您检查事件,如果您检测到鼠标正在被移动(并且只有那时),则将图像绘制到屏幕上。

如果您想要在不移动鼠标的情况下绘制图像,只需停止检查MOUSEMOTION事件并简单地绘制图像:

while True:
    screen.fill(white)
    pygame.mouse.set_visible(False)

    x,y = pygame.mouse.get_pos()
    x = x - cursorPng.get_width()/2
    y = y - cursorPng.get_height()/2
    screen.blit(cursorPng,(x,y))
    if x < 50 and y < 250:
        screen.blit(enemy,(100,100))

    for event in pygame.event.get():
        ...

答案 1 :(得分:-1)

你需要在屏幕上blit一个Surface和一个Rect。

首先,使用我用于加载图片的代码段。它确保正确加载图像:

def loadImage(name, alpha=False):
"Loads given image"

    try:
        surface = pygame.image.load(name)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s' %
                     (name, pygame.get_error()))
    if alpha:
        corner = surface.get_at((0, 0))
        surface.set_colorkey(corner, pygame.RLEACCEL)

    return surface.convert_alpha()

其次,当你得到Surface时,得到它的矩形:

cursorSurf = loadImage('resources/images/cursor.png')
cursorRect = cursorSurf.get_rect()

然后,在更新内部执行以下操作:

cursorRect.center = pygame.mouse.get_pos()

最后,像这样盲目地屏幕:

screen.blit(cursorSurf, cursorRect)

现在您将注意到您的鼠标无需移动鼠标即可正确呈现。