簡體   English   中英

在C中的戰艦程序中遇到while循環問題

[英]having trouble with while-loop in battleship program in c

我正在嘗試制定戰艦計划。 到目前為止,我的程序要求用戶1輸入他/她想要他們的船的位置。 然后用戶2猜測他們認為船在哪里。

如果用戶2第一次沒有擊中玩家1的所有戰艦,我會嘗試讓其重新提示用戶2。

我曾嘗試在多個位置放置while循環while循環,但每次程序崩潰時,現在的while循環也會使其崩潰。 似乎沒有任何作用。

#include <stdio.h>

int main(void)
{
    int board[2][2];
    int i, j;   //initialize loop variables
    int i2, j2; //initialize 2nd loop variables
    int i3, j3; // 3rd loop variables

    printf(" User 1: Enter a '1' where you want to place your ship and '0' where you do not.\n");

    /* these loops prompt the user to enter a 0 or 1 for each space in the 2d array depending on where they want their ship*/ 
    for(i = 0; i <= 1 ; i++)
    {
      for(j = 0 ; j <= 1 ; j++)
      {
          printf("space[%d][%d]: ", i, j);
          scanf("%d", &board[i][j]);
      }
    }

    while(board[i][j] == 1)
    { 
        /*used to prompt the user2 as long as user1 still has ships left*/
        int board2[2][2];
        printf("User 2: Enter a '1' where you think User 1 placed their ship and '0' where \nyou do not.\n");

        /* Asks user2 for their guesses */
        for(i2 = 0 ; i2 <= 1 ; i2++)
        {
          for(j2 = 0 ; j2 <= 1 ; j2++)
          {
              printf("space[%d][%d]:", i2, j2);
              scanf("%d", &board2[i2][j2]);
          }
        }

        for(i3 = 0 ; i3 <= 1 ; i3++)
        {
            //compares user1 input to user2 guess
            for(j3 = 0 ; j3 <= 1 ; j3++)
            {
                if(board[i3][j3] == 1 && board2[i3][j3] == 1)
                {
                    printf("Hit!\n"); // if the inputs match display "hit"
                    board[i][j] = 0;
                }
                else
                {
                    printf("Miss!\n"); // if no hit display miss
                }
            }
        }
    }

    return 0;
}

我認為,根據戰列艦計划的規則,我們為用戶找到隨機放置的艦船規定了一些限制。 如果用戶沒有輸入有效的響應,則您將繼續重復此過程,直到輸入了有效的響應或超過極限為止。

在您的情況下,您要重復此過程,直到用戶2找到所有船而沒有任何限制。

我在您的代碼中發現了一些問題:

  1. 假設user1給出1 0 1 0,而user2給出1 1 1 1,則您的程序將獲得成功的結果,因為您正在使用user2輸入搜索完整的戰板。
  2. User2將連續運行,直到board [] []包含零值為止。

更改程序設計的幾點-

  1. 保持用戶2找到船的限制。
  2. 不要使用user2輸入來搜索完整的矩陣,而是使用user2輸入來檢查戰局的索引。

祝您好運迎接挑戰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM