用C语言实现一个简易的三子棋,九宫格
1.game.h
#ifndef _GAME_H_ #define _GAME_H_ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <Windows.h> #pragma warning(disable:4996) #define COL 3 #define ROW 3 void game(); #endif // !_GAME_H_
2.game.c
#include "game.h" static void display(char board[][COL], int row) { int i = 0; for (; i < row; i++) { printf(" %c | %c | %c |\n",\ board[i][0], board[i][1], board[i][2] ); if (i < row - 1) { printf("---|---|---\n"); } } } static void playerMove(char board[][COL], int row) { int x, y; do { printf("请输入 <x,y>:"); scanf("%d %d", &x, &y); if (x >= 1 && x <= 3 && y >= 1 && y <= 3) { if (board[x - 1][y - 1] == ' ') { board[x - 1][y - 1] = 'x'; break; } else { printf("此处已被占用!请重新输入:\n"); } } else { printf("输入错误!请重试!\n"); } } while (1); } static void computerMove(char board[][COL], int row) { srand((unsigned long)time(NULL)); do { int x = rand() % row; int y = rand() % COL; if (board[x][y] == ' ') { board[x][y] = 'o'; break; } } while (1); } static int isFull(char board[][COL], int row) { int i = 0; for (; i < row; i++) { int j = 0; for (; j < COL; j++) { if (board[i][j] == ' ') { return 0; } } } return 1; } static int isWin(char board[][COL], int row) { int i = 0; for (; i < row; i++) { if (board[i][0] == board[i][1] && \ board[i][1] == board[i][2] && board[i][0] != ' ') { return board[i][0]; } } for (i = 0; i < COL; i++) { if (board[0][i] == board[1][i] && \ board[1][i] == board[2][i] && board[0][i] != ' ') { return board[0][i]; } } if (board[0][0] == board[1][1] && \ board[1][1] == board[2][2] && board[0][0] != ' ') { return board[0][0]; } if (board[0][2] == board[1][1] && \ board[1][1] == board[2][0] && board[0][2] != ' ') { return board[0][2]; } if (isFull(board, row)) { return 'q'; } return ' '; } void game() { char board[ROW][COL]; memset(board, ' ', ROW * COL); char ret; do { system("CLS"); display(board, ROW); playerMove(board, ROW); ret = isWin(board, ROW);//x->plaer, o->computer, q->eq, ' 'no one win if (ret != ' ') { break; } computerMove(board, ROW); ret = isWin(board, ROW); } while (ret = ' '); if (ret == 'x') { printf("You Win!\n"); } else if (ret == 'o') { printf("You Lose!\n"); } else if (ret == 'q') { printf("平局!\n"); } else { printf("Debug!\n"); } }
3.main.c
#include "game.h" void menu() { printf("##############################\n"); printf("### 1. play 2. exit###\n"); printf("##############################\n"); printf("Plaes Select: "); } int main() { int select = 0; do { menu(); scanf("%d", &select); switch (select) { case 1: game(); break; case 2: exit(0); default: break; } } while (1); system("pause"); return 0; }