将值从一个函数返回到另一个函数

Returning a value from a function to another function

本文关键字:函数 一个 返回 另一个      更新时间:2023-10-16

我正在制作一个程序,用户可以在打印到屏幕上的数组中移动他们的字符(数字 1)。当我尝试检查下一个仓位是否在我的 moveRight 函数中打开时,我遇到了麻烦。

我想返回数组部分的值,该部分是 1 右侧的一个空格。我尝试返回数组下一个位置的值的原因是,我想将该值返回到我的 drawBoard 函数,以便我可以使用该值重新打印在该位置制作电路板的电路板。如何将 mB[i+1] -(1 右侧的下一个值)返回到我的绘图板函数?

#include "stdafx.h"
#include <iostream>
#include "PlayerM.h"
using namespace std;
class Player {
public:
   Player::Player(int b[]) //create a constructer to copy the values of b into mB
   {
      // copy b into the member array
      for (int i = 0; i < 16; i++) {
         mB[i] = b[i];
      }
   }
   int moveUp();
   void moveDown();
   int moveRight();
   void moveLeft();
private:
   int mB[16];
};
int Player::moveUp() {
   return 0;
}
void Player::moveDown() {
}
int Player::moveRight() {
   for (int i = 0; i < 16; i++) //find the players pos on aray
   {
      if (mB[i] == 1 && i < 3) //if the player is eligible to move
      {
         mB[i] = 0;
         mB[i + 1] = 1;
         return mB[i + 1];
      }
   }
}
void Player::moveLeft() {
}
int drawBoard(int boardArray[16]) //draw the game board
{
   for (int i = 0; i < 16; i++) //use a for loop to simply draw the game board (4x4)
   {
      cout << boardArray[i]; //ouput the storage id of the array
      if (i == 3 || i == 7 || i == 11 || i == 15) //every 4 lines begin new line
      {
         cout << "n";
      }
   }
   return 0;
}
int main() {
   int bArray[16] = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //create an array [16]
   drawBoard(bArray); //send the aray to drawBoard ()
   Player p(bArray); //send bArray to the p constructer
   char m;
   cin >> m;
   if (m == 'W') {
      p.moveRight();
   }
   char f;
   cin >> f;
}
int Player::moveRight() {
   for (int i = 0; i < 16; i++) //find the players pos on aray
   {
      if (mB[i] == 1 && i < 3) //if the player is eligible to move
      {
         mB[i] = 0;
         mB[i + 1] = 1;
         return mB[i + 1];
      }
   }
}

我认为您想要以下内容(假设电路板是 4x4):

int Player::moveRight() {
   for (int i = 0; i < 16; i++) //find the players pos on aray
   {
      if (mB[i] == 1 && (i%4) < 3) //if the player is eligible to move
      {
         mB[i] = 0;
         mB[i + 1] = 1;
         return mB[i + 1];
      }
   }
}

更改内容:i < 3改为(i%4) < 3

相关文章: