如何在c++中随机移动球

How to move a ball randomly in c++?

本文关键字:随机 移动 c++      更新时间:2023-10-16

我正在创建一个简单的网球游戏,玩家是线,球是点。我用兰特踢球有问题。我希望球在y轴上随机移动,因为它在x轴上递增一。这是程序。

我正在使用的库:

 #include <stdio.h>     
 #include <stdlib.h>    
 #include <time.h>   
void punto::viajar (char dir,int largo,int anch)// direction, length and width
{
    if (dir=='d') // if direction is to the right
    {
        x++; // moves to the right by 1
        srand(time(NULL)); // here is my problem
        if (rand()%2==0 && y<largo) // if ball is within the court's borders
        {
            y++;
        }
    }
    else
    {
        y--;
    }
    if (dir=='i') // to the left
    {
        x--;
        srand(time(NULL));
        if (rand()%2==0 && y<largo)
        {
            y--;
        }
    }
    else
    {
        y++;
    }
}

我怎样才能移动球?

编辑:这就是我所说的viajar:

void juego:: funcionar()
 {
dibujar(); // draws ball, court, and players
char diraux='d'; // auxiliary direction
char tecla; // char key
while (1==1)
{
  while (pel.GetX()>0 && pel.GetX()<ancho) // while the ball is within court's range
  {
    pel.viajar(diraux,30,60); // ball travels to right, and court's length=30, width=60
    if (kbhit()) // if any of the two players presses a key
    {
       tecla=getch();
       moverraquetas(tecla); // if s/b is pressed, player 1 moves. if 2/8 is pressed, player 2 moves.
    }
    if (r1.toca(pel)=='S') //if player 1 touches the ball,
        diraux='d'; // ball moves to the right
    if (r2.toca(pel)=='S') // if player 2 touches the ball,
      diraux='i'; // ball moves to the left
  }
}

很抱歉我的解释令人困惑!

srand初始化整个随机流-不应该每次调用rand都调用它,否则你总是会得到相同的值(流中的第一个,给定srands的参数)。启动程序时只调用一次。

此外,rand() % small_int不是一个非常可靠的随机方法,因为它不能保证均匀分布。请参阅此处,例如-为什么rand()%7总是返回0?

调用srand()一次,并且仅在程序启动时调用一次。每次调用rand()时设置随机数种子是不必要的,并且不允许rand()按预期生成其序列。此外,如果用相同的值调用srand()rand()将产生相同的值,因此,如果在同一秒内调用两次,则使用当前时间作为种子将产生不希望的效果。

在许多情况下,根本没有必要调用srand()——如果你的球每次运行程序时都使用相同的随机序列,这真的重要吗——在任何情况下,球员的"随机"行为都会使每场比赛变得不同。

尽管如前所述,srand()的使用存在问题,但我不认为这是最大的问题。

例如,如果dir=='d',y可以递增,但在dir=='i'的else子句中总是递增。同样,当dir=='i'时,y将递减两次。

控制流程也许应该是:

if (dir=='d') // if direction is to the right
{
    x++ ;
    if( ... )
    {
        y++;
    }
    else
    {
        y--;
    }
}
else if (dir=='i') // MUTUALLY EXCLUSIVE TO 'd'
{
    x--;
    if( ... )
    {
        y--;
    }
    else
    {
        y++;
    }
}

使用此代码获取随机值

srand (time(NULL)); cout << (rand() % 100 + 1)

我希望这将工作