三子棋、井字棋 -python版本代码-C语言版本代码
三子棋和井字棋是两个非常经典的小游戏,以下是它们的Python版本和C语言版本的代码实现。
Python版本:
三子棋:
import numpy as np
import pprint
def initialize_board(board):
# 初始化棋盘
board = np.array(board)
return board
def print_board(board):
# 打印棋盘
pprint.pprint(board)
def is_win(board, player):
# 判断是否有玩家获胜
wins = [(0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)]
for win in wins:
if board[win[0]] == player and board[win[1]] == player and board[win[2]] == player:
return True
return False
# 示例使用
board = [' ']*9
board = initialize_board(board)
print_board(board)
# 玩家1和玩家2轮流下棋子
player = 'X'
for i in range(9):
move = input(f"Player {player}, enter move: ")
board[int(move)] = player
print_board(board)
if is_win(board, player):
print(f"Player {player} wins!")
break
player = 'O' if player == 'X' else 'X'
else:
print("Draw!")
井字棋:
import numpy as np
import pprint
def initialize_board(board):
# 初始化棋盘
board = np.array(board)
return board
def print_board(board):
# 打印棋盘
pprint.pprint(board)
def is_win(board, player):
# 判断是否有玩家获胜
wins = [(0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)]
for win in wins:
if board[win[0]] == player and board[win[1]] == player and board[win[2]] == player:
return True
return False
# 示例使用
board = [' ']*9
board = initialize_board(board)
print_board(board)
# 玩家1和玩家2轮流下棋子
player = ' '
for i in range(9):
move = input(f"Player {player}, enter move: ")
board[int(move)] = 'X' if player == ' ' else 'O'
player = ' ' if player != ' ' else 'X'
print_board(board)
if is_win(board, 'X' if player == ' ' else 'O'):
print(f"Player {'X' if player == ' ' else 'O'} wins!")
break
else:
print("Draw!")
C语言版本:
三子棋:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BOARD_SIZE 3
#define PLAYER_X 'X'
#define PLAYE
评论已关闭