2

我正在用 Python 制作一个基本的文本冒险 RPG 游戏。我的问题是移动系统,其中地牢被分成正方形,每个正方形都有一个坐标。向玩家询问移动位置的坐标,然后将其传递给函数 move2,然后程序检查一堆 if 语句,类似于下面的语句,并打印相应的楼层地图。每个坐标都有一个 if 语句,因此有 40 种不同的 if 语句,每个都有地图的图像。问题是在要求玩家提供坐标后什么都没有发生。程序在询问坐标后结束,但没有给出任何错误(我知道我输入了正确的坐标。)

move = input("\n To move around the room Hero, simply think the coordinates of the tile        you want to move to! However, you can only move one tile at a time Ex: You are at tile 5,4. You can move to 5,3 5,5 or 4,4")
move2(move)

我为糟糕的代码道歉。我敢肯定有更好的方法可以做到这一点,但我还没有知道...

def move2 (move):      
    while move == "5,1" "5,2" "5,3" "5,4" "5,5" "5,6" "5,7" "5,8" "4,1" "4,2" "4,3" "4,4" "4,5" "4,6" "4,7" "4,8" "3,1" "3,2" "3,3" "3,4" "3,5" "3,6" "3,7" "3,8" "2,1" "2,2" "2,3" "2,4" "2,5" "2,6" "2,7" "2,8" "1,1" "1,2" "1,3" "1,4" "1,5" "1,6" "1,7" "1,8":
        if move == "5,3":
            move = input("""
       1  2  3  4  5  6  7  8                
       __ __ __ D_ __ __ __ __                 
    1 |_ |_ |_ |_ |_ |_ |_ |_C|                      
    2 |_ |_ |_ |_ |_ |_ |_ |_ |                             
    3 |_ |?_|_ |_ |_ |_ |_ |_ |                            
    4 |_ |_ |_ |_ |_ |_ |_ |_ |                              
    5 |_ |_ |_x|_ |_ |_ |_ |_ |                              
                D""")    
4

3 回答 3

5

这会有所帮助,但你真的应该阅读一个教程:

while move in ("5,1", "5,2", "5,3", "5,4", ... etc):
    # body
于 2013-06-25T20:37:47.803 回答
1

As others have pointed out,

while move == "5,1" "5,2" "5,3" "5,4" "5,5" "5,6" "5,7" "5,8" "4,1" "4,2" "4,3" "4,4" "4,5" "4,6" "4,7" "4,8" "3,1" "3,2" "3,3" "3,4" "3,5" "3,6" "3,7" "3,8" "2,1" "2,2" "2,3" "2,4" "2,5" "2,6" "2,7" "2,8" "1,1" "1,2" "1,3" "1,4" "1,5" "1,6" "1,7" "1,8":

concatenates (smashes together) all the strings. What you want instead is:

while move in ("5,1", "5,2", "5,3", "5,4", "5,5", "5,6", "5,7", "5,8", "4,1", "4,2", "4,3", "4,4", "4,5", "4,6", "4,7", "4,8", "3,1", "3,2", "3,3", "3,4", "3,5", "3,6", "3,7", "3,8", "2,1", "2,2", "2,3", "2,4", "2,5", "2,6", "2,7", "2,8", "1,1", "1,2", "1,3", "1,4", "1,5", "1,6", "1,7", "1,8"):

but that's not so great either. Instead I'd use better string-matching:

import re
while re.match(r'\d,\d', move):
于 2013-06-25T20:42:41.327 回答
0

For good coding practices, you should move any long declaration into a separate part of your code. Some simple re-factoring:

allowed_moves =["5,1", "5,2", "5,3", "5,4",...]
while move in allowed_moves:
    etc...

Also, if you're looking for a good resource to learn Python, which will help you with this as well as countless other thing sin your programming career I suggest the following book:

http://www.greenteapress.com/thinkpython/

Free online, and written by a professor of mine.

于 2013-06-25T20:40:54.540 回答