rand()函数的问题

时间:2015-05-07 02:33:54

标签: c++ c

我的随机生成的“蛇粒”存在一些问题。我想让*用作我蛇的食物。它不是在我用作游戏板的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';
      }
    }
  }
}

1 个答案:

答案 0 :(得分:2)

您在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] = '*',使用random_x_val,其中random_y_val和{{1}}是矩阵的有效范围

相关问题