python - Pygame - 设计代码

标签 python pygame

我对这个糟糕的标题表示歉意。我对如何使用 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) SpriteGroup (及其更复杂的子类)。

所以你的玩家类可能看起来像:

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

然后,在您的游戏中,您可以将所有实体放入一个(或多个)组中,然后只需对该组调用 drawupdate (小)。

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/

相关文章:

python - 图像不响应不同的按键 Pygame Python

python - pandas 按 3 个变量分组,但对其中 2 个变量求和

Python DataFrame - 根据列的值应用不同的计算

python - PyGame 获取 Sprite 组

python - 近距离 3D 显示困惑

python - 无法使用pip安装pyaudio

python - 类型错误 : 'int' object has no attribute '__getitem__'

python - 为什么单击按钮时插入命令 OpenERP

python - 如何更改 settings.py 以从 SQLite3 数据库迁移到 mysql 数据库?

python - 有没有更有效的方法来重写多个 if-else 语句