On this tutorial we will cover how to create a custom victory rule for our game, so to make it clear we will create a very simple game:
This game has the following rules:
- Red starts.
- Only one turn per player.
- You can only move to adjacent cells.
- You can’t capture enemy pieces.
- You win when you have a piece has three or more pieces of the same color in neighboring cells.
This last condition is not a common game rule, so we will make a script to validate this condition and make the game end when it happens.1Configure the game board as shown in the image above, and make sure your pieces have a “Relative Move Rule” Script with 8 relative valid directions:
We will also use a Canvas Text to show a message when the game end. To know how to do this refer to this tutorial.
Make a new script that will drive the game (YourOwnVictoryRule), and add it to the GameBoard Also add a VictoryOtherPlayer component to the game board, which is a default victory condition that can be configure to make a player lose if the other wins like this:
2Implement the custom victory rule class, and call it CustomVictoryRule and add it to the game board. Make it extend from VictoryRules and use a RectPoint and GridGamePieceSettings class as types:
public class CustomVictoryRule : VictoryRules<RectPoint, GridGamePieceSettings>
Implement the the CheckVictory method with the rule. To do this, iterate over every point on the board using “currentState.GetAllPoints()”. If the cell is not empty and if the piece belongs to the current player, then we count how many neighbors of the same type the piece has. If we count 4 then we set the current player as a winner with the following line.
Since we use the “Victory Other Player” script, making a player win means the other player lose, and this make the game finish.
Try out the game and change the number of pieces, add piece to the board and see how it all behaves.
To check out this example:
- Import Abstract Strategy in a new project.
- Import the package below into the same project.
- Open the YourOwnVictoryRules scene.