首頁  >  文章  >  後端開發  >  一個用C語言修改過的Nim遊戲?

一個用C語言修改過的Nim遊戲?

PHPz
PHPz轉載
2023-09-01 14:57:07707瀏覽

一個用C語言修改過的Nim遊戲?

Nim 的改進賽局是一個陣列的最佳化賽局。遊戲根據起始玩家和最佳移動來預測獲勝者。

#遊戲邏輯 - 在遊戲中,我們得到一個包含元素的陣列{}。通常有兩個玩家玩遊戲,即玩家 1 和玩家 2。兩者的目的都是確保從數組中刪除它們的所有數字。現在,玩家1必須刪除所有可被3整除的數字,玩家2必須刪除所有可被5整除的數字。目標是確保他們以最佳方式刪除所有元素並找到獲勝者。

##範例

#
Array : {1,5, 75,2,65,7,25,6}
Winner : playerB.
A removes 75 -> B removes 5 -> A removes 6 -> B removes 65 -> No moves for A, B wins.

程式碼預覽

程式碼將尋找A 可以刪除的元素數量、B 可以刪除的元素數量以及它們都可以刪除的元素數量消除。根據它們都可以刪除的元素數量找到解決方案。由於 A 刪除了第一個元素,即使他必須比 B 多刪除一個元素,它也可以獲勝。在正常情況下,刪除的元素數量最多的玩家獲勝。

尋找遊戲解決方案的程序NIM

#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {1,5, 75,2,65,7,25,6};
   int n = sizeof(arr) / sizeof(arr[0]);
   int movesA = 0, movesB = 0, movesBoth = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] % 3 == 0 && arr[i] % 5 == 0)
         movesBoth++;
      else if (arr[i] % 3 == 0)
         movesA++;
      else if (arr[i] % 5 == 0)
         movesB++;
   }
   if (movesBoth == 0) {
      if (movesA > movesB)
         cout<<"Player 1 is the Winner";
      cout<<"Player 2 is the Winner";
   }
   if (movesA + 1 > movesB)
      cout<<"Player 1 is the Winner";
   cout<<"Player 2 is the Winner"; ;
   return 0;
}

輸出

Player 2 is the Winner

以上是一個用C語言修改過的Nim遊戲?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除