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 ROW 3 #define COL 3 void game(); #endif
2.main.c:
#include "game.h" void menu() { printf("#####################\n"); printf("##1.play 2.exit##\n"); printf("#####################\n"); printf("Please Select:"); } int main() { int select; do{ menu(); scanf("%d", &select); switch (select){ case 1: game(); break; case 2: exit(0); default: break; } } while (1); system("pause"); return 0; }
3.game.c:
#include "game.h" static void displayBoard(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("Please enter your<x,y>:\n "); 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("This place is taken,try agin\n"); } } else{ printf("Error,try agin!\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 char isWin(char board[][COL], int row) //判断谁是赢家 { int i = 0; for (i =0; 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"); displayBoard(board, ROW); playerMove(board, ROW); //x->player,o->computer,q->eq,noone win ret = isWin(board, ROW); if (ret !=' '){ break; } computerMove(board, ROW); ret = isWin(board, ROW); } while (ret == ' '); if (ret == 'q'){ printf("We are all winers\n"); } else if (ret == 'x'){ printf("Conggratulations to you!\n"); } else if (ret == 'o'){ printf("Oh,you are a loser\n"); } else{ printf("debug!\n"); } }