2015-10-15 3 views
1
print "Welcome to the game. In the game you can 'look around' and 'examine things'." 
print "There is also some hidden actions." 
print "You wake up." 

input = raw_input("> ") 

haveKey = False 
applesExist = True 


if input == "look around": 
    print "You are in a dusty cell. There is a barrel in the corner of the room, an unmade bed," 
    print "a cabinet and chest. There is also a cell door." 
elif haveKey == False and input == "open door": 
    print "The door is locked." 
elif haveKey == True and input == "open door": 
    print "You open the door, walk out and immediately gets shot with an arrow. You won, kinda." 
elif input == "examine barrel": 
    print "There is apples in the barrel." 
elif applesExist == True and input == "eat apple": 
    print "Mmmmh, that was yummy! But now there are no apples left..." 
    applesExist = False 
elif applesExist == False and input == "eat apple": 
    print "sury, u et al aples befur!!1111" 
elif input == "examine bed": 
    print "The bed is unmade, and has very dusty sheets. This place really needs a maid." 
elif input == "sleep on bed": 
    print "You lie down and try to sleep, but you can't because of all the bugs crawling on you." 
elif input == "examine chest": 
    print "There is a key in the chest." 
elif input == "take key": 
    haveKey = True 
    print "You take the key." 
elif input == "examine cabinet": 
    print "The cabinet is made of dark oak wood. There is a endless cup of tea in it." 
elif input == "drink tea": 
    print "You put some tea in your mouth, but immediately spit it out." 
    print "It seems it has been here for quite some time." 
else: 
    print "Huh, what did you say? Didn't catch that." 

Um, hi. Мне нужна помощь. Как вы можете видеть, это очень простая текстовая игра, которую позволяет игроку взаимодействовать с окружающей средой. Я планирую расширить взаимодействующую вещь , и с этим мне не нужна помощь. Но с игровым циклом я это делаю. Вы, вероятно, понимаете, но для тех, кто этого не делает, каждый раз, когда я пишу команду, программа закрывается. Мне сказали, что для этого мне нужен игровой цикл, но я понятия не имею, как это сделать.Текстовая игра - Игровая петля

Что-то, что мне нужно сказать вам, по сравнению с вами, я немного замедлен. Я не программирующий гений, просто просто наслаждаюсь программированием. Поэтому, пожалуйста, просто скажите , как, а не почему. Я сам это пойму, так как я все время в мире. И если мне когда-нибудь понадобится знать , почему, то я еще раз спрошу вас! = D

+0

Вы * делаете * знаете о петлях и как их сделать? Например, создавая цикл, итерации * while * выполняется какое-то условие? –

+0

Да, kinda = D. Я знаю, как сделать что-то петлю навсегда, или до логического изменения, но это мой лимит =) – Elsvaer

+0

Тогда подумайте немного (каламбур не предназначен): вы создаете цикл, который петли, пока пользователь не хочет уходить, это так просто. Вам нужна переменная, которая инициализируется значением «Истина» и остается «Истина», пока пользователь не запустит команду для выхода и не использует эту переменную в качестве условия цикла. –

ответ

0

Вы должны использовать петлю наподобие while. Вы должны получить вход изнутри цикла. И вы должны проверить, закончилась ли игра или нет. Вход будет сбрасываться автоматически из-за raw_input() функции:

print "Welcome to the game. In the game you can 'look around' and 'examine things'." 
print "There is also some hidden actions." 
print "You wake up." 

haveKey = False 
applesExist = True 
gameover = False 

while gameover == False: 
    input = raw_input("> ") 
    if input == "look around": 
     print "You are in a dusty cell. There is a barrel in the corner of the room, an unmade bed," 
     print "a cabinet and chest. There is also a cell door." 
    elif haveKey == False and input == "open door": 
     print "The door is locked." 
    elif haveKey == True and input == "open door": 
     print "You open the door, walk out and immediately gets shot with an arrow. You won, kinda." 
    elif input == "examine barrel": 
     print "There is apples in the barrel." 
    elif applesExist == True and input == "eat apple": 
     print "Mmmmh, that was yummy! But now there are no apples left..." 
     applesExist = False 
    elif applesExist == False and input == "eat apple": 
     print "sury, u et al aples befur!!1111" 
    elif input == "examine bed": 
     print "The bed is unmade, and has very dusty sheets. This place really needs a maid." 
    elif input == "sleep on bed": 
     print "You lie down and try to sleep, but you can't because of all the bugs crawling on you." 
    elif input == "examine chest": 
     print "There is a key in the chest." 
    elif input == "take key": 
     haveKey = True 
     print "You take the key." 
    elif input == "examine cabinet": 
     print "The cabinet is made of dark oak wood. There is a endless cup of tea in it." 
     gameover = True 
    elif input == "drink tea": 
     print "You put some tea in your mouth, but immediately spit it out." 
+1

Почему «перезагрузка» входной строки в конце цикла? Сначала он будет «перезагружен», как только цикл начнется в любом случае. –

+0

@JoachimPileborg да, ты прав, я ошибся из-за моего тестового заказа. не нужна эта строка: 'input = 0' – mertyildiran

+0

Нет проблем, извините за поздний ответ, отправился на resturaunt и съел некоторые суши. Но я сохраню: input = 0, поскольку он напоминает мне о вас. Я люблю тебя. Спасибо за решение моей тривиальной проблемы = D – Elsvaer

Смежные вопросы