基于C語言代碼實現(xiàn)掃雷游戲
更新時間:2020年11月10日 08:40:04 作者:楠c
這篇文章主要為大家詳細介紹了基于C語言代碼實現(xiàn)掃雷游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言實現(xiàn)掃雷游戲的具體代碼,供大家參考,具體內容如下
掃雷(第一次多文件應用)
掃雷的思路
game.h
#ifndef _GAME_H_ #define _GAME_H_ #include<stdio.h> #include <time.h> #include<string.h> #include<windows.h> #pragma warning(disable:4996) #define ROW 12 #define COL 12 //定義20個雷 #define NUMS 20 void Menu(); void Game(); #endif
main.c
#include "game.h" int main(){ int quit = 0; int select = 0; while (!quit){ Menu(); scanf("%d", &select); switch (select){ case 1: Game(); break; case 2: quit = 1; break; default: printf("請重新輸入"); break; } } system("pause"); return 0; }
game.c
#include "game.h" void Menu() { printf("##########################\n"); printf("## 1. Play 2. Exit ##\n"); printf("##########################\n"); printf("請輸入# "); } //設置20個隨機雷 void SetMines(char mine_board[][COL], int row, int col) { int count = NUMS; while (count){ int x = rand() % 10 + 1; int y = rand() % 10 + 1; if (mine_board[x][y] == '0'){ mine_board[x][y] = '1'; count--; } } } //判斷周圍有幾個雷 int GetMines(char mine[][COL], int row, int col, int x, int y) { return mine[x - 1][y - 1] + mine[x - 1][y] + mine[x - 1][y + 1] + \ mine[x][y - 1] + mine[x][y + 1] + mine[x + 1][y - 1] + \ mine[x + 1][y] + mine[x + 1][y + 1] - 8 * '0'; } //設置界面的下劃線 static void ShowLine(int nums) { printf("---"); for (int i = 0; i < nums; i++){ printf("-"); } printf("\n"); } //一個顯示界面,傳入界面數(shù)組顯示掃雷界面,傳入布雷數(shù)組顯示雷區(qū)界面 void ShowBoard(char show_board[][COL], int row, int col) { printf(" "); for (int i = 1; i < row - 1; i++){ printf(" %d ", i); } printf("\n"); ShowLine(2 * col + col + 4); for (int i = 1; i < row - 1; i++){ printf("%2d|", i); for (int j = 1; j < col - 1; j++){ printf(" %c |", show_board[i][j]); } printf("\n"); ShowLine(2 * col + col + 4); } } void Game() { char show_board[ROW][COL]; char mine_board[ROW][COL]; memset(show_board, '*', sizeof(show_board)); memset(mine_board, '0', sizeof(mine_board)); srand((unsigned long)time(NULL)); SetMines(mine_board, ROW, COL); int count = (ROW - 2)*(COL - 2) - NUMS; int x = 0; int y = 0; do{ ShowBoard(show_board, ROW, COL); printf("請輸入位置# "); scanf("%d %d", &x, &y); if (x < 1 || x > 10 || y < 1 || y >10){ printf("輸入越界,請重新輸入!\n"); continue; } if (show_board[x][y] != '*'){ printf("該位置已經被排除,請重新輸入!\n"); continue; } if (mine_board[x][y] == '1'){ break; } int num = GetMines(mine_board, ROW, COL, x, y); show_board[x][y] = num + '0'; count--; system("cls"); } while (count > 0); //count>0說明坐標是雷,break提前退出了 if (count > 0){ printf("你被炸死了!\n"); } else{ printf("你贏了!\n"); } printf("下面是雷區(qū)的排布!\n"); ShowBoard(mine_board, ROW, COL); }
更多有趣的經典小游戲實現(xiàn)專題,分享給大家:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C++實現(xiàn)LeetCode(92.倒置鏈表之二)
這篇文章主要介紹了C++實現(xiàn)LeetCode(倒置鏈表之二),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07C語言時間函數(shù)的ctime()和gmtime()你了解嗎
這篇文章主要為大家詳細介紹了C語言時間函數(shù)的ctime()和gmtime(),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02