用Python写一个井字棋程序
时间: 2023-11-30 12:04:55 浏览: 73
以下是一个简单的井字棋程序的Python代码:
```python
def display_board(board):
print(board[0] + '|' + board[1] + '|' + board[2])
print('-+-+-')
print(board[3] + '|' + board[4] + '|' + board[5])
print('-+-+-')
print(board[6] + '|' + board[7] + '|' + board[8])
def check_winner(board):
if board[0] == board[1] == board[2] != ' ':
return True
elif board[3] == board[4] == board[5] != ' ':
return True
elif board[6] == board[7] == board[8] != ' ':
return True
elif board[0] == board[3] == board[6] != ' ':
return True
elif board[1] == board[4] == board[7] != ' ':
return True
elif board[2] == board[5] == board[8] != ' ':
return True
elif board[0] == board[4] == board[8] != ' ':
return True
elif board[2] == board[4] == board[6] != ' ':
return True
else:
return False
def main():
board = [' '] * 9
player = 'X'
while True:
display_board(board)
move = int(input('Player ' + player + ', enter your move (0-8): '))
if board[move] != ' ':
print('Invalid move. Try again.')
continue
board[move] = player
if check_winner(board):
display_board(board)
print('Player ' + player + ' wins!')
break
if ' ' not in board:
display_board(board)
print('It is a tie!')
break
player = 'O' if player == 'X' else 'X'
if __name__ == '__main__':
main()
```
程序使用一个列表来表示井字棋的棋盘,其中每个元素代表一个格子,初始时都是空格。程序通过循环来交替让两个玩家下棋,每次下棋后检查是否有玩家获胜或平局。如果有获胜者,程序输出获胜者的信息并结束游戏;如果是平局,程序输出平局信息并结束游戏。如果没有获胜者或平局,则继续下一轮。
阅读全文