我已经编写了一个简单的控制台游戏,允许我把我的玩家移动到一个有墙和空格的小关卡里。所有这些都是用几个简单的函数来完成的。你知道吗
我对Python还比较陌生,但接下来我想学习OOP,如果我想让这个游戏面向对象,我将如何继续呢?你知道吗
我非常理解类和对象,但是如果我不理解所有的答案,请原谅我。你知道吗
以下是当前游戏:
LEVEL = [
'xxxxxx',
'x x',
'x i x',
'x x',
'x x',
'xxxxxx'
]
def get_block(x, y):
"""Gets a block at the given coordinates."""
try:
return LEVEL[y][x]
except IndexError:
return None
def set_block(x, y, block):
"""Sets a block at the given coordinates."""
try:
LEVEL[y] = LEVEL[y][:x] + block + LEVEL[y][x + 1:]
except IndexError:
pass
def get_player_position():
"""Gets player's position."""
for y, row in enumerate(LEVEL):
for x, column in enumerate(row):
if column == 'i':
return x, y
def set_player_position(x, y):
"""Sets player's position."""
block = get_block(x, y)
if block == ' ':
px, py = get_player_position()
set_block(px, py, ' ')
set_block(x, y, 'i')
def main():
"""Entry point for the program."""
cmd = ''
while cmd.lower() not in ('quit', 'q'):
print('\n' * 30)
for row in LEVEL:
print(row)
cmd = input('Command: ').lower()
px, py = get_player_position()
if cmd == 'w':
set_player_position(px, py - 1)
elif cmd == 's':
set_player_position(px, py + 1)
elif cmd == 'a':
set_player_position(px - 1, py)
elif cmd == 'd':
set_player_position(px + 1, py)
print('Bye.')
if __name__ == '__main__':
main()
你的问题是非常开放的,所以很难给出一个包罗万象的答案-所以我所做的是在你现有的代码中识别一个数据结构,并将其转化为一个类。你知道吗
用于对全局数据结构进行操作的函数现在都是类实例的公共方法,该类是唯一允许对其内部名为
_field
的私有属性中的数据进行更改的函数。你知道吗做这类事情是编写面向对象软件必不可少的第一步。你知道吗
希望你觉得这个例子有些启发。你知道吗
相关问题 更多 >
编程相关推荐