简体   繁体   中英

Issues with rand() function

I'm having some issues with my random-generated "snake pellet". I want the * to be used as the food for my snake. It's not generating inside the char array that I'm using as the board for the game. I'm not sure; I could be calling it wrong or using the function improperly.

#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';
      }
    }
  }
}

You overwrite pellet in the for loop with 0 so it is always initialized with 0 instead of rand() . Also, rand() produces some random number between 0 to at least 32767, so you need to mod it to get the range you want. eg from 0-20 you would do pellet = rand() % 21 or 4-16 you could do pellet= (rand() % 13) + 4 (since 4-16 can be rewritten as range 0-12 plus 4). Here is documentation for rand() : http://www.cplusplus.com/reference/cstdlib/rand/

On a second note, do you really need a for loop? And should it really be in the game loop? It seems it would make more sense to set it once at the beginning.

you would want to set some random box in the map as the '*' at the beginning using something like Map[random_x_val][random_y_val] = '*' where random_x_val and random_y_val are valid ranges for your matrix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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