如何在c++中随机移动球
How to move a ball randomly in c++?
我正在创建一个简单的网球游戏,玩家是线,球是点。我用兰特踢球有问题。我希望球在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)
我希望这将工作
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 将对象移动到std::shared_ptr
- 字符串-C++后显示的随机字符
- 何时在引用或唯一指针上使用移动语义
- 如何从具有移动语义的类对象中生成共享指针
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- SDL/C++: 如何平滑但随机地移动矩形?
- 我试图将光标平滑地移动到随机点
- 矩阵中字符的随机移动
- 为什么我的TicTacToe游戏在生成随机移动时会卡住
- 随机坐标和禁用下一个随机集的移动
- 需要帮助来理解ns3 ->随机游走2移动模型
- OpenGL-在随机方向上移动的对象
- C++:Tic Tac Toe计算机随机移动
- c++的随机代理移动是相同的
- 随机移动物体
- 在cocos2d-x中的游戏场景中随机移动障碍物
- 如何在c++中随机移动球