I’m writing a simple command-line board game in Ruby. I need to have main game code and then independent code for the two players that are going to be written by two different people or teams. So the main game needs to allow different players to play without changing any code.
I’ve been thinking of ways to do this, but this is the biggest programming project I’ve ever undertaken and I frankly don’t have a good Idea yet.
Should both player-programms define a method that the main game calls? Should I have a Player class and have the player-Programms subclass it? I tried a few things but it never seems to be what I was looking for or what would be considered even decent design.
What would be a good way to do this in Ruby (or any other language, as the problem is a general programming problem)?
I hope I was able to phrase the question correctly.
I’d say that the subclass approach sounds good (in other languages, interfaces might be a better choice, but I don’t think interfaces exist in Ruby). The method that each player class must implement should take as a parameter an object that contains the entire game state (such as the piece positions if you are making chess). This object must be read-only or must be a copy of the game state, so that the player classes may not directly alter the game state. Instead, the method that the player classes must implement should return some value that indicates what move the player wishes to do. I suppose that Ruby supports some mechanism to dynamically instantiate a class from another file based on the names of the class and the file. You could start the game like this, using parameters to indicate the file and class names:
The game would probably look like this pseudocode:
With this approach, you can write the core game code once and launch it without modification with any pair of player classes.