DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Senior Member
Join Date
Aug 2004
Posts
43,023

visual basic

[Originally posted by vijay]

i am designing a game in visual basic (noughts and crosses/tic tac toe)

i want to be able to play against the computer.

i have created a grid with the 9 labels for the x or the o.

i've made the random number thing BETWEEN 10-0. now i want each number in to represesnt a label. i.e. label1 represents rnd1, label2 -> 2....and so on upto label9->9. then the computer will automatically place its mark on that chosen label, but if it is not available, i want it to choose again and so on.

i'd really appreciate if this could b solved by about the 11th March 02. thanks very much

2. Senior Member
Join Date
Aug 2004
Posts
43,023

Re:visual basic

[Originally posted by Kroc2000]

What you want is a control array, much like a normal array you can have multiple controls with the same name, each indexed with a number.

Create your first label and call it LblBox.
Copy it using Ctrl-C and then Press Ctrl-V to paste, VB will ask 'Do you want to create a control array?' click yes.

You now have two labels, LblBox(0) and LblBox(1).
Create the rest of the labels the same way and position appropriatley.

You can now use your random number (which you should change to 0-9) to place a mark in the label. The code below will also check if there is something already in the square. (This assumes the CPU is 'X')

'A label so that we may jump here if a square is allready taken.
LblLoop:

x = int(Rnd(1)*10) 'random number between 0-9
'If the square has an 'O' in it then choose another.
if LblBox(x).caption = "O" then
ÿ ÿ goto LblLoop
else
ÿ ÿ 'Otherwise put an X in the box
ÿ ÿ LblBox(x).caption = "X"
end if

That's it! A random number is produced and the relevant square is marked if it is empty.

Does this help?

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise