When | Mood | Music |
2012-04-13 01:16:00 | anxious | the whirring of Iggy’s fans |
Lots of anxiety today: the condition to ensure my creatures didn’t move illegally gave rise to infinite loop after infinite loop. Having 4 sorts of creatures represented as integer values within grid-squares gave rise to LOTS of duplicated code. Aaarrggh!
I’d resisted coding the creatures as objects, despite the opportunity to show I understood inheritance (creature = ogre or enemy; enemy = donkey, parrot or snake) because I feared that there would be a class between the creatures having coordinates and the grid-squares having coordinates. The creature would have to get its coordinates from the grid square in which it currently resided. But while moving, it would have no source of coordinates. Worse, how would a creature tell a grid-square “I’m moving in – increment your count of my type of creature!”?
It struck me today that there may be no need for formal coding of grid-squares. If the creatures know and can change their own co-ordinates on command, then so long as they can’t move past the upper or lower bounds of the swamp, then things should work – or so I thought.
On its own, code of the form works.
public static void move(int size, int Coord) {
double decider;
int limit = size – 1;
do {
decider = Math.random();
if (decider < 0.5) {
Coord = Coord – 1;
} //end if
else Coord = Coord + 1;
} while (Coord < 0 || Coord > limit);
} //end move
The while condition says ‘keep trying while the co-ordinate is negative or past the upper limit’.
But try as I might, putting this into the code for a creature didn’t work – in fact the IDE came perilously close to choking Iggy.
So I’m doing it in a klutzy, non-satisfactory way:
- If the current coordinate is 0, it’s then either unchanged or increased by 1.
- If the current coordinate > 0 and < limit, it’s then decreased by 1, unchanged or increased by 1.
- If the current coordinate is at the upper limit, it’s then decreased by 1 or unchanged.
To make an actual move, I run through the above process twice, once for x-direction and once for y-direction.
To ensure there is some movement, I find the x-distance travelled and the y-distance travelled: if both of these are zero, a boolean is set to ‘false’. The ‘make a move’ code is wrapped in a do/while loop which forces the code to be repeated until the boolean becomes true.
So now I can add an ogre to my program at a random place and a random choice of enemy at coordinates (0,0). Tomorrow I aim to have the game mechanism set up: this starts by placing an ogre at random. The luser is asked if another turn should occur. (If not, the game will quit.) At the start of each turn, all creatures already present move, then there is a finite chance of a new enemy turing up at (0,0).
After that, it’s just a matter of being able to serialise the game state so it can be saved, creating a set of tests and drawing UML diagrams.