1. 程式人生 > 程式設計 >C語言實現消消樂遊戲

C語言實現消消樂遊戲

本文例項為大家分享了C語言實現消消樂遊戲的具體程式碼,供大家參考,具體內容如下

問題描述

給定一個矩陣, 判斷移動哪一個格子,可以實現消除。(定義連續三個即可消除)

據說是華為的筆試題。

分析

先寫一個函式,判斷包含(i,j)的格子是否可能實現消除。

然後就是向右向下交換,然後呼叫上面寫好的函式判斷
被交換的兩個格子是否實現消除。

重點是:

1、只需要向右向下交換,因為遍歷的時候,後面的交換會重複。前一個判斷了向右交換是否消除,後一個遍歷就不需要再判斷向左交換是否重複了。
2、一定要對被交換的兩個格子都判斷是否能消除,才能實現全面的判斷。

程式碼

//
// main.cpp
// huawei
//
// Created by SteveWong on 11/10/2016.
// Copyright © 2016 SteveWong. All rights reserved.
//

#include <iostream>
#include <string>
#include <vector>
#include <ctime>
//#include <cstdlib>
using namespace std;


const int LEN = 8;

void pmap(int map[][LEN])
{
 for (int i = 0; i < LEN; ++i)
 {
 for (int j = 0; j < LEN; ++j)
 {
 cout << map[i][j] << " ";
 }
 cout << endl;
 }
}



// 檢查以(i,j)為中心的點,看是否可以消除
bool check(int map[][LEN],int i,int j)// 保證i、j不越界,{
 if (
 (i-1>=0 && i+1<LEN && map[i-1][j]==map[i][j]&&map[i][j]==map[i+1][j])
 || (j-1>=0 && j+1<LEN && map[i][j-1]==map[i][j]&&map[i][j]==map[i][j+1])
 || (i-2>=0 && map[i-2][j]==map[i-1][j]&&map[i-1][j]==map[i][j])
 || (j-2>=0 && map[i][j-2]==map[i][j-1]&&map[i][j-1]==map[i][j])
 || (i+2<LEN && map[i+2][j]==map[i+1][j]&&map[i+1][j]==map[i][j])
 || (j+2<LEN && map[i][j+2]==map[i][j+1]&&map[i][j+1]==map[i][j])
 )
 {
 return true;
 }
 return false;
}


bool swapAndJudge(int m[][LEN],應該對被swap的兩個點都做縱向和橫向的檢查
{
 int map[LEN][LEN];
 for (int ii = 0; ii < LEN; ++ii)
 {
 for (int jj = 0; jj < LEN; ++jj)
 {
 map[ii][jj] = m[ii][jj];
 }
 }
 // 原來就可以消除
 if (check(map,i,j))
 {
 printf("no need to swap at (%d,%d)\n",j);
 return true;
 }
 // 只需要向下換和向右換
 // 向下換
 if (i + 1 < LEN)
 {
 swap(map[i+1][j],map[i][j]);

 if (check(map,j))
 {
 printf("# swap and sweap! (%d,j);
 return true;
 }
 if (check(map,i+1,j);
 return true;
 }

 swap(map[i+1][j],map[i][j]);// 換回來
 }

 // 向右換
 if (j + 1 < LEN)
 {
 swap(map[i][j+1],j+1))
 {
 printf("# swap and sweap! (%d,j+1);
 return true;
 }

 swap(map[i][j+1],map[i][j]);// 換回來
 }

 return false;

}


void findMinSwap(int map[][LEN])
{
 for (int i = 0; i < LEN; ++i)
 {
 for (int j = 0; j < LEN; ++j)
 {
 if (swapAndJudge(map,j))
 {
 printf("gotcha! (%d,j);
 }
 }
 }
}

int main(int argc,const char * argv[]) {
 // insert code here...
// std::cout << "Hello,World!\n";
 srand(unsigned(time(0)));
 for (int i = 0; i < LEN; ++i)
 {
 for (int j = 0; j < LEN; ++j)
 {
 map[i][j] = rand() % 5;
 }
 }
 cout << "xiaoxiaole!\n";
 findMinSwap(map);
 pmap(map);
 return 0;
}

更多有趣的經典小遊戲實現專題,分享給大家:

C++經典小遊戲彙總

python經典小遊戲彙總

python俄羅斯方塊遊戲集合

JavaScript經典遊戲 玩不停

javascript經典小遊戲彙總

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。