我对这个糟糕的标题表示歉意。我对如何使用 C# (XNA) 或 java (LibGDX) 编写游戏代码有经验,但我最近开始专门使用 python 和 pygame,并且我很难弄清楚如何设计代码。这就是我认为应该做的事情:
游戏.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: ...
但是这段代码给了我错误。我认为问题是我在 game.py
中导入 entities.py
,然后在 中导入
。 game.py
实体.py
我将如何在 python 中正确设计它?
最佳答案
我建议使用 pygame 已经提供的内容。
看看类(class) Sprite
和 Group
(及其更复杂的子类)。
所以你的玩家类可能看起来像:
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)
...
关于python - Pygame - 设计代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31220011/