는 메인 게임 루프입니다. 먼저 사용자 입력을 얻습니다. 다음으로, 당신은 그것에 행동합니다. 마지막으로, 몬스터를 움직이거나 산란시키는 것과 같이 게임에 필요한 다른 모든 업데이트를 수행합니다. 이 시점에서, 그것은 되돌아와 사용자에게 다른 명령을 요구합니다.
업데이트 : 속인 적이과 사용자 입력에 의존하고,이 예에서
# In commands.py:
def bag():
print 'bag'
def other():
print 'other'
def unrecognized():
print 'unknown command'
# In main.py:
import commands
def user_input():
print 'a question'
return raw_input('>')
def user_do(command):
# get the matching command out of commands, or pass back
# the unrecognized function if it's not found
action = getattr(commands, command, commands.unrecognized)
action()
is_running = True
while is_running:
command = user_input()
if command == 'quit':
is_running = False
else:
user_do(command)
호출되는 함수의 이름과 동일되는 명령 : 여기은 작업 예입니다. 에서 getattr
호출은 사용자가 입력 한 문자열을 command
모듈의 내용과 비교하여 같은 이름의 함수가 있으면 반환하거나 그렇지 않은 경우 대체 함수 unrecognized
을 반환합니다. action
은 이제 명령 함수 또는 unrecognized
을 보유하게됩니다.
당신이 사용자를하지 않으려는 경우가 너무 밀접하게 실제 기능 자체에 바인딩 명령 대신 if/elif/else
문을 많이 가진 당신은 분기 구조로 dict
을 사용할 수 있습니다 (또는 는을 파견) :
를
# Modified main.py
import commands
COMMAND_DISPATCH = {
'bag': commands.bag,
'sack': commands.bag,
'other': commands.other,
# ...
}
# ...
def user_do(command):
action = COMMAND_DISPATCH.get(command, commands.unrecognized)
action()
이 예에서는 commands
모듈의 기능을 조회하지 않고 대신 COMMAND_DISPATCH
에서 찾았습니다.
조언이 한 번 더 있습니다. 곧 사용자 입력을 하나의 명령 이상으로 파싱하는 것이 좋습니다. 이 예제에서는 "command ..."형식의 입력을 받아 들일 수 있기를 원한다고 가정 해 봅시다. 당신이 알아서하는 user_input
기능을 확장 할 수
def user_input():
print 'a question'
user_input = raw_input('>').split(' ')
command = user_input[0]
arguments = user_input[1:]
return command, arguments
당신이 'foo는 바 바즈'를 입력 그렇다면,이 튜플 ('foo', ['bar', 'baz'])
을 반환합니다. 다음으로 인수를 다루기 위해 메인 루프를 업데이트합니다.텍스트 모험
def bag(arguments):
for argument in arguments:
print 'bagged ', argument
:
def user_do(command, arguments):
action = COMMAND_DISPATCH.get(command, commands.unrecognized)
action(arguments)
그리고 마지막으로, 우리가 수락하고 인수를 처리하는 명령을 수정
while is_running:
# use tuple unpacking to split into command, argument pairs
command, arguments = user_input()
if command == 'quit':
is_running = False
else:
user_do(command, arguments)
그런 다음 우리는 명령에 전달할 확인 command object
, command object preposition subject
및 심지어 command adjective object ...
을 처리하는보다 실질적인 파서를 원할 것입니다.
권자 모험 모듈을보고 ... 그리고 소스를 보면 ... 아마도 –
미안 해요, 무엇을 당신의 말 아무 생각이 없습니다. 주의를 기울여야겠습니까? –