I'm creating a simple game of tennis, where the players are lines and the ball is a point. I'm having trouble moving the ball using rand. I want the ball to move randomly on the y-axis as it increments by one on the x-axis. Here is the procedure.
Libraries I'm using:
#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++;
}
}
How can I move the ball?
EDIT: This is where I call 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
}
}
I'm sorry for the confusing explanation!