You’ve seen how objects combine state and behavior, and how we can construct them and protect their private state. In this lesson we’ll put all of those capabilities to use in modeling a real-world entity! After all, that’s one of the things that objects are for…
First, as a warm-up, let’s construct the imperative logic that we need to check the board. We’ll then use this later in our solution!
Declare and implement a function called
gameOver receives a single 3x3
Array<CharArray> as a parameter, representing a tic-tac-toe board,
with each cell containing either a
O, or a
gameOver should return
X has won the game,
O has won the game, and a blank space (' ') otherwise,
including in the case of ties.
(Ties should probably be handled differently, but you can use a ' ' for now.)
Do not check the diagonals!
For those unfamiliar with Tic-Tac-Toe, here is link to the rules: https://en.wikipedia.org/wiki/Tic-tac-toe.
As our example we’ll model a game of tic-tac-toe. Whenever we model something using a Kotlin class, we want to consider:
Note that frequently these considerations overlap. We may need to add state to support some action that we realize that we want our class to support. But, anyway, we’ll get there. Let’s get started!
But before we can even start designing our class, we need to choose a name! That’s not as simple as it sounds! Frequently deciding on a name can encourage you to give some initial productive consideration to exactly what it is that you’re modeling…
First, let’s think about what a
class modeling a tic-tac-toe game needs to store.
Let’s work through that together and begin designing our classes instance variables:
With an initial set of instance variables, let’s think through various things that we want our game model to be able to do. This is not a complete list! You may have other ideas of what to add:
Now let’s have some fun implementing these features! Note that, as we go, we may find places where we need to add state, or create some helper functions. We’ll see!
Define a public class named
Counter with a single public instance method named
increment takes no parameters and returns an
The first time it is called it should return
0, the next
1, the next
2, and so on.
Each instance of
Counter should maintain its own counter.
Cool! You designed and implemented your first interesting Kotlin class. That was fun! Don’t worry—you’ll get a lot more practice, starting with this lesson’s homework problem.
Create a public
Restaurant should store two pieces of data: a name (as a
String?) using the property
and a capacity (as an
Int) using the property
Provide a constructor that allows both fields to be set, with the name first.
Design your class so that it provides both a setter and a getter for the capacity but only a getter for the name.
Finally, reject negative and zero capacity values and
Need more practice? Head over to the practice page.