用python写一个代码一字棋游戏
时间: 2024-11-05 07:25:02 浏览: 15
编写一个简单的Python字典棋游戏可以帮助我们理解基本的用户输入处理、规则逻辑以及游戏循环。以下是一个简易版的五子棋游戏示例:
```python
import random
# 定义棋盘大小
board_size = 9
# 初始化空棋盘
chess_board = [[' ' for _ in range(board_size)] for _ in range(board_size)]
def print_board():
print('-------------')
for row in chess_board:
print('|', ' '.join(row), '|')
print('-------------')
def check_win(player):
# 检查行、列和对角线是否有连续五个同色格子
directions = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for direction in directions:
count = 1
for i in range(board_size):
if chess_board[i][direction[0] * i + direction[1]] == player:
count += 1
if count >= 5:
return True
else:
count = 1
return False
def make_move():
while True:
try:
x = int(input("请输入横坐标(1-%d):" % board_size))
y = int(input("请输入纵坐标(1-%d):" % board_size))
if chess_board[x-1][y-1] == ' ':
chess_board[x-1][y-1] = 'X' if current_player == 'O' else 'O'
break
else:
print("该位置已被占据,请重新选择!")
except ValueError:
print("无效输入,请输入数字!")
current_player = 'X'
while True:
print_board()
if check_win(current_player):
print(f"玩家{current_player}获胜!")
break
make_move()
if current_player == 'X':
current_player = 'O'
else:
current_player = 'X'
阅读全文