Pygame按键事件

时间:2014-04-23 20:39:42

标签: python events key pygame

嘿伙计们我试图为我所拥有的精灵添加动作,而且我遇到了一些麻烦,继承人的代码。我使用WASD键将玩家移动到这个地方,我似乎无法弄清楚为什么它不会移动。任何帮助表示赞赏。

import pygame
import math 
from sys import exit
from pygame.locals import *
pygame.mixer.init

class Player(pygame.sprite.Sprite):
    def __init__(self, screen):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("ryu.png")
        transColor = self.image.get_at((1, 1))
        self.image.set_colorkey(transColor)
        self.rect = self.image.get_rect()
        self.dx = screen.get_width()/2
        self.dy = screen.get_height()/2 
        self.rect.center = (self.dx, self.dy)
        self.screen = screen
        self.speed = 4

        def update(self):
            self.rect.center = (self.dx, self.dy)

        def returnPosition(self):
            return self.rect.center
        def MoveLeft(self):
            if  self.rect.left < 0:
                self.dx+=0
            else:
                self.dx-=self.speed

        def MoveRight(self):
            if self.rect.right >self.screen.get_width():
                self.dx+=0
            else:
                self.dx+=self.speed

        def MoveUp(self):
            if self.rect.top <0:
                self.dy+=0
            else:
                self.dy-=self.speed
        def MoveDown(self):
            if self.rect.bottom > self.screen.get_height():
                self.dy+=0
            else:
                self.dy+=self.speed

def checkKeys(myData):
    (event, player) = myData
    keys = pygame.key.get_pressed()
    if keys [K_a]:
        print 'He turned left!!!'
        player.MoveLeft()
    if keys [K_s]:
        print "He's going down!!!"
    if keys [K_d]:
        print "He turned right!!!"
    if keys [K_w]:
        print "He's going up!!!"

def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    keepGoing = True    
    pygame.display.set_caption("Creating a sprite")

    player = Player(screen)

    background = pygame.Surface(screen.get_size())
    background.fill((0, 0, 0))

    allSprites = pygame.sprite.Group(player)

    while keepGoing:
        clock.tick(30)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False

        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)
        pygame.display.flip()

if __name__ == "__main__":
    main()

0 个答案:

没有答案