请编写一个Python的五子棋小游戏
时间: 2024-09-13 19:15:52 浏览: 44
创建一个基本的五子棋游戏需要实现棋盘的显示、玩家的交替下棋、判断胜负等功能。下面是一个简单的五子棋Python程序示例:
```python
# 五子棋游戏
BOARD_SIZE = 15
EMPTY_MARK = '-'
PLAYER_X = 'X'
PLAYER_O = 'O'
def print_board(board):
for row in board:
print(' '.join(row))
def is_valid_move(board, row, col):
return 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE and board[row][col] == EMPTY_MARK
def make_move(board, row, col, player):
board[row][col] = player
def is_winner(board, player):
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE):
if board[row][col] == player:
for direction in directions:
win = True
for n in range(1, 5):
r = row + direction[0] * n
c = col + direction[1] * n
if r < 0 or r >= BOARD_SIZE or c < 0 or c >= BOARD_SIZE or board[r][c] != player:
win = False
break
if win:
return True
return False
def play_game():
board = [[EMPTY_MARK] * BOARD_SIZE for _ in range(BOARD_SIZE)]
current_player = PLAYER_X
move_count = 0
while True:
print_board(board)
print(f"Player {current_player}'s turn.")
row = int(input('Enter row: '))
col = int(input('Enter column: '))
if is_valid_move(board, row, col):
make_move(board, row, col, current_player)
move_count += 1
if is_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
if move_count == BOARD_SIZE * BOARD_SIZE:
print("It's a tie!")
break
current_player = PLAYER_O if current_player == PLAYER_X else PLAYER_X
else:
print("Invalid move. Try again.")
if __name__ == "__main__":
play_game()
```
这段代码实现了一个文本界面的五子棋游戏,玩家通过输入行和列的坐标来下棋。游戏会检查每次落子后是否有玩家获胜。如果棋盘填满且没有玩家获胜,则判定为平局。
阅读全文