Tic-Tac-Toe (Working Solution)

  • Thread starter Thread starter Steven Smith
  • Start date Start date
S

Steven Smith

Vallerie, combining Kims logic for determining whether
an "X" or an "O" should be displayed & the rest of my
code makes a perfect working solution for the course
book. Liked the use of NOT kim cheers for that. anyway
heres the complete code for a working solution, any
improvments or comments are as always appreciated.


/////////

Dim mLabelCollection As New Collection()


Private Sub ExitButton_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles ExitButton.Click
Me.Close()
End Sub



Private Sub NewGameButton_Click(ByVal sender As
Object, ByVal e As System.EventArgs) Handles
NewGameButton.Click
'declare object & integer variables
Dim objLabel As Label
Dim intx As Integer

'looping to find Label controls on form &
clearing the contents
Do While intx < Controls.Count - 1
If TypeOf Controls.Item(intx) Is Label Then
objLabel = Controls.Item(intx)
objLabel.Text = ""

End If
intx = intx + 1
Loop

End Sub

Private Sub TicTacToeForm_Load(ByVal sender As
Object, ByVal e As System.EventArgs) _
Handles MyBase.Load

'add controls to the form level collection
mLabelCollection.Add(Me.TTT1Label)
mLabelCollection.Add(Me.TTT2Label)
mLabelCollection.Add(Me.TTT3Label)
mLabelCollection.Add(Me.TTT4Label)
mLabelCollection.Add(Me.TTT5Label)
mLabelCollection.Add(Me.TTT6Label)
mLabelCollection.Add(Me.TTT7Label)
mLabelCollection.Add(Me.TTT8Label)
mLabelCollection.Add(Me.TTT9Label)


End Sub

'determine player turn & process the label clicks to
display the correct marker
Private Sub PlacePlayersMarker(ByVal sender As
Object, ByVal e As System.EventArgs) _
Handles TTT1Label.Click, TTT2Label.Click,
TTT3Label.Click, _
TTT4Label.Click, TTT5Label.Click,
TTT6Label.Click, _
TTT7Label.Click, TTT8Label.Click,
TTT9Label.Click


'determine which label has been clicked and
display players marker

'declare object variables
Dim ObjLabel As Label
'assign sender parameter to object variable
ObjLabel = sender
Static strPlayer As Boolean

strPlayer = Not strPlayer
If ObjLabel.Text = "" Then
If strPlayer Then
ObjLabel.Text = "X"
Else
ObjLabel.Text = "O"
End If
End If
End Sub
End Class


////////
 
Nice to see when things work out :-)

I made an online tic-tac-toe, but it was in VB6 so I doubt it would help
much, but the logic was pretty much the same as yourself, whoever clicked
the board first became "O" in my case (In England we do "O" first for some
reason or another), the players go would toggle with each position of the
piece and a 'check for win' routine would also run with ever click on and
after the 3rd go :-)

Nick.

--
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
Slow internet connection?
Having problems with you job?
You're marriage is on the rocks?
You can't sleep at night?
You have a drink and drugs addiction?
You are sexually impotent?
Then enable Option Strict!
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
 
oops. I kept replying to you personally instead of to you in the newsgroups.
Did you get my messages?
 
-----Original Message-----
Hi Steven,

I walloped your code onto an existing form of mine and it failed to work -
completely that is. The placement is fine but the clearing isn't quite.

Questions.
What do you do with that lovely collection of yours?

In NewGameClicked are you sure about that loop? What is the equivalent
For loop that you'd use? Does the existing while loop match that?

On style - why is strPlayer a Boolean ? (I know why, just want you to
see it :-))

I would tend to put Static strPlayer As Boolean at the top of the routine
so that it stands out.

Regards,
Fergus


.


Your absolutely right fergus the collection does
nothing... :)

The program runs fine here, so not sure whats goin on
there.

the static boolean selection structure is explained in
code to the best of my ability but I've only been doing
this for a few weeks :)

the do...while loophas also been replaced.

any further comments or guidance is appreciated

Private Sub ExitButton_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles ExitButton.Click
Me.Close()
End Sub



Private Sub NewGameButton_Click(ByVal sender As
Object, ByVal e As System.EventArgs) Handles
NewGameButton.Click
'declare object & integer variables
Dim objLabel As Label
Dim intx As Integer

'looping to find Label controls on form &
clearing the contents

'///Do While intx < Controls.Count - 1
'///If TypeOf Controls.Item(intx) Is Label Then
'///objLabel = Controls.Item(intx)
'///objLabel.Text = ""

'///End If
'///intx = intx + 1
'///Loop


'Equivalent FOR... LOOP carrrying out task
'of clearing the text property from all members
'of the label class on the form

For intx = 0 To Controls.Count - 1
If TypeOf Controls.Item(intx) Is Label Then
objLabel = Controls.Item(intx)
objLabel.Text = ""
End If
Next



End Sub


'determine player turn & process the label clicks to
display the correct marker
Private Sub PlacePlayersMarker(ByVal sender As
Object, ByVal e As System.EventArgs) _
Handles TTT1Label.Click, TTT2Label.Click,
TTT3Label.Click, _
TTT4Label.Click, TTT5Label.Click,
TTT6Label.Click, _
TTT7Label.Click, TTT8Label.Click,
TTT9Label.Click

'declare static
Static strPlayer As Boolean
'declare object variable
Dim ObjLabel As Label

'assign sender parameter to object variable
ObjLabel = sender

'change value of strPlayer to True. Then check if
a
'marker has already been displayed in the Label
control
'which was returned by the sender. If not check
'wether strPlayer = strPlayer if that is true
'set the text property of the object label to "X"
'if it is false set the text property to "O"
'the process is then repeated except the initial
'value of the static variable is "O" as it holds
'its value after the procedure ends

strPlayer = Not strPlayer
If ObjLabel.Text = "" Then
If strPlayer = True Then
ObjLabel.Text = "X"
Else 'false
ObjLabel.Text = "O"
End If
End If
End Sub
End Class
 
Hi again Stephen,

I wanted to make you look for meanings rather than me handing them to you
on a plate. Then I'd come back after to fill in any gaps. Best for learning
that way, even if it's a bit puzzling for you in the meantime. :-)

I mentioned the collection because it's just what you need in that reset
loop! It doesn't matter in this sort of program, of course, but I'm interested
in you learning principles as well as getting your code working.

Namely:
Having taken the trouble to create a collection containing <only> the
tic-tac labels, what do you do with it? And then when it comes to clearing the
labels, how many Controls do you check? That's one part of it. The other part,
which you wouldn't realise on your test setup, is that there may be other
labels on the Form, such as "Player 1", "Player 2". These would get wiped
too!! Oops.

Regarding the 'while' loop. I can assure you that it didn't work for me.
Not because I plonked it onto my form and messed it up, but because there was
a logic error in your code. That's why I asked about the equivalent 'for'
loop. I also wanted you to tell me whether your 'while' loop matches the 'for'
loop. (It doesn't - but why? Learning point: How 'while' and 'for' are not
always the same.)

strPlayer - presumably it was initially a string variable. Now it's a
Boolean. But a reader of your code will wionder - did he forget to change the
"str" to "t" (truth) or "f" (flag) or "b" (boolean) or whatever is your choice
for a Boolean. I've got no problem with your choice of a Boolean for a
two-state variable! But change the type and change the name is a handy habit
to develop early on.

In fact developing a style and becoming habitually consistent is very
important. I notice that you have the following:

strBoolean - lower-case type and capitalised type, but no name.
mLabelCollection m for member, capitalised type, capitalised name, but
only a sort of name.
objLabel - lower case type, but no name.
intx - lowercase everything
TTT1Label. - upper case name, capitalised type.

strBoolean - it's a Boolean give it a 't' (that's my style, many would
disagree, but 'b' and 'f' are already taken in my scheme). That says it all as
regards type. So what should its name be? Well, it controls whose turn it is.
It also controls which type of mark is made (X or O). Which is the central
concept? At the moment it's the mark. But, if later you decide to allow Player
1 to choose whether they'd like to be X or O, then it directly controls the
player's turn but only indirectly the mark - you'd use it to index an array of
Marks - one for each player. But that wouldn't work because it's a Boolean -
an integer would be better. So let's change it to, say, iPlayerToGo. And place
asMarks (iPlayerToGo) in the tic-tak grid. ["asMarks" is 'a', an array, of
's', strings, containing 'Marks' the marks made by the players. Or whatever
word you prefer.]

All that discussion over just a single variable. Is it worth it? Tell me
what you think.

mLabelCollection, TTT1Label, ObjLabel. These are all labels. It's common
to have control types abbreviated in lower case at the front. There's a
Microsoft recommended list somewhere in the Help. For labels you'd use "lbl".
Which gives us mlblCollection, lblTTT1 and lblObj. Still not there yet.

mlblCollection. Some people like to separate the 'm' with an underscore.
Now, what is it a collection of? Not labels. That's how whatever they are is
<implemented> but that's not what they <are>. They are in fact squares, or
places or whatever, on your tic-tac-toe board. Labels is a computery thing.
But your game is a human thing. Choose the human names over the computery
names. So that gives us "m_lblSquares". Note the use of the plural. This
indicates that it's not a single sqaure. Some people like to have "coll"
instead. "m_colllblSquares" or "m_collSquares" and who cares about the
labelness, or "m_alblSquares" because it's an array of labels.

Tomorrow you might rewrite your program using PictureBoxes instead of
labels. "m_collSqaures" would survive untouched. Anything with "lbl" would
have to be changed to "pic". [Remember strBoolean - that didn't survive the
change from string]. So a name that is implementation free can be better.
There are those who go for that approach.

Well, that's enough to put in your pipe for now. I'm not saying which
style you should develop. My own style has developed and changed over many
years. It has never conformed to Microsoft's (I got there first, lol). Many
others have different styles. You are just beginning to develop a style.
Ponder on it. Adapt it. Be consistent but prepared to change it when
necessary.

This applies to code layout as well. There's a bit that you did that I
particularly liked. It doesn't show well here so I'm going to edit it a bit.

Private Sub PlacePlayersMarker(.....) _
Handles TTT1.Click, TTT2.Click, TTT3.Click, _
TTT4l.Click, TTT5.Click, TTT6.Click, _
TTT7l.Click, TTT8l.Click, TTT9.Click

You broke the line <before> the Handles. This means that anyone looking at
the next line will immediately see it there. This leaves only one
interpretation for TTT1.Click - it is an event being handled. Had you left it
out, the next line would have started with TTT1.Click. Now is that an event
being handled or is it a method being called? It's only a small point but a
bit of careful thought can save someone tripping up. Some will say that that's
too trivial. [I call it subtle :-)]. As you develop your style and think about
all these "little points" you get to develop code which has a clarity that
will be appreciated without even being noticed.

Here's another example:
If tTheHouseIsOnFire And tTheresNoPhone And _
eDistanceToNeighbour = eDistances.TooFarToWalk Then
JumpInTheCarAndDriveLikeHell (GrabTheKeysOnTheWayOut())
vs.
If tTheHouseIsOnFire And tTheresNoPhone _
And eDistanceToNeighbour = eDistances.TooFarToWalk Then
JumpInTheCarAndDriveLikeHell (GrabTheKeysOnTheWayOut())

In the first case you see the assignment "eDistanceToNeighbour = ..." and
finally notice the Then at the end which makes you realise that it's <not> as
assignment.
In the second you see the "And" first and know immediately that it can't
be an assignment.

Subtle. Trivial. What do you think ?

Anyway, that's enough for now. :-)

All the best,
Fergus.

ps. You'll have noticed that I like long variable names and 'If ' statements
that read like a sentence.
 
I used mLabelCollection because my text, Programming with Microsoft Visual
Basic .Net by Diane Zak states on page 50, ... the naming convention in this
book records the object's purpose at the beginning of the name, and then
includes the object's type at the end of the name. Hence, TTT1Label
(TicTacToe/Position1in the grid/Label), mLabelCollection (m is for a
form-level variable; Label for the type of controls contained within the
Collection), objLabel (object variable that is for the addresses of Label
controls), etc., etc., etc.

The naming convention that you prefer to use (lblTTT1) is also preferred by
my instructor. My instructor began using Visual Basic before .Net.

Whether or not Diane Zak created the naming convention used in her book or
it is a new naming convention to go with .Net, I don't know.

I am beginning my Visual Basic knowledge with .Net. So, whenever I see
lblTTT1 versus TTT1Label, I believe the programmer came to Visual Basic .Net
after having experience with an earlier version of Visual Basic.

I used the mLabelCollection because I have another label on my form with
self identifying information for the instructor's need to distinguish each
student's work. Therefore, I need to separate my labels. I chose a
collection to do so.

thank you everyone for your help. i think i got it now. peace

Fergus Cooney said:
Hi again Stephen,

I wanted to make you look for meanings rather than me handing them to you
on a plate. Then I'd come back after to fill in any gaps. Best for learning
that way, even if it's a bit puzzling for you in the meantime. :-)

I mentioned the collection because it's just what you need in that reset
loop! It doesn't matter in this sort of program, of course, but I'm interested
in you learning principles as well as getting your code working.

Namely:
Having taken the trouble to create a collection containing <only> the
tic-tac labels, what do you do with it? And then when it comes to clearing the
labels, how many Controls do you check? That's one part of it. The other part,
which you wouldn't realise on your test setup, is that there may be other
labels on the Form, such as "Player 1", "Player 2". These would get wiped
too!! Oops.

Regarding the 'while' loop. I can assure you that it didn't work for me.
Not because I plonked it onto my form and messed it up, but because there was
a logic error in your code. That's why I asked about the equivalent 'for'
loop. I also wanted you to tell me whether your 'while' loop matches the 'for'
loop. (It doesn't - but why? Learning point: How 'while' and 'for' are not
always the same.)

strPlayer - presumably it was initially a string variable. Now it's a
Boolean. But a reader of your code will wionder - did he forget to change the
"str" to "t" (truth) or "f" (flag) or "b" (boolean) or whatever is your choice
for a Boolean. I've got no problem with your choice of a Boolean for a
two-state variable! But change the type and change the name is a handy habit
to develop early on.

In fact developing a style and becoming habitually consistent is very
important. I notice that you have the following:

strBoolean - lower-case type and capitalised type, but no name.
mLabelCollection m for member, capitalised type, capitalised name, but
only a sort of name.
objLabel - lower case type, but no name.
intx - lowercase everything
TTT1Label. - upper case name, capitalised type.

strBoolean - it's a Boolean give it a 't' (that's my style, many would
disagree, but 'b' and 'f' are already taken in my scheme). That says it all as
regards type. So what should its name be? Well, it controls whose turn it is.
It also controls which type of mark is made (X or O). Which is the central
concept? At the moment it's the mark. But, if later you decide to allow Player
1 to choose whether they'd like to be X or O, then it directly controls the
player's turn but only indirectly the mark - you'd use it to index an array of
Marks - one for each player. But that wouldn't work because it's a Boolean -
an integer would be better. So let's change it to, say, iPlayerToGo. And place
asMarks (iPlayerToGo) in the tic-tak grid. ["asMarks" is 'a', an array, of
's', strings, containing 'Marks' the marks made by the players. Or whatever
word you prefer.]

All that discussion over just a single variable. Is it worth it? Tell me
what you think.

mLabelCollection, TTT1Label, ObjLabel. These are all labels. It's common
to have control types abbreviated in lower case at the front. There's a
Microsoft recommended list somewhere in the Help. For labels you'd use "lbl".
Which gives us mlblCollection, lblTTT1 and lblObj. Still not there yet.

mlblCollection. Some people like to separate the 'm' with an underscore.
Now, what is it a collection of? Not labels. That's how whatever they are is
<implemented> but that's not what they <are>. They are in fact squares, or
places or whatever, on your tic-tac-toe board. Labels is a computery thing.
But your game is a human thing. Choose the human names over the computery
names. So that gives us "m_lblSquares". Note the use of the plural. This
indicates that it's not a single sqaure. Some people like to have "coll"
instead. "m_colllblSquares" or "m_collSquares" and who cares about the
labelness, or "m_alblSquares" because it's an array of labels.

Tomorrow you might rewrite your program using PictureBoxes instead of
labels. "m_collSqaures" would survive untouched. Anything with "lbl" would
have to be changed to "pic". [Remember strBoolean - that didn't survive the
change from string]. So a name that is implementation free can be better.
There are those who go for that approach.

Well, that's enough to put in your pipe for now. I'm not saying which
style you should develop. My own style has developed and changed over many
years. It has never conformed to Microsoft's (I got there first, lol). Many
others have different styles. You are just beginning to develop a style.
Ponder on it. Adapt it. Be consistent but prepared to change it when
necessary.

This applies to code layout as well. There's a bit that you did that I
particularly liked. It doesn't show well here so I'm going to edit it a bit.

Private Sub PlacePlayersMarker(.....) _
Handles TTT1.Click, TTT2.Click, TTT3.Click, _
TTT4l.Click, TTT5.Click, TTT6.Click, _
TTT7l.Click, TTT8l.Click, TTT9.Click

You broke the line <before> the Handles. This means that anyone looking at
the next line will immediately see it there. This leaves only one
interpretation for TTT1.Click - it is an event being handled. Had you left it
out, the next line would have started with TTT1.Click. Now is that an event
being handled or is it a method being called? It's only a small point but a
bit of careful thought can save someone tripping up. Some will say that that's
too trivial. [I call it subtle :-)]. As you develop your style and think about
all these "little points" you get to develop code which has a clarity that
will be appreciated without even being noticed.

Here's another example:
If tTheHouseIsOnFire And tTheresNoPhone And _
eDistanceToNeighbour = eDistances.TooFarToWalk Then
JumpInTheCarAndDriveLikeHell (GrabTheKeysOnTheWayOut())
vs.
If tTheHouseIsOnFire And tTheresNoPhone _
And eDistanceToNeighbour = eDistances.TooFarToWalk Then
JumpInTheCarAndDriveLikeHell (GrabTheKeysOnTheWayOut())

In the first case you see the assignment "eDistanceToNeighbour = ..." and
finally notice the Then at the end which makes you realise that it's <not> as
assignment.
In the second you see the "And" first and know immediately that it can't
be an assignment.

Subtle. Trivial. What do you think ?

Anyway, that's enough for now. :-)

All the best,
Fergus.

ps. You'll have noticed that I like long variable names and 'If ' statements
that read like a sentence.
 
Hi Valerie,

Yes, the important think is that you choose your stye and become
consistent with it.

Although it's necessay to conform to external standards sometimes, eg when
working in a company that has a defined policy.

Peace, too,
Fergus
 
Nak said:
I made an online tic-tac-toe, but it was in VB6 so I doubt it would

Do you have an algorithm for creating a computerized opponent? I've been
looking for one to study and have not been able to find one.

Chris
 
Do you have an algorithm for creating a computerized opponent? I've been
looking for one to study and have not been able to find one.

Hi,

Unfortunately my version wasn't as flash as that. But I shouldn't
imagine that it would be that hard to be honest with you. Maybe there are a
few on Planet Source Code,

www.planet-source-code.com

You'll find most under the "Visual Basic" section rather than the .NET
section.

Nick.

--
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
Slow internet connection?
Having problems with you job?
You're marriage is on the rocks?
You can't sleep at night?
You have a drink and drugs addiction?
You are sexually impotent?
Then enable Option Strict!
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
 
Back
Top