The general idea I had for the game is to have a little ship represented by two LEDs that could move in one dimension to avoid oncoming blocks. I wanted the blocks to come in randomly at intervals at 3 LED columns.
I created the program in the onReload function so that each time i pressed apply it would run.
First I set up the initial conditions of the game, such as the starting position of the ship and obstacles, as well as the end game cross.
For this project I found the WebSDK page helpful in configuring the breadboard block to constantly poll the joystick for data. By doing this I could continuously update the posx value that controls the location of the ship on the LED matrix.
The rest of the code goes through a continuous loop of:
- Updating the ship coordinates using the posx value.
- Checking for a collision between the ship and the obstacles
- Updating the LED block to show the new obstacle and ship positions
- Updating the obstacle positions
There is a counter i value that updates the state of the program. The reason for this is explained in the shiftObstacles function.
When a collision occurs the game will display an X and delay the game for 2 seconds before resuming again.
The shift ship function checks the joystick value as well as checking the current position, so that if you are already at the maximum/minum positions you can not increment out of the bounds of the LED display. If the conditions are met, the function will return the incremented position of the ship.
This function goes through 3 states: an add state, delete state and do nothing state. The diagram I’ve drawn below shows how each state works, where each row represents a state. For this example I have simplified the 8*8 matrix to a 1*8 array. Once an obstacle reaches the end of the screen it must be deleted, which is the “delete” state. As there is a two LED gap between each obstacle there is a “do nothing” state. And after it has gone through the “delete” and “do nothing” state it can add another obstacle randomly.
The collision function iterates over each element in the ship array and the obstacle array to check that there are no duplicate numbers. Since the LED array has a number corresponding to each position in the matrix, if there are duplicated numbers it means they are occupying the same position and have “crashed”. It will return a 1 if this has occurred, which will trigger the end of the game in the main function.
Some improvements that could be implemented in the future are:
-Add a score system by adding a finish line after a set number of rounds
-creating obstacles that move faster as the game progresses
-adding lives to the game
-allowing the ship to move in 2 dimensions.
-creating obstacles that move in diagonals.
-creating obstacles that move at different speeds.