简单的Python脚本中的流控制

时间:2012-07-04 07:29:10

标签: python python-3.x python-2.7

我正在尝试制作一款简单的游戏。

逻辑是这样的:“有五个门,每个门编号为1到5.用户将被要求输入任何一个号码。例如,如果他们输入”1“,GoldRoom将被打开(和相关联课程将被处理)。“

现在,我已经定义了一个类GoldRoom(),并且为了测试,输入了“1”。处理按预期进行。但是,当我输入“2”作为我的选择时,处理仍然发生,而不是print语句,即else语句没有被执行。

我哪里错了?

#################################
#   Learning to make a game#
#################################

# An attempt to make a game
# Each room will be described by a class, whose base class will be Room
# The user will be prompted to enter a number, each number will be assigned with a Room in return

from sys import exit

print "Enter your choice:"
room_chosen = int(raw_input("> "))

if room_chosen == 1:
    goldroom = GoldRoom()
    goldroom.gold_room()


def dead(why):
    print "why, Good Job!"
    exit(0)

#class Room(object):  #the other room will be derived of this
#   pass

class Room(object):
    pass

class GoldRoom(Room):

    # here the user will be asked with question on how much Gold he wants

    print"This room is full of gold. How much do you take!"

    next = raw_input("> ")

    if "0" in next or "1" in next:
        how_much = int(next)
        print how_much
    else:
        dead("Man, learn to type some number")

    if how_much < 50:
        print "Nice, you are not greedy, you win!"
        exit(0)

    else:
        dead("You greedy bastard!")

#class KoiPondRoom(Room):

    # in this room, the user will be made to relax

#class Cthulhu_Room(Room):

    # sort of puzzle to get out

#class Bear_Room(Room):

    # bear room

#class Dark_Room(Room):

    # Dark Room, will  be turned into Zombie

#class Dead_Room(Room):

    # Those who enter here would be dead
if room_chosen == 1:
    goldroom = GoldRoom()
    goldroom.gold_room()
else:
    print "YOU SUCK!"

1 个答案:

答案 0 :(得分:5)

问题在于:

class GoldRoom(Room):

    # here the user will be asked with question on how much Gold he wants

    print"This room is full of gold. How much do you take!"

当整个源加载到python vm中时,这段代码被执行,并且它打印了一些东西,你应该把它改成:

class GoldRoom(Room):

    # here the user will be asked with question on how much Gold he wants
    def gold_room(self):
        print"This room is full of gold. How much do you take!"

        next = raw_input("> ")

        if "0" in next or "1" in next:
            how_much = int(next)
            print how_much
        else:
            dead("Man, learn to type some number")

        if how_much < 50:
            print "Nice, you are not greedy, you win!"
            exit(0)

        else:
            dead("You greedy bastard!")