2014-09-19 83 views
0

我想使用pygame做一个简单的菜单,但我发现每当我使用pygame.mouse.get_position,它确实blit我想要但我必须保持移动我的鼠标,使我的图片保持blitting。python/pygame鼠标位置不更新(blit函数)

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() 

怎么了?

回答

-1

你需要在屏幕上出现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() 

其次,当你的面,得到了矩形这样的:

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

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

cursorRect.center = pygame.mouse.get_pos() 

而且finnally,blit的筛选是这样的:

screen.blit(cursorSurf, cursorRect) 

现在您会注意到您的鼠标无需移动鼠标即可正确渲染。

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(): 
     ...