首页 > 解决方案 > Python - 如何根据用户输入更改字典中的值?(“关上盒子”游戏)

问题描述

使用一些 Python 基础知识在我的第一个程序上工作的极端新手。我正在尝试创建“关闭盒子”桌面游戏,玩家尝试通过掷一对骰子来消除一行数字(在本例中为 1-10),然后根据掷骰子的总和删除数字.

在我的程序中,我有一个 Board 字典(theBoard),我想根据用户输入要删除的数字来更改字典中的各种值。例如,用户掷出 5,他们输入 5(但也可以输入 2 和 3)从棋盘上删除,所以棋盘现在是 1-2-3-4-X-5-6-7-8- 9-10。

下面的当前代码,你会在最后看到我试图检查输入是否在字典中。我想检查输入是否在字典中,如果是,我想将该值更改为 X:


#setting up the Board to show which number slot we're in, which will have an integer
#until it is selected by the user to be removed from the board, then it will be 'X'

theBoard = {'one': '1', 'two':'2', 'three': '3', 'four': '4', \
            'five':'5', 'six': '6', 'seven': '7', 'eight':'8', 'nine': '9', \
            'ten': '10'}

#printing the visual of the board, starts with showing each integer 1 thru 10

def printBoard(board):
    print(board['one'] + '|' + board['two'] + '|' + board['three'] + '|' \
          + board['four'] + '|' + board['five'] + '|' + board['six'] + '|' \
          + board['seven'] + '|' + board['eight'] + '|' + board['nine'] + '|' \
          + board['ten'] + '|')


#first attempt at coding a dice roll
diceRoll = random.randint(1, 6) + random.randint(1,6)

print('Welcome! Here is your board, let\'s get started.')
printBoard(theBoard)

print('To begin, roll the pair of dice by typing \'r\'.')


rollOne = input()

#the user input triggers a dice roll
if rollOne == 'r':
    print('You rolled a ' + str(diceRoll) + '.  Now choose which \
numbers to remove from the board.')
    print('Here\'s the board again, you can type a single number, or multiple \
numbers separated by a commma to remove them from the board.')
    printBoard(theBoard)

newBoard = input()

if str(newBoard) in theBoard:
    print('yes')
else:
    print('no')```

标签: pythondictionaryinput

解决方案


推荐阅读