Skip to content

Chapter 5

Informations presented on this page may be incomplete or outdated. You can find the most up-to-date version reading my book Learn Swift by examples. Beginner level

What we will do:
In this part we will implement methods checking win conditions. After implementig whole game logic finaly we will be able to play the game.

In this part we cover the following topics

Source code for this chapter.

EngineGameBattleship class modification

Add to EngineGameBattleship class three private properties to keep information about board dimension and sizes of ships used during the game

and modify accordingly initializer

To make playing game possible we need a method used to check if there is a winner and, if the answer is yes, who is this.

Next let's implement a very simple shooting method. In this case we try maxTries to find an accpetable cell (that is a cell we may shoot on). If we fail, we systematicaly, row by row and column by column, search until we find acceptable cell.

Because previously implemented method mayShot(row: Int, col: Int) -> Bool is defined in Board class, we need a boilerplate method to call it.

This simple method uses getWhoTarget(who: Who) -> Who method to get current player's opponent so we can get current player opponent's board

Knowing that shot is possible, we can shoot

Last thing left to implemented to make our engine usable is a boilerplate mathod calling shiop auto-layout metod from Board

Last step

At this moment our engine is ready, and we can try to use it to play the game. All the changes from this section are about main file.

First let's add some variables.

  • Array with sizes of the ships
  • An instance of our game engine
  • If ships auto-layout for an opponent (computer) succeeded
  • If ships auto-layout for a player (human) succeeded
  • Indicating whos turn is now
  • Player's or opponent's shot coordinates

Now we can implement main game loop

Almost ready but we have to add two methods to get shot coordinates from human player. Add the following methods just after import Foundation

Now we can run our code. Ships for player (human player) and his opponent (computer player) should be automaticaly arranged on game boards. Both players should have 10 ships. To make debug possible, both boards are printed on the screen.