Pygame,继续跳跃和通过“地面”的故障

时间:2014-11-24 21:28:18

标签: python pygame

我的角色不会正常跳跃,他不停地在地上摔跤。如果我按住键,我的角色不会停止走高。你对我如何解决它有什么想法吗?

import pygame,sys
from pygame.locals import *

pygame.init()


screen = pygame.display.set_mode((1200, 800))
screen.fill((0,0,0))
pygame.display.set_caption('Jump and Run')

BLACK = (0,0,0)
WHITE = (250, 250,250)
RED = (250, 0, 0)
BLUE = (0,0,250)

direction = 'right'
way = 0
jump_high = 0

class Hero():
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.image = pygame.image.load('hero.bmp')
        self.groundcontact = True
        self.vy = 0
        alive = True

    def check_pos(self):
        if self.y >= 400:
            self.groundcontact = True
        elif self.y <= 400:
            self.groundcontact = False

    def load_picture(self,surface):
        surface.blit(self.image,(self.x, self.y))

    def check_input(self):
        key = pygame.key.get_pressed()
        if key[pygame.K_RIGHT]:
            self.x += 10
        elif key[pygame.K_LEFT]:
            self.x -= 10
        elif key[pygame.K_UP]:
            self.y -= 50

        if not self.groundcontact:
            self.vy += 1 #max(min(2,200), -200)
            #self.y += self.vy 
            print "not self.groundcontact"
        else:
            self.vy = 0
            #self.y += self.vy 
        self.y += self.vy


class Monster():
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.image = pygame.image.load('monster.bmp')
        self.collision = False
        self.alive = True

    def load_picture(self,surface):
        surface.blit(self.image,(self.x, self.y))

    def walk(self):
       global direction
       global way
       if direction == "right":
          self.x += 4
          way += 1
          if way == 100:
              direction = "left"
       elif direction == "left":
          self.x -= 4
          way -= 1
          if way == 0:
             direction = "right"  

monster2 = Monster( 200, 333)
monster1 = Monster(400, 450)
hero = Hero(0, 400)
clock = pygame.time.Clock()

pygame.draw.rect(screen, WHITE,(0,500, 1200, 50))

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



    hero.check_pos()
    monster1.walk()
    monster2.walk()
    hero.check_input()
    screen.fill(BLACK)
    hero.load_picture(screen)
    monster1.load_picture(screen)
    monster2.load_picture(screen)
    pygame.draw.rect(screen, WHITE,(0,500, 1200, 50))
    pygame.display.update() 


    clock.tick(40)

1 个答案:

答案 0 :(得分:1)

关于我上面的评论,将Hero类更改为以下内容:

JUMP_POWER = 10

class Hero():

    ...

    def check_input(self):
        key = pygame.key.get_pressed()

        ...

        elif key[pygame.K_UP]:
            if self.groundcontact:
                self.vy -= JUMP_SPEED