OOP Pygame player_x变量改变,但显示没有变化



我对编程很陌生,所以这可能是一个相当愚蠢的问题。我目前正试图通过制作游戏来了解更多关于OOP的知识。

当player_x的值由于某些原因而改变时,它没有像我预期的那样移动。

main.py

import pygame, settings, obstacles, npc, player
from utils import *
pygame.init()
window = pygame.display.set_mode((settings.WIDTH, settings.HEIGHT))
FPS = pygame.time.Clock()
player = player.Player(window)
Loop
run = True
while run:
FPS.tick(settings.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
settings.PLAYER_X -= 5
print(settings.PLAYER_X)
pygame.display.update()

player.py

import pygame, settings
pygame.init()
class Player():
def __init__(self, window) -> None:
pygame.draw.rect(window, settings.OLIVE, (settings.PLAYER_X, settings.PLAYER_Y, settings.PLAYER_WIDTH, settings.PLAYER_HEIGHT)) # (x, y, width, height)

def player_control(self):
pass

settings.py

WIDTH = 1440
HEIGHT = 720
FPS = 60
PLAYER_X = 100
PLAYER_Y = 200
PLAYER_WIDTH = 50 
PLAYER_HEIGHT = 50
OLIVE = (136, 196, 23)

要移动您的player,您需要:

  • 在每个while-loop中渲染你的player
  • 用更新的PLAYER_X渲染你的player

要实现它,您需要在代码中进行一些修改:

  1. 创建一个函数在你的player.py中渲染,并在循环中调用它,而不是在__init__中渲染player,这将只被调用一次。

  2. 仅在player.py中的__init__中引用settings.PLAYER_X一次,并在按下键时更新player对象的变量。

  3. 在每个循环结束时,渲染player对象。


player.py

import pygame, settings
pygame.init()
class Player():
def __init__(self, window) -> None:
self.window = window
self.color = settings.OLIVE
self.X = settings.PLAYER_X
self.Y = settings.PLAYER_Y
self.W = settings.PLAYER_WIDTH
self.H = settings.PLAYER_HEIGHT
self.render()

def render(self):
pygame.draw.rect(self.window, self.color, (self.X, self.Y, self.W, self.H)) 

def player_control(self):
pass

main.py

import pygame, settings, player
pygame.init()
window = pygame.display.set_mode((settings.WIDTH, settings.HEIGHT))
FPS = pygame.time.Clock()
player = player.Player(window)
run = True
while run:
FPS.tick(settings.FPS)

for event in pygame.event.get():

if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.X -= 5
print(player.X)
window.fill((0, 0, 0))
player.render()
pygame.display.update()

相关内容

  • 没有找到相关文章