Computer Science Canada Tic-Tac-Toe |
Author: | rdrake [ Fri Dec 09, 2005 11:27 pm ] | ||
Post subject: | Tic-Tac-Toe | ||
Kinda messy code, but it works well. It's your basic tic-tac-toe game. Not much variation, just works the way it's suppost to.
|
Author: | wtd [ Fri Dec 09, 2005 11:53 pm ] |
Post subject: | |
Now, rewrite it with some thought to separating logic and display code. |
Author: | wtd [ Fri Dec 09, 2005 11:56 pm ] | ||||||||
Post subject: | |||||||||
Some simple things while you ponder that...
Replaces:
Can be:
|
Author: | wtd [ Sat Dec 10, 2005 12:18 am ] | ||
Post subject: | |||
It's worth noting that you don't need three separate "row" variables. You can easily have:
|
Author: | rdrake [ Sat Dec 10, 2005 8:37 pm ] | ||
Post subject: | |||
wtd wrote: Now, rewrite it with some thought to separating logic and display code. What exactly do you mean? Can you provide an example. I'm fairly new to Ruby still.
Here's a version with nicer classes instead of just random code.
|
Author: | wtd [ Sat Dec 10, 2005 8:44 pm ] | ||||||||||||
Post subject: | |||||||||||||
cartoon_shark wrote: wtd wrote: Now, rewrite it with some thought to separating logic and display code. What exactly do you mean? Can you provide an example. I'm fairly new to Ruby still.Thinking about tic-tac-toe, we have a 3x3 grid. We can easily represent that in Ruby as an array of three arrays. Elements in the array can have one of three values. The possibilities are X, O and Empty. They should all start off empty.
Now, we'd want to print this. So, let's define a new method to do this. Except we'll make it a bit more general and just have this generate a string representation of the board.
Now when we want to print a board, we can write:
But that's pretty redundant, so let's turn Board into a class. The initialize method will do the setup for us. The to_s method will do the same as our board_to_s method.
And now we can:
And get:
This is possible because the puts method automatically calls the to_s method on an object, and the new method of the Board class creates a new Board object. |