Problems dealing with rand()

Hello! I am coding a tic tac toe game in which the computer generates a random number and makes a move accordingly. The random numbers are being generated well the only problem is that sometimes when i execute the program it goes haywire! It ignores all the if condition i have specified. But it works just fine 80% of the times.. PLEASE CAN ANYONE HELP ME OUT. The following is the code for the functions of class Match that i made.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
void Match::AIplaceMark()
{
	tempMark=p2mark;				//sets tempMark to AI mark
	do
	{
		turnvalid==true;
		Match::AIopponent();				//Calls AIopponent behaviour inside the AIplaceMark behaviour to find out the next move
		if(select=='1' && board[0][0]=='1')
		{
			board[0][0]=tempMark;
		}
		else if(select=='2' && board[0][1]=='2')
		{
			board [0][1]=tempMark;

		}
		else if(select=='3' && board[0][2]=='3')
		{
			board [0][2]=tempMark;
		}
		else if(select=='4' && board[1][0]=='4')
		{
			board [1][0]=tempMark;
		}
		else if(select=='5' && board[1][1]=='5')
		{
			board [1][1]=tempMark;
		}
		else if(select=='6' && board[1][2]=='6')
		{
			board [1][2]=tempMark;
		}
		else if(select=='7' && board[2][0]=='7')
		{
		board [2][0]=tempMark;
		}
		else if(select=='8' && board[2][1]=='8')
		{
			board [2][1]=tempMark;
		}
		else if(select=='9' && board[2][2]=='9')
		{
			board [2][2]=tempMark;
		}
		else
		{
			turnvalid=false;
			cout<<".";
		}
	}
	while(turnvalid==false);
}

void Match::AIopponent()
{
	srand(static_cast<unsigned int>(time(0)));
	for(int i=0;i<10;i++)
	{
      randNum=(rand()%9+1);
	}
	if(randNum==1)
	{
		select='1';
	}
	else if(randNum==2)
	{
		select='2';
	}
	else if(randNum==3)
	{
		select='3';
	}
	else if(randNum==4)
	{
		select='4';
	}
	else if(randNum==5)
	{
		select='5';
	}
	else if(randNum==6)
	{
		select='6';
	}
	else if(randNum==7)
	{
		select='7';
	}
	else if(randNum==8)
	{
		select='8';
	}
	else
	{
		select='9';
	}
}
Last edited on
I didn't look through your code completely, but a few things stood out for me.

#1: Line 6... is that really the equals operator you meant to use there?

#2: You can convert between a one-digit integer and its ASCII character equivalent just by subtracting '0' from it. That might help shorten your code. ;)

#3: srand() is best called only once @ line 56. Maybe call it from main()?

-Albatross
Last edited on
Oh my bad. Thank you for Helping. And sorry to inconvinience you over such a minor error.
Topic archived. No new replies allowed.