pygame - 用鼠标移动一个精灵,用键盘移动另一个精灵?

时间:2015-12-18 22:00:00

标签: python pygame

我试图让每个精灵在屏幕上独立移动。第一部分主要是填充/定义变量,我已经将问题略微降低了一点。

由键盘控制的那个正在工作,但我试图用鼠标控制的精灵静止不动。可能是一个变数问题,但我似乎无法确切地知道它是什么。想知道如何解决这个问题?

import pygame
import sys
from pygame.locals import *
import time

pygame.init()

#preset colors
black = (0, 0, 0)
white = (255, 255, 255)

#screen display
screen = pygame.display.set_mode((800, 600)) 
pygame.display.set_caption("RADICAL")
screen.fill(white)

#sprites and sounds
imga = pygame.image.load('coina.png')
imgb = pygame.image.load('coinb.png')

imgc = pygame.image.load('berrya.png')
imgd = pygame.image.load('berryb.png')
sound = pygame.mixer.Sound('coin.wav')

#preset variables
FPS = 30
imgx = 10
imgy = 10
picx = 1
picy = 1
pixMove = 5
steps = 0  
x1 = 0 
y1 = 0
stepsb = 0
x2 = 0  
y2 = 0
fpsTime = pygame.time.Clock()

#actions
GameOver = False
while not GameOver:
    screen.fill(white)
    imgx += x1
    imgy += y1

    picx += x2
    picy += y2

    points = (steps)
    font = pygame.font.SysFont(None, 30)
    text = font.render('Control the coin with the keyboard, and the berry   with the mouse', True, black)
    screen.blit(text, (0,0))

    if steps % 2 == 0: 
        screen.blit(imga, (imgx, imgy))
    else:
        screen.blit(imgb, (imgx, imgy))

    if stepsb % 2 == 0: 
        screen.blit(imgc, (picx, picy))
    else:
        screen.blit(imgd, (picx, picy))        

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

这是我遇到问题的代码的具体部分

        elif event == MOUSEMOTION:
            (x2, y2) = pygame.mouse.get_pos()

此后的所有内容都有效,或者至少我是这么认为的。

        elif event.type == KEYDOWN:
            if event.key == K_UP:
                y1 -= pixMove
            elif event.key == K_DOWN:
                y1 += pixMove
            elif event.key == K_LEFT:
                x1 -= pixMove
            elif event.key == K_RIGHT:
                x1 += pixMove
        elif event.type == KEYUP:
            if event.key == pygame.K_LEFT:
                x1 = 0 
            elif event.key == pygame.K_RIGHT:
                x1 = 0 
            elif event.key == pygame.K_UP:
                y1 = 0 
            elif event.key == pygame.K_DOWN:
                y1 = 0
                steps +=1

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

1 个答案:

答案 0 :(得分:1)

你的逻辑不太正确。键盘精灵一次移动pixMove,而鼠标精灵正在移动大部分屏幕; get_pos()将返回鼠标的当前位置,因此它将很快飞离屏幕。

您当前的问题是“event == MOUSEMOTION”而不是“event.type == MOUSEMOTION”。