繁体   English   中英

rand()函数的问题

[英]Issues with rand() function

我的随机生成的“蛇丸”有一些问题。 我希望将*用作蛇的食物。 它不是在我用作游戏板的char数组内部生成的。 我不确定; 我可能会说错了或使用了该函数。

#include<iostream>
#include<Windows.h>
#include<stdlib.h>
#include<time.h>
#include<stdio.h> 
using namespace std;

char Map[11][22] =
{
  "---------------------",
  "|S              *   |",
  "|                   |",
  "|                   |",
  "|                   |",
  "|                   |",
  "|                   |",
  "|                   |",
  "|                   |",
  "|                   |",
  "---------------------"
};
int x = 1, y = 1;
bool GameRunning = true;
int main()
{
  srand(time(NULL));
  int pellet = rand();

  while (GameRunning == true)
  {
    for (int pellet = 0; pellet % Map[11][22]; pellet++)
    {
      cout << '*';
    }
    system("cls");
    for (int display = 0; display < 11; display++)
    {
      cout << Map[display] << endl;
    }
    system("pause>nul");

    if (GetAsyncKeyState(VK_DOWN))
    {
      int y2 = y + 1;
      if (Map[y2][x] == ' ')
      {
        Map[y][x] = ' ';
        y++;
        Map[y][x] = 'S';
      }
    }
    if (GetAsyncKeyState(VK_UP))
    {
      int y2 = y - 1;
      if (Map[y2][x] == ' ')
      {
        Map[y][x] = ' ';
        y--;
        Map[y][x] = 'S';
      }
    }
    if (GetAsyncKeyState(VK_RIGHT))
    {
      int x2 = x+1;
      if (Map[y][x2] == ' ')
      {
        Map[y][x] = ' ';
        x++;
        Map[y][x] = 'S';
      }
    }
    if (GetAsyncKeyState(VK_LEFT))
    {
      int x2 = x - 1;
      if (Map[y][x2] == ' ')
      {
        Map[y][x] = ' ';
        x--;
        Map[y][x] = 'S';
      }
    }
  }
}

您在for循环中用0覆盖了pellet ,所以它总是用0而不是rand()初始化。 另外, rand()会产生一个介于0到至少32767之间的随机数,因此您需要对其进行修改以获取所需的范围。 例如,从0-20开始,您将执行pellet = rand() % 21或4-16,而您可以进行pellet= (rand() % 13) + 4 (因为4-16可以重写为范围0-12加4)。 这是rand()文档: http : //www.cplusplus.com/reference/cstdlib/rand/

第二点,您真的需要for循环吗? 真的应该出现在游戏循环中吗? 在开始时设置一次似乎更有意义。

您可能希望使用Map[random_x_val][random_y_val] = '*'Map[random_x_val][random_y_val] = '*'的开头将随机框设置为'*' ,其中random_x_valrandom_y_val是矩阵的有效范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM