首页 > 解决方案 > 与上一个问题类似,但已切换到 OOP,如何让我的精灵移动?

问题描述

我设法在屏幕上显示我的精灵,但无法移动它。已设置移动键。

我并没有真正尝试太多导致任何改变的东西。

import pygame
pygame.init()

window = pygame.display.set_mode((650, 630))

pygame.display.set_caption("PeaShooters")

avatar = pygame.image.load('Sprite 1 Red.png')
background = pygame.image.load('Bg.jpg')
white = (255, 255, 255)

class player(object):
    def __init__(self, x, y, width, height):
        self.x = 300
        self.y = 500
        self.width = 40
        self.height = 60
        self.vel = 9



def drawGrid():
    window.blit(background, (0,0))
    window.blit(avatar, (300, 500))
    pygame.draw.line(window, white, [50,50], [50, 600], 5)
    pygame.draw.line(window, white, [50,50], [600, 50], 5)
    pygame.draw.line(window, white, [600,600], [600, 50], 5)
    pygame.draw.line(window, white, [50,600], [600, 600], 5)
    pygame.draw.line(window, white, [50,450], [600, 450], 5)
    pygame.display.update()

av = player(300, 500, 40, 60)
running = True
while running:
    pygame.time.delay(100) 

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

    keys = pygame.key.get_pressed()

    if keys[pygame.K_w] and av.y > 440:
        av.y -= av.vel

    if keys[pygame.K_a] and av.x > 65:
        av.x -= av.vel

    if keys[pygame.K_s] and av.y < 530:
        av.y += av.vel

    if keys[pygame.K_d] and av.x < 525 :
        av.x += av.vel


    drawGrid()

window.blit(avatar, (x,y))

pygame.quit()

当我加载游戏时,玩家应该移动它没有做的事情。

标签: pythonpygame

解决方案


您正在按键检查中更新您的玩家位置,但没有使用这些值将您的玩家blit到正确的位置。尝试更改此行:

window.blit(avatar, (300, 500))

window.blit(avatar, (av.x, av.y))

推荐阅读