Pygame - 更流畅的运动

时间:2016-08-29 07:55:11

标签: python pygame

我在main_screen上添加了一个对象/图像,该对象名为cancer_cell。 我在这里要做的是我希望对象顺利移动。我必须重复按箭头键以保持它移动。 如何移动while箭头键被按下?

这是代码:

exitgame = False
cellpos_x = 0
cellpos_y = cancer_cell.get_rect().height*2
while not exitgame:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exitgame = True
            quitgame()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                cellpos_x -= 10
            if event.key == pygame.K_RIGHT:
                cellpos_x += 10


    gameplay_bg = pygame.image.load("/Users/wolf/Desktop/python/img/gameplay_bg.png").convert()
    main_screen.fill(white)
    main_screen.blit(gameplay_bg, [0,0])
    main_screen.blit(cancer_cell, [cellpos_x, cellpos_y])
    pygame.display.flip()
    clock.tick(20)

有人告诉我在How to use pygame.KEYDOWN尝试解决方案: 但那也不起作用。或许我做错了:

if event.type == pygame.KEYDOWN:
    key_pressed = pygame.key.get_pressed()
    if key_pressed[pygame.K_LEFT]:
        cellpos_x -= 10
    if key_pressed[pygame.K_RIGHT]:
        cellpos_x += 10

2 个答案:

答案 0 :(得分:0)

问题已解决

我通过从FOR循环中取消这个部分来解决这个问题     而不是退出游戏:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exitgame = True
            quitgame()

    key_pressed = pygame.key.get_pressed()
    if key_pressed[pygame.K_LEFT]:
        cellpos_x -= 10
    if key_pressed[pygame.K_RIGHT]:
        cellpos_x += 10

答案 1 :(得分:0)

我看到你已经解决了缩进问题,这是你的例子的另一个版本:

import pygame

class Player(object):
    def __init__(self, img_path):
        self.image = pygame.image.load(img_path)
        self.x = 0
        self.y = self.image.get_rect().height*2

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_RIGHT]:
            self.x += dist
        elif key[pygame.K_LEFT]:
            self.x -= dist

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


pygame.init()
clock = pygame.time.Clock()
size = width, height = 1024, 768
speed = [2, 2]
white = 1, 1, 1
main_screen = pygame.display.set_mode(size)
gameplay_bg = pygame.image.load("background.jpg")
cancer_cell = Player("player.jpg")
running = False

while not running:
    event = pygame.event.poll()

    if event.type == pygame.QUIT:
        running = True

    main_screen.fill(white)
    main_screen.blit(gameplay_bg, [0, 0])

    cancer_cell.handle_keys()
    cancer_cell.draw(main_screen)

    pygame.display.flip()

    clock.tick(50)
    pygame.display.set_caption("fps: " + str(clock.get_fps()))

你需要调整图像的路径(" background.jpg"," player.jpg"),这个版本你不会一遍又一遍地加载游戏事件循环中的精灵和玩家的动作将是平滑的。