使用Python的Dungeon&Dragon游戏中的问题

时间:2018-12-28 13:53:47

标签: python while-loop

我刚刚写了这个地牢和龙的迷你游戏,还没有完成,我还没有写过Dragon功能或当用户碰墙时显示错误的功能。我只想将播放器“ X”移动我想要多少次,但我不能。 这是代码:

import random
import os

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

dungeon = [(0,0),(0,1),(0,2),(0,3),(0,4),
        (1,0),(1,1),(1,2),(1,3),(1,4),
        (2,0),(2,1),(2,2),(2,3),(2,4),
        (3,0),(3,1),(3,2),(3,3),(3,4),
        (4,0),(4,1),(4,2),(4,3),(4,4)
        ]

def first_random_position():
    return(random.choice(dungeon))

def make_dungeon(player_position):
    print(" _ _ _ _ _")
    for cell in dungeon:
        y = cell[1]
        if y < 4:
            if cell == player_position:
                print("|X", end = "")
            else:
                print("|_", end = "")
        elif cell == player_position:
            print("|X|")
        else:
            print("|_|")

def move_player(position,m_input):
    x,y = position
    if m_input.upper() == "UP":
        x -= 1
    elif m_input.upper() == "LEFT":
        y -= 1
    elif m_input.upper() == "RIGHT":
        y += 1
    elif m_input.upper() == "DOWN":
        x += 1
    position = x,y
    return(x,y)

def main():
    print("Welcome to the Dungeon!")
    input("Press 'Enter' on your keyboard to start the game!")
    first_pos = first_random_position()
    make_dungeon(first_pos)
    print("You are currently in room {}".format(first_pos))
    print("Enter LEFT , RIGHT , UP and DOWN to move the 'X'")
    print("Enter 'QUIT' to quit")
    main_input = input("\n")
    location = move_player(first_pos,main_input)
    clear_screen()
    make_dungeon(location)

main()

如您所见,我只能将X移动一次,但是我希望能够将其移动任意次,而且我不知道该怎么做,我应该编写一个while循环吗?我曾尝试过,但失败了,我真的需要您的帮助。谢谢

1 个答案:

答案 0 :(得分:1)

运行这些行时:

Serializer.new(Model.first).to_json

它仅要求用户输入一次,因为Patrick Artner评论您需要在脚本中使用loops。 如果您用main_input = input("\n") location = move_player(first_pos,main_input) clear_screen() make_dungeon(location) 包围该脚本,则应该继续移动:

while True:

您应该使用def main(): print("Welcome to the Dungeon!") input("Press 'Enter' on your keyboard to start the game!") location = first_random_position() make_dungeon(location) print("You are currently in room {}".format(location)) while True: print("Enter LEFT , RIGHT , UP and DOWN to move the 'X'") print("Enter 'QUIT' to quit") main_input = input("\n") location = move_player(location,main_input) clear_screen() make_dungeon(location) 而不是location,因为它会随着上一个动作而更新。


尽管这与问题无关,但我认为这些更改将对您的代码将来有所帮助。首先,我建议添加first_pos作为退出游戏的临时方法。其次,与其写出地牢变量,不如使用列表理解来创建elif m_input.upper() == "QUIT": exit()


完整更新的代码

dungeon = [(x,y) for x in range(5) for y in range(5)]

希望这会有所帮助。


以下是表格的简单说明,供以后参考:

Simple Explanation