简体   繁体   English

开启python文字冒险之旅

[英]Turn counter for python text adventure

I have written a python text adventure game and the final thing I want to add is a counter to count the amount of turns taken that will be displayed at the end of the game. 我已经编写了一个python文字冒险游戏,我要添加的最后一件事是一个计数器,用于计算将在游戏结束时显示的转弯次数。

It only needs to count every time the player inputs something but Im not sure how to code this and its a bit embarrassing as im sure this will be a very simple solution 每次玩家输入东西时都只需要计数,但是我不确定如何编写代码,这有点尴尬,因为我肯定这将是一个非常简单的解决方案

im using python 3.4.1 我正在使用python 3.4.1

while True:
    playerInput = input("What do you want to do? ")
    playerInput = playerInput.lower()
    playerWords = playerInput.split(" ", 1)
    verb = playerWords[0]
    if len(playerWords) == 2:
        noun = playerWords[1]
    else:
        noun = ""


    if playerInput == "quit":
        break



    elif playerInput == "look":
        print(roomDescriptions[currentRoom])



    ##--Controls movement--##             
    elif playerInput in dirs:
        playerInput = playerInput[0]
        if "treasure" in invItems and playerInput == "s" and currentRoom == "strangeWall":##--Checks for treasure in inventory before allowing game to be won--##
            print("!!!!Congratulations you have escaped from the dark dungeon!!!!")
            break

        elif playerInput in roomDirections[currentRoom]:
            currentRoom = roomDirections[currentRoom][playerInput]
            print(roomEntrance [currentRoom])
        else:
            print("You can't go that way")



    elif playerInput == "lookdown":##--checks for room items on the ground--##
        printList ("You see;", roomItems[currentRoom])



    elif playerInput == "inventory" or playerInput == "inv":##--Displays inventory items--##
        printList ("You are carrying;", invItems)



    elif verb == "get":##--Controls picking up items and adding them to inventory/removes from room--##
        if noun in roomItems[currentRoom]:
            print("picked up", noun)
            invItems.append(noun)
            roomItems[currentRoom].remove(noun)
        else:
            print("There is nothing to pick up")



    elif verb == "drop":##--Controls dropping items and removing them from the inventory/adds to room items--##
        if noun in invItems:
            print("You drop the", noun)
            roomItems[currentRoom].append(noun)
            invItems.remove(noun)
        else:
            print("You are not carrying", noun)


    elif verb == "use":##--Controls using the lamp and snow boots--##
        if noun in invItems:##--Checks inventory for lamp or snowboots before allowing certain directional movement--##
            if noun == "lamp":
                print("You light the lamp")
                invItems.remove(noun)
                roomDirections["hallMid"]["e"] = "giantNature"

            elif noun == "snowboots":
                print("You put on the snowboots")
                invItems.remove(noun)
                roomDirections["hallMid"]["s"] = "snowRoom"
            else:
                print("You cannot use that")
        else:
            print("You do not have", noun)





    else:
        print ("I don't understand")

Without seeing an example of your code, it's pretty much impossible to tell you anything specific that will work in your code. 没有看到您的代码示例,几乎不可能告诉您任何可以在您的代码中使用的特定内容。

But I can give you something general that you can probably adapt to fit your code. 但是我可以给您一些一般性的信息,使您可以适应您的代码。

class CountedInput(object):
    def __init__(self):
        self.counter = 0
    def input(self, *args):
        self.counter += 1
        return input(*args)

counted_input = CountedInput()

Now, anywhere in your code that you call input() , you instead call counted_input.input() . 现在,在代码中调用input()任何地方,都改为调用counted_input.input()

And when you want to display the turn counter, that's just counted_input.counter . 当您要显示转弯计数器时,这只是counted_input.counter

(If you're using Python 2.x, change input to raw_input .) (如果您使用的是Python 2.x,请将input更改为raw_input 。)


Now that you've added an example to the question: 现在,您已经向问题添加了一个示例:

This suggestion will work just fine as it is, but you can make things even simpler. 这个建议可以正常使用,但是您可以使事情变得更简单。

Your whole game is built around a command loop. 您的整个游戏都是围绕命令循环构建的。 You call input exactly once per loop. 您每个循环仅调用一次input So, all you need to do is count how many times you go around that loop. 因此,您所需要做的就是计算循环次数。 You can do that like this: 您可以这样做:

counter = 0
while True:
    counter += 1
    playerInput = input("What do you want to do? ")
    # all the rest of your code

And now, you just print out or otherwise use counter the same as any other variable. 现在,您只需打印输出或以其他方式使用counter For example: 例如:

    elif playerInput == "score":
        print("You have 0/0 points after", counter, "turns")

(I'm guessing that you don't actually want to troll your players with a score command when you don't keep score, but that should show you the ideal.) (我猜想,当您不保持得分时,您实际上并不想使用score命令来吸引玩家,但这应该显示出理想的状态。)


If you want to get clever, there's an even simpler way to do this: Just loop over all the numbers from 1 to infinity. 如果您想变得聪明一点,可以采用一种更简单的方法:将所有数字从1循环到无穷。 How? 怎么样? The count function, which works kind of like range except there's no stop value because it never stops: count函数的作用类似于range但没有stop值,因为它永远不会停止:

from itertools import count

for counter in count(1):
    # the rest of your code

I know many would probably not like this idea, as I have seen conflicting views on global variable use, however I would use a global variable for turn count storage and a global function to track it. 我知道许多人可能不喜欢这个想法,因为我已经看到了有关全局变量使用的不同观点,但是我将使用全局变量来存储转数计数并使用全局函数来跟踪它。

For example: 例如:

global turn_counter
turn_counter = 0

Then, when an action is taken, you could do: 然后,当采取措施时,您可以执行以下操作:

turn_counter += 1

I believe you need to have include the global in your function, however. 我相信您需要在函数中包含全局变量。

Example: 例:

def game_input_handler():
    """ handles all user input """
    global turn_counter

    // game prompt code here
    // if..elif...else for option handling

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

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