python - 井字游戏蟒蛇
问题描述
我是 python 新手,正在开发井字游戏。我被困在 make_move 和 next_player 函数中。每当我运行代码时,都会出现如下错误。
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
X
轮到1:选择一个正方形:1
Traceback(最近一次调用最后一次):
文件“第 268 行,在 display_board(board)
文件中”第 58 行,在 display_board board_to_show += player_name(board[i]) # 显示玩家的标记
文件“第 23 行,在 player_name 返回 PLAYER_NAMES[player_id ]
TypeError:列表索引必须是整数或切片,而不是 str
我想解决这个错误并想确保 make_move 和 next_player 工作,但我不知道该怎么做...谢谢你的帮助
# CONSTANTS
PLAYER_NAMES = ["Nobody", "X", "O"]
# FUNCTIONS
def player_name(player_id):
'''return the name of a player with a specified ID
Looks up the name in the PLAYER_NAMES global list
Parameters
----------
player_id: int
player's id, which is an index into PLAYER_NAMES
Returns
-------
string
the player's name
'''
return PLAYER_NAMES[player_id]
# for current_player in range(len(PLAYER_NAMES)):
# print(player_name(current_player))
def display_board(board):
'''display the current state of the board
board layout:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Numbers are replaced by players' names once they move.
Iterate through the board and choose the right thing
to display for each cell.
Parameters
----------
board: list
the playing board
Returns
-------
None
'''
board_to_show = "" # string that will display the board, starts empty
for i in range(len(board)):
if board[i] == 0: # 0 means unoccupied
# displayed numbers are one greater than the board index
board_to_show += str(i + 1) # display cell number
else:
board_to_show += player_name(board[i]) # display player's mark
if (i + 1) % 3 == 0: # every 3 cells, start a new row
board_to_show += "\n"
else:
board_to_show += " | " # within a row, divide the cells
print()
print(board_to_show)
def make_move(player, board):
'''allows a player to make a move in the game
displays who's move it is (X or O)
prompts the user to enter a number 1-9
validates input, repeats until valid input is entered
checks move is valid (space is unoccupied), repeats until valid move
is entered
Parameters
----------
player: int
the id of the player to move (1 = X, 2 = O)
board: list
the board upon which to move
the board is modified in place when a valid move is entered
'''
# TODO: Implement function
if player == 1:
marking = 'X'
if player == 2:
marking = 'O'
invalid_input = "sorry, please enter a valid input. You can select a number 1-9."
try:
selection = int(input("{}'s turn: Select a square: ".format(player)))-1
board[selection] = marking
# display_board(board)
except ValueError:
print(invalid_input)
except IndexError:
print(invalid_input)
def check_win_horizontal(board):
# TODO: write docstring
'''
Way to check for horizontal victories.
The player who marked 1,2,3 / 4,5,6/ 7,8,9 on board will win.
parameter
---------
board: list
'''
if (board[0] != 0 and
board[0] == board[1] and
board[0] == board[2]):
return board[0]
if (board[3] != 0 and
board[3] == board[4] and
board[3] == board[5]):
return board[3]
if (board[6] != 0 and
board[6] == board[7] and
board[6] == board[8]):
return board[6]
return 0
def check_win_vertical(board):
# TODO: write docstring
'''
Way to check for Vertical victories.
The player who marked 1,4,7 / 2,5,8/ 3,6,9 on board will win.
parameter
---------
board: list
'''
# TODO: implement function
if (board[0] != 0 and
board[0] == board[3] and
board[0] == board[6]):
return board[0]
if (board[1] != 0 and
board[1] == board[4] and
board[1] == board[7]):
return board[1]
if (board[2] != 0 and
board[2] == board[5] and
board[2] == board[8]):
return board[2]
return 0
def check_win_diagonal(board):
# TODO: write docstring
'''
Way to check for diagonal victories.
The player who marked 1,5,9 / 3,5,7 on board will win.
parameter
---------
board: list
'''
# TODO: implement function
if (board[0] != 0 and
board[0] == board[4] and
board[0] == board[8]):
return board[0]
if (board[2] != 0 and
board[2] == board[4] and
board[2] == board[6]):
return board[2]
return 0
def check_win(board):
'''checks a board to see if there's a winner
delegates to functions that check horizontally, vertically, and
diagonally to see if there is a winner. Returns the first winner
found in the case of multiple winners.
Parameters
----------
board: list
the board to check
Returns
-------
int
the player ID of the winner. 0 means no winner found.
'''
winner = check_win_horizontal(board)
if (winner != 0):
return winner
winner = check_win_vertical(board)
if (winner != 0):
return winner
return check_win_diagonal(board)
def next_player(current_player):
'''determines who goes next
given the current player ID, returns the player who should
go next
Parameters
----------
current_player: int
the id of the player who's turn it is now
Returns
-------
int
the id of the player to go next
'''
# TODO: Implement function
# if player_turn == 'O':
# marking = "O"
return 2
# MAIN PROGRAM (INDENT LEVEL 0)
# GLOBAL VARIABLES
board = [0, 0, 0, # top row: indices 0, 1, 2
0, 0, 0, # middle row: indices 3, 4, 5
0, 0, 0] # bottom row: indices 6, 7, 8
player = 1 # X goes first
moves_left = 9 # number of moves so far
winner = 0 # "Nobody" is winning to start
while(moves_left > 0 and winner == 0):
display_board(board)
make_move(player, board)
winner = check_win(board)
player = next_player(player)
moves_left -= 1
解决方案
根据您的错误和代码,您在棋盘中分配了玩家的标记(X 或 O),而不是它所在位置的索引PLAYER_NAMES
。这意味着board[i]
访问字符串的位置而不是引用索引的整数(因此您的错误)。
要修复它,请更改board_to_show += player_name(board[i])
为board_to_show += player_name(PLAYER_NAMES.index(board[i]))
.
推荐阅读
- r - 向 data.frame 添加一行,每列具有条件均值
- flutter - 未定义的名称“上下文”(在 Flutter 导航中)
- python - 在 Dash python 中移动到另一个页面时页面内容被重置
- ggplot2 - 在 Shiny 中绘制两个数据框中的列
- flutter - 应用打开后如何使颤振要求用户添加受华为保护的应用
- rest - 如何通过 Camunda Rest-Api 获取表单字段值
- r - R闪亮和dplyr:如果为过滤器提供输入值,则在应用过滤器时从数据库中查询数据
- javascript -
在 App.js 中给出此错误:元素类型无效 - sql - SQL Select - Union 结合 Join 查询导致错误
- javascript - 在 ondrop 事件中调用 focus() 时如何使光标闪烁?