我为糟糕的头衔道歉。我有使用C#(XNA)或java(LibGDX)编写游戏代码的经验,但我最近开始专门使用python和pygame,我无法弄清楚如何设计代码。这就是我认为它会做的事情:
game.py文件:
import pygame
import entities
width = 400
height = 300
# Set up the window size
screen = pygame.display.set_mode((width, height), 0, 32)
player = entities.Player(width / 2, height / 2) # The player
#main game loop is here...
entities.py文件:
import pygame
import game
class Player:
def __init__(self, x, y):
# Texture for the player
self.texture = pygame.image.load('player.png')
def draw(self):
""" Draws the player """
game.screen.blit(self.texture, (self.position.x, self.position.y))
#class Enemy: ...
但是这段代码给了我错误。我认为问题在于我在entities.py
中导入game.py
,然后在game.py
中导入entities.py
。
我将如何在python中正确设计它?
答案 0 :(得分:1)
我建议使用pygame已经提供的内容。
所以你的玩家类看起来像:
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
# Texture for the player
self.image = pygame.image.load('player.png')
self.rect = self.image.get_rect(topleft=(x, y))
# no need for a draw function
# the sprite class will handle this
# just make sure you store the coordinates of
# your entity in self.rect
def update(self, some_game_state):
pass # do something with some_game_state
然后,在您的游戏中,您将所有实体放在一个(或多个)组中,只需在该组上调用draw
和update
。
entities = pygame.sprite.Group(player) # add other sprite here, too
# main loop
while True:
...
# pass the game state to all entities
# how you design this is up to you
# (pass multiple values, pass a single instace of the game class,
# create a class that encapsulates the state necesseray for the entities etc.)
entites.update(some_game_state)
# pass the main surface to the draw function
entities.draw(screen)
...
答案 1 :(得分:0)
您应该将变量传递给相关的类,而不是将它们作为全局变量并导入它们。因此,一种可能的解决方案是使screen
成为Player的属性:
class Player:
def __init__(self, x, y, screen):
self.screen = screen
...
def draw(self):
""" Draws the player """
self.screen.blit(...)
现在,无需在entities.py中导入game
,您可以像这样实例化播放器:
player = entities.Player(width / 2, height / 2, screen)
可能有其他方法可以做到这一点,但这应该会给你一个想法。