简体   繁体   English

Python初学者,基于文本的游戏

[英]Python beginner, text-based game

I'm fairly new to the programming game; 我是编程游戏的新手。 I'm 3/4 of the way through Learn Python the Hard Way and I had a question about a little text-based game I made... So in this game my guy is stranded on a desert island and you have the option(raw input) of going left right or into the jungle . 我在“ Learn Python the Hard Way占了3/4,我对我制作的一款基于文本的小游戏有疑问...所以在这个游戏中,我的guy被困在荒岛上,您可以选择(原始输入)是left right还是into the jungle After choosing a direction, you're given the option to choose how many miles to walk. 选择方向后,您可以选择步行多少英里。 Each direction is supposed to have a different end result (and mile distance). 每个方向的最终结果(和英里距离)应该有所不同。

If you enter a number that is less than the number of miles to the destination, you're prompted with a choice to either "turn around or "keep going". If you enter turn around , you're taken back to the beginning, where you're again asked to choose a direction. If you enter keep going , the program returns to miles(), where you can choose a new amount of miles to walk. 如果输入的数字小于到目的地的英里数,则系统会提示您选择“转身”或“继续前进”。如果输入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() 

Ok so here's two questions: 好的,这是两个问题:

  1. How would I make it so that if the user originally enters a number of miles less than the destination distance, and the second mile input + the first mile input == the amount of miles to the destination, it will add the inputs and run my destination function, not just repeat miles(). 如果用户最初输入的距离小于目标距离,而第二英里输入量+第一英里输入量==到目的地的距离量,我将如何做,它将添加输入并运行我的目标函数,而不仅仅是重复Miles()。

  2. Since all three final destinations will have different distances, should I write three separate mile functions? 由于所有三个最终目的地的距离都不同,我是否应该编写三个单独的英里功能? Is there a way to make it so that depending on the original direction chosen, miles() will run the different endpoints? 有没有一种方法可以使它根据选定的原始方向,在不同的端点上运行miles()?

I'm sorry if this doesn't make a lick of sense... I'm still learning and I'm not sure how to fully explain what I'm trying to get across. 很抱歉,如果这没有说服力的话……我仍在学习,而且不确定如何全面解释我要传达的内容。

You could store the amount of miles to walk in each direction in a dict, and then check the dict to see if the user has walked far enough: 您可以存储要在字典中沿每个方向行走的英里数,然后检查该字典以查看用户是否走了足够远:

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()

Be sure to properly validate and cast the user input, which I have not addressed. 请确保正确验证并投放用户输入(我尚未解决)。 Good luck! 祝好运!

I don't fully understand the requirements (the intended behavior and constraints). 我不完全了解需求(预期的行为和约束)。 However, you might consider passing a parameter to your function (through and argument) to convey the maximum number of miles which the play could go in that direction). 但是,您可以考虑将参数传递给函数(通过和参数),以传达该方向可能达到的最大英里数。

For example: 例如:

#!/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

... in this case you pass maximum valid number of miles into the function through the "max_miles" argument and you return a valid integer (between 1 and max_miles) back. ...在这种情况下,您通过“ max_miles”参数将最大有效英里数传递给函数,然后返回有效整数(1到max_miles之间)。

It would be the responsibility of this function's caller to then call right_dest() or turn() as appropriate. 然后,适当时调用right_dest()turn()是此函数的调用者的责任。

Note that I've removed your recursive call to miles() and replace it with a while True: loop, around a try: ... except ValueError: ... validation loop. 请注意,我已经删除了对Miles miles()递归调用,并用while True:循环替换了它, while True: try: ... except ValueError: ...验证循环try: ... except ValueError: ... That's more appropriate than recursion in this case. 在这种情况下,这比递归更合适。 The code does a break out of the loop when the value of how_much is valid. 该代码做一个break圈外时how_much的值是否有效。

(By the way, if you call miles() with no parameter then the argument will be set to 10 as per the "defaulted argument" feature. That's unusual to Python (and Ruby) ... but basically makes the argument optional for cases where there's a sensible default value). (顺便说一句,如果您不带任何参数调用miles() ,那么根据“默认参数”功能,该参数将被设置为10。这在Python(和Ruby)中是不常见的...但是基本上使该参数对于某些情况是可选的有合理的默认值)。

@Question #1: I used Class intern variables. @问题#1:我使用了Class内部变量。 You will maybe need them for further programming parts and should take it to zero when you are done on one direction, to start with zero for next step/lvl. 您可能需要它们来进行进一步的编程,并在一个方向上完成后将其设置为零,以便从零开始进行下一步/ lvl。

@Question #2: Dictionaries are the best way to do so, self.dest . @Question#2:字典是这样做的,最好的办法self.dest Parameter pos used as key to get the value from the dictionary. 参数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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM