1.打印棋盘
采用二维数组打印元素,先初始化棋盘中元素为' '(空格字符),在打印棋盘元素的同时加上边框
2.玩家落子9(棋子用字符‘x’表示)
3.电脑落子(棋子用字符‘o’表示)
用rand函数设置随机数(再用rand前设置随机种子),作为电脑的落子位置
4判定胜负
判断横行,纵行,对角线的元素是否相等
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define max_row 3
#define max_line 3
//三子棋游戏
void init_board(char board[max_row][max_line]){ //初始化棋盘为' '
for (int row = 0; row < max_row; row++){
for (int line = 0; line < max_line; line++){
board[row][line] = ' ';
}
}
srand((unsigned int)time(0));//在程序开始处设置随机种子
}
//1打印棋盘
void print_checkboard(char board[max_row][max_line]){
system("cls");//每次打印之前先清屏
for (int row=0; row <max_row; row++){
printf("+--+--+--+\n"); //在打印每一行元素之前打印棋盘的横向边框
for (int line = 0; line <max_line; line++){
printf("|%c ", board[row][line]);//在打印每一行的每一个元素之前先打印'|'
}
printf("|\n");//在打印每一行的最后一个元素之后先打印'|'
}
printf("+--+--+--+\n");//在打印完所有元素之后打印棋盘的底边框
}
void player_move(char board[max_row][max_line]){
printf("请玩家落子!\n");
printf("请玩家输入落子位置row line:");
while (1){
int row = 0;
int line = 0;
scanf("%d %d", &row,&line);//防止玩家输入的数字超出范围
if (row<0 || row >= max_row || line<0 || line >= max_line){
printf("请重新输入坐标!\n");
continue;
}
if (board[row][line] != ' '){ //已经有子的地方就不能落子
printf("此处有子\n");
continue;
}
board[row][line] = 'x';//玩家落'x'的子
print_checkboard(board);
break;
}
}
void computer_move(char board[max_row][max_line]){
printf("轮到电脑落子\n");
while (1){
int row = rand() % max_row;
int line = rand() % max_line;
if (board[row][line] == ' '){ //判断此处是否有子
board[row][line] = 'o';
print_checkboard(board);
break;
}
}
}
char winer(char board[max_row][max_line]){
for (int row = 0; row < max_row; row++){ //判断每一行上的棋子(字符)是否相等
if (board[row][0] == board[row][1] //若相等,返回对应的元素
&& board[row][0] == board[row][2]
&& board[row][1] == board[row][2]){
return board[row][0];
}
}
for (int line = 0; line < max_line; line++){ //判断每一列上的棋子(字符)是否相等
if (board[0][line] == board[1][line] //若相等,返回对应的元素
&& board[0][line] == board[2][line]
&& &board[1][line] == board[2][line]){
return board[0][line];
}
}
if (board[0][0] == board[1][1] //判断两条对角线上的棋子(字符)是否相等
&& board[0][0] == board[2][2] //若相等,返回对应的元素
&& board[1][1] == board[2][2]){
return board[0][0];
}
if (board[0][2] == board[1][1]
&& board[0][2] == board[2][0]
&& board[1][1] == board[2][0]){
return board[1][2];
}
for (int row = 0; row < max_row; row++){ //判断是否和棋(棋盘已满,但未分出胜负)
for (int line = 0; line < max_line; line++){
if (board[row][line] != ' '){
return ' ';
}
}
}
}
int main(){
char board[max_row][max_line] = { 0 };
//初始化棋盘
init_board(board);
while (1){
print_checkboard(board);//打印棋盘
player_move(board);//玩家落子
computer_move(board);//电脑落子
if (winer(board) == 'x'){ //判定胜负
printf("玩家获胜!\n");
}
if (winer(board) == 'o'){
printf("电脑获胜!\n");
}
if (winer(board) == ' '){
printf("和棋!");
}
system("pause");
}
system("pause");
return 0;
}