2

我对编程游戏还很陌生;我已经完成了 3/4,Learn Python the Hard Way我有一个关于我制作的基于文本的小游戏的问题......所以在这个游戏中,我guy被困在一个荒岛上,你可以选择(原始输入)去left rightinto the jungle. 选择方向后,您可以选择步行多少英里。每个方向都应该有不同的最终结果(和英里距离)。

如果您输入的数字小于到目的地的里程数,系统会提示您选择“转身”或“继续前进”。如果您输入turn around,您将被带回到起点,您' 再次被要求选择一个方向。如果你输入keep going,程序返回到miles(),你可以选择一个新的步行里程。

def miles():
        print "How many miles do you walk?"     
    miles_choice = raw_input("> ")
    how_much = int(miles_choice)    
    if how_much >= 10:
        right_dest()    
    elif  how_much < 10:
        turn()  
    else: 
        print "You can't just stand here..."
        miles() 

好的,这里有两个问题:

  1. 我将如何做到这一点,以便如果用户最初输入的英里数小于目标距离,并且第二英里输入 + 第一英里输入 == 到目的地的英里数,它将添加输入并运行我的目的地函数,而不仅仅是重复英里()。

  2. 由于所有三个最终目的地都有不同的距离,我应该编写三个单独的英里函数吗?有没有办法让它根据选择的原始方向,miles() 将运行不同的端点?

如果这没有一点意义,我很抱歉......我仍在学习,我不确定如何完全解释我想要表达的内容。

4

3 回答 3

0

我不完全理解要求(预期的行为和约束)。但是,您可能会考虑将参数传递给您的函数(通过和参数)以传达游戏可以朝该方向前进的最大英里数)。

例如:

#!/usr/bin/env python
# ...
def miles(max_miles=10):
    print "How many miles do you walk?"
    while True:     
        miles_choice = raw_input("> ")
        try:
            how_much = int(miles_choice)
        except ValueError, e:
            print >> sys.stderr, "That wasn't a valid entry: %s" % e
            continue

        if max_miles > how_much > 0:
            break
        else:
            print "That's either too far or makes no sense"
    return how_much

...在这种情况下,您通过“max_miles”参数将最大有效英里数传递给函数,然后返回一个有效整数(介于 1 和 max_miles 之间)。

right_dest()然后调用或turn()酌情由该函数的调用者负责。

请注意,我已经删除了您的递归调用,miles()并将其替换为while True:围绕try: ... except ValueError: ...验证循环的循环。在这种情况下,这比递归更合适。break当 how_much 的值有效时,代码会跳出循环。

(顺便说一下,如果你miles()不带参数调用,那么根据“默认参数”功能,参数将设置为 10。这对 Python(和 Ruby)来说是不寻常的......但基本上在有参数的情况下使参数可选合理的默认值)。

于 2014-04-28T07:18:37.153 回答
0

@问题#1:我使用了类实习生变量。您可能需要它们来进行进一步的编程部分,并且当您在一个方向上完成时应该将其归零,以便从零开始进行下一步/lvl。

@问题#2:字典是最好的方法,self.dest. pos用作从字典中获取值的键的参数。

class MyGame:
    def __init__(self):
        self.current_miles = 0
        self.dest = {'Left' : 10, 'Into the jungle' : 7, 'Right' : 22}

    def miles(self,pos):

        print "How many miles do you walk?"     
        miles_choice = raw_input("> ") 
        self.current_miles += int(miles_choice) 

    if self.current_miles >= self.dest.get(pos):
            self.miles("Right")    
    elif  self.current_miles < self.dest.get(pos):
        print "you went "+ str(self.current_miles) + " miles"
    else: 
        print "You can't just stand here..."
        self.miles(pos) 

mg = MyGame()
mg.miles('Into the jungle')
于 2014-04-28T07:43:54.430 回答
0

您可以将沿每个方向行走的英里数存储在字典中,然后检查字典以查看用户是否已经走得足够远:

distances = {
    'right': 7,
    'left': 17,
    'forward': 4
}

direction_choice = raw_input("> ")
miles_choice = raw_input("> ")

if how_much >= distances['direction_choice']:
    right_dest()    
elif  how_much < distances['direction_choice']:
    turn()  
else: 
    print "You can't just stand here..."
    miles()

确保正确验证和转换用户输入,我没有解决这个问题。祝你好运!

于 2014-04-28T07:08:26.313 回答