c语言扫雷小游戏
Posted ~千里之行,始于足下~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c语言扫雷小游戏相关的知识,希望对你有一定的参考价值。
用c语言实现扫雷小游戏
game.h
#pragma once
#include<stdio.h>
#include<string.h>
#include<time.h>
#include<stdlib.h>
#include<windows.h>
#pragma warning(disable:4996)
#define ROW 12
#define COL 12
#define STYLE '*' //棋盘风格
#define MINE_COUNT 20 //棋盘的风格
extern void game();
game.c
#include"game.h"
//埋雷
static void setMines(char board[][COL], int row, int col)
{
int count = MINE_COUNT;
while (count)
{
int x = rand() % (ROW - 2) + 1;
int y = rand() % (COL - 2) + 1;
if (board[x][y] == '0')//1是雷,0不是雷
{
board[x][y] = '1';
count--;
}
}
}
static void ShowLine(int col)
{
for (int i = 0; i <= (col - 2); i++){
printf("----");
}
printf("\\n");
}
static void showMyBoard(char board[][COL], int row, int col)
{
printf(" ");
for (int i = 1; i <= (col - 2); i++){
printf("%d ", i);
}
printf("\\n");
ShowLine(col);
for (int i = 1; i <= (row - 2); i++){
printf("%-3d|", i);
for (int j = 1; j <= (col - 2); j++){
printf(" %c |", board[i][j]);
}
printf("\\n");
ShowLine(col);
}
}
//返回该位置周围雷的数量
static int countMines(char board[][COL], int x, int y)
{
return board[x - 1][y - 1] + board[x - 1][y] + board[x - 1][y + 1] + \\
board[x][y + 1] + board[x + 1][y + 1] + board[x + 1][y] + \\
board[x + 1][y - 1] + board[x][y - 1] - 7 * '0';
}
void game()
{
srand((unsigned long)time(NULL));
char showBoard[ROW][COL]; //已排雷的位置为雷的数量
char mineBoard[ROW][COL]; //雷盘,都是0或1字符
memset(showBoard, STYLE, sizeof(showBoard));
memset(mineBoard, '0', sizeof(mineBoard));
setMines(mineBoard, ROW, COL);
int x = 0;
int y = 0;
int row = ROW;
int col = COL;
int mineCount = MINE_COUNT;
int cnt = (row - 2) * (COL - 2) - mineCount;//排雷的次数
while (cnt)
{
system("cls");
showMyBoard(showBoard, ROW, COL);
printf("please the position: \\n");
scanf("%d %d", &x, &y);
if (x < 1 || x > 10 || y < 1 || y > 10)
{
printf("Position error!\\n");
continue;
}
if (showBoard[x][y] != STYLE)
{
printf("position is not *\\n");
continue;
}
if (mineBoard[x][y] == '1')
{
printf("game over!\\n");
showMyBoard(mineBoard, ROW, COL);
system("pause");
system("cls");
break;
}
showBoard[x][y] = countMines(mineBoard, x, y);
cnt--;
}
}
main.c
#include"game.h"
void menu()
{
printf("|+++++++++++++++++++++++++++++++++++|\\n");
printf("|+++1. play 0. exit+++|\\n");
printf("|+++++++++++++++++++++++++++++++++++|\\n");
}
int main()
{
int quit = 0;
while (!quit)
{
menu();
int select = 0;
printf("请输入您的选择: \\n");
scanf("%d", &select);
switch (select)
{
case 1: //printf("开始游戏\\n");
game();
break;
case 0:
quit = 1;
printf("欢迎使用!\\n");
break;
default:
printf("输入错误!\\n");
}
}
system("pause");
return 0;
}
这个扫雷游戏设计最妙之处就是12 * 12的棋盘,实际使用了10 * 10,原因是为了方便计算排完雷位置周围雷的数量。
以上是关于c语言扫雷小游戏的主要内容,如果未能解决你的问题,请参考以下文章
C语言实现小游戏篇我接触的第一款电脑游戏,你可以永远相信 “ 扫雷 ” 。[ C语言实现 ] [ 超详细,超清楚 ] [ 有代码 ]