同五子棋,三子棋即在九宫格里能实现三个棋子连在一起即获胜
//未修改写法,实现了功能但是繁琐不美观且有很多不健全的地方 #include<stdio.h> #include<stdlib.h> void init(int arr[][3])//初始化数组 { int i = 0; for (i = 0; i < 3; i++) { printf(" %c | %c | %c ", arr[i][0], arr[i][1], arr[i][2]); if (i != 2) printf("\n---|---|---\n");//按照此格式打印出九宫格 } } void print_meue(int game)//游戏菜单 { printf(" 三子棋 \n"); printf("**********1>start************\n"); printf("**********2>exit ************\n"); printf("*****************************\n"); } void player(int arr[][3])// 玩家 { int a = 0, b = 0; int i = 0; int flag; flag: printf("\nyour turn:\n"); scanf("%d%d", &a, &b); if (arr[a - 1][b - 1] == ‘ ‘) { arr[a-1][b-1] = ‘O‘; for (i = 0; i < 3; i++) { printf(" %c | %c | %c ", arr[i][0], arr[i][1], arr[i][2]); if (i != 2) printf("\n---|---|---\n"); } printf("\n"); } else goto flag; } void computer(int arr[][3])//电脑 { int i = 0, j = 0; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (arr[i][j] == ‘ ‘) { arr[i][j] = ‘X‘; for (i = 0; i < 3; i++) { printf(" %c | %c | %c ", arr[i][0], arr[i][1], arr[i][2]); if (i != 2) printf("\n---|---|---\n"); } break; } } } } void jud_win( int arr[][3])//判断输赢 { if ((arr[0][0] == ‘O‘ && arr[0][1] == ‘O‘ && arr[0][2] == ‘O‘) || (arr[1][0] == ‘O‘ && arr[1][1] == ‘O‘ && arr[1][2] == ‘O‘) || (arr[2][0] == ‘O‘ && arr[2][1] == ‘O‘ && arr[2][1] == ‘O‘) || (arr[0][0] == ‘O‘ && arr[1][0] == ‘O‘ && arr[2][0] == ‘O‘) || (arr[0][1] == ‘O‘ && arr[1][1] == ‘O‘ && arr[2][1] == ‘O‘) || (arr[0][2] == ‘O‘ && arr[1][2] == ‘O‘ && arr[2][2] == ‘O‘) || (arr[0][0] == ‘O‘ && arr[1][1] == ‘O‘ && arr[2][2] == ‘O‘) || (arr[0][2] == ‘O‘ && arr[1][1] == ‘O‘ && arr[2][0] == ‘O‘)) { printf("you win!\n"); } if ((arr[0][0] == ‘X‘ && arr[0][1] == ‘X‘ && arr[0][2] == ‘X‘) || (arr[1][0] == ‘X‘ && arr[1][1] == ‘X‘ && arr[1][2] == ‘X‘) || (arr[2][0] == ‘X‘ && arr[2][1] == ‘X‘ && arr[2][1] == ‘X‘) || (arr[0][0] == ‘X‘ && arr[1][0] == ‘X‘ && arr[2][0] == ‘X‘) || (arr[0][1] == ‘X‘ && arr[1][1] == ‘X‘ && arr[2][1] == ‘X‘) || (arr[0][2] == ‘X‘ && arr[1][2] == ‘X‘ && arr[2][2] == ‘X‘) || (arr[0][0] == ‘X‘ && arr[1][1] == ‘X‘ && arr[2][2] == ‘X‘) || (arr[0][2] == ‘X‘ && arr[1][1] == ‘X‘ && arr[2][0] == ‘X‘)) { printf("you lose"); } } int main()//主函数 { int game=0; print_meue(game);//调用菜单函数 printf("请选择:"); scanf("%d", &game); switch (game) { case 1: { int arr[3][3] = { 0 }; int step = 0; int i = 0, j = 0; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { arr[i][j] = ‘ ‘; } } init(arr);//调用初始化函数 while (step < 10) { player(arr); step++; jud_win(arr); computer(arr); step++; jud_win(arr); } if (step >= 10) { printf(" 平局"); } } case 2: exit(0); } system("pause"); return 0; }
2.修改后健全三子棋程序
时间: 2024-10-16 19:45:10