时间:2021-08-06 09:05:58 | 栏目:C代码 | 点击:次
本文实例为大家分享了C语言扫雷游戏的实现代码,供大家参考,具体内容如下
1、创建俩12*12的字符数组,一个用作放雷,一个呈现给用户
2、利用随机数往防雷数组中产生雷
3、设计呈现给用户的数组
4、利用输入坐标判断――如果有雷,游戏结束并呈现放雷数组;如果无雷,计算周围一圈雷的数量并显示
头文件
#define _CRT_SECURE_NO_WARNINGS #pragma once #include<stdio.h> #include<windows.h> #include<time.h> #include<string.h> #define ROW 12 #define COL 12 #define NUM 20//放二十个雷 #define UnArea '\v' extern void GameMine();
text代码
#include"mine.h" static void Menu() { printf("===========================\n"); printf("-------1、开始扫雷---------\n"); printf("-------0、退出 ---------\n"); printf("===========================\n"); } int main() { int quit = 1; int num = 0; while (quit) { Menu(); printf("Please input......\n"); scanf("%d", &num); switch (num) { case 1: GameMine(); break; case 0: quit = 0; break; default: printf("\aPlease input in standand format\n"); break; } system("pause"); return 0; } }
mine 代码
#include"mine.h" static Create_Mine(char arr[][COL],int row,int col)//产雷函数 { int num = NUM; while (num) { int x = rand() % (row - 2) + 1; int y = rand() % (col - 2) + 1; if (arr[x][y] == '0') { arr[x][y] = '1'; num--; } } } static void ShowLine(col) { for (int i = 1; i < (col - 1); i++) { //printf("---"); } printf("\n"); } static void ShowBoard(char arr[][COL], int row, int col) { system("cls"); printf(" "); for (int i = 1; i < (row - 1); i++) { printf(" %d ", i); } printf("\n"); ShowLine(col); for (int i = 1; i < (row - 1); i++) { printf("%2d", i); for (int j = 1; j < (col - 1); j++) { printf(" %2c", arr[i][j]); } printf("\n"); ShowLine(col); } } static char MineNum(char arr[][COL], int x, int y) { return arr[x - 1][y - 1] + arr[x][y - 1] + arr[x + 1][y - 1] + arr[x + 1][y] + \ arr[x + 1][y + 1] + arr[x][y + 1] + arr[x - 1][y + 1] + arr[x - 1][y] - 7 * '0'; } void GameMine() { //创建用户数组和真实数组 char User_Board[ROW][COL]; char Mine_Board[ROW][COL]; //初始化俩数组 memset(User_Board, UnArea, sizeof(User_Board)); memset(Mine_Board, '0', sizeof(Mine_Board)); //随机产生雷区 srand((unsigned long)time(NULL)); Create_Mine(Mine_Board,ROW,COL); int num = (ROW - 2)*(COL - 2) - 20;//可点非雷区数目 while (num) { ShowBoard(User_Board,ROW,COL); printf("Please input the point you want\n"); int x = 0, y = 0; scanf("%d%d", &x, &y); if (x < 1 || x>10 || y < 1 || y>10) { printf("Illegal input\n"); continue; } if (User_Board[x][y] != UnArea) { printf("Please input again\n"); continue; } if (Mine_Board[x][y] == '1')//踩雷――炸 { printf("You loss ,Game Over"); ShowBoard(Mine_Board, ROW, COL); break; } User_Board[x][y] = MineNum(Mine_Board, x, y); num--; } }
输出结果
=========================== -------1、开始扫雷--------- -------0、退出 --------- =========================== Please input......
游戏失败