Building My First Custom Game Development PC

I have never owned a non-Apple computer in my life. The first computer my parents bought was an Apple ][ back in 1984. No, we didn’t buy a Mac.

Over the years I have found trying to purchase a PC to be overwhelming. Choosing a manufacturer, building your own, picking the parts… Couple that with the price of GPUs now that people have discovered Blockchain, it’s always just been easier to pick the most powerful Apple computer I could afford.

But it’s always bothered me that there are games and programs that only work on PC. It’s annoying to constantly get a look of pity when I ask if X technology, like VR, works on Mac.

I decided at the beginning of the year that I really want to make a go of doing game/graphics/ML programming. I need the right tools to work with these technologies. This blog post is about how I built my first computer.

Backstory

I told The Fiancé several months ago that I wanted to build a game development workstation for VR. For us, the biggest question was what GPU we were going to use. Everything else would work around that.

In March of this year The Fiancé won a trip to NVIDIA’s GPU Technology Conference (GTC). I had finished my book on Metal but was having trouble finding anyone in the iOS community who needed a GPU programmer. I wanted to see what things were like on the other side and to see what other options I had in this field, so I made him take me with him.

On the show floor, they had a VR exhibition. I wanted to get a bunch of pictures for a blog post I never wound up writing, so I asked The Fiancé to get some pictures of me in front of the Holodeck. Someone working the Holodeck noticed and asked if I wanted to use their photo booth. I got a few goofy pictures taken with my service pug. The guy working the photo booth gave me my photos and told me I should post them to Twitter because they were running a contest. I entered the contest with this picture and kind of forgot about it.

Ready Puggle One

A month after we got home, I got a notification from NVIDIA that I had won their contest. The prize package included the new HTC Vive Pro and an NVIDIA Quadro P6000 GPU.

The GPU wound up being worth four times as much as the rest of the computer. I am grateful to NVIDA for their assistance to me in getting my VR development environment up and running.

Components

We didn’t order the computer parts until we had the GPU because I was afraid I would forget to respond to an email and lose the GPU and I wouldn’t believe it was real until I had it in my hands. The GPU arrived about a week before I had to leave for WWDC.

The Fiancé asked me what I wanted for components for the computer. I know nothing about this stuff because I have never done this before, so I told him I wanted the computer to look like a unicorn puked all over it. I wanted it to be pink and sparkly but also powerful.

From that directive, The Fiancé helped put together this part list:

Word of warning! We accidentally purchased the wrong variant of mother board that did not have WiFi and we had to purchase a separate WiFi card to place in the computer. I asked why they wouldn’t all just come with WiFi and The Fiancé said a lot of people who do intense online gaming need reliable high bandwidth Internet access and that isn’t WiFi. So if you’re like me and just want access for like email or whatever, be sure to get the right motherboard!!

Assembly

One thing I absolutely wanted in regards to this computer is that I wanted to assemble it. I wanted some assistance from The Fiancé because he’s done this before and I didn’t want to break a thousand dollar plus component out of ignorance. But I wanted to do most of the work. When I was a kid my dad would insist upon “helping” me with various projects and would not let me do anything I wanted to and so I have a lot of bad memories of trying to do projects with my dad.

The first thing we did was install the power supply:

Next, we installed the SSD:

Then we had to assemble the components that compose the motherboard:

This included the CPU:

And the RAM:

Next we had to apply the liquid cooler to the CPU:

At this point we had to string a bunch of cables. The Fiancé helped me with this task and gave me some eye candy:

Last, but not least, we installed the special GPU:

Conclusions

It was really interesting to actually put a computer together from parts. I am grateful to both NVIDIA and The Fiancé for making my computer possible. I was sad I didn’t get to play around with it before I went to WWDC. I am trying to make sure I make the best use of the windfalls I have benefitted from.

Tic Tac Toe: Creating Multiple Views/Scenes

This game is coming along well as a sample project, but not as a real game. There are things I expect as a player when playing an actual game I bought on the App Store. One of those things is having more than one screen. You usually have a main menu screen, a settings screen, etc…

I don’t want to go overboard on this project, but I do want this to look like a real game. The point of this exercise was to take a simple set of requirements and execute them fully. For me a minimum viable product would have at least a main menu scene. I have other ways I would like to handle a game ending, but I am behind schedule on this project and I don’t want to get stuck polishing it forever when a simpler solution will suffice.

I want my game to have the following scenes:

  • Main Menu
  • Variant Menu
  • Main Game Scene (already created)
  • Game Over Scene

The main menu should be simple. You tap on it and it brings you to the menu where you choose what variation of tic tac toe you want to play. This leads to the main game scene where you play the game. After the game ends one way or another, this leads to a final game over scene announcing how the game ended. After a set period of time, this reloads the main menu.

SpriteKit Scene Editor

When all of this stuff was in an immutable single scene, placing objects programmatically made a modicum of sense. But right now I want to place objects as I would if I were doing a traditional iOS app. I want to create a better UI for menus and asking questions. I don’t generally do my UI in code because it’s difficult to debug. I was trying to figure out how to create buttons and layouts and was starting to freak out. At this point I am bringing in the SpriteKit scene editor.

The scene editor is SpriteKit’s version of storyboards. They provide a WYSIWYG interface for laying out game elements. This makes all kinds of sense. Games are even more visually intensive than normal UIVew based applications. I find storyboards invaluable for laying out my UI elements. Not having something like this would be idiotic.

Game Over

I actually created this one first. I have been working through the 2D games book published by Ray Wenderlich’s company. They created both the main menu and the game over menu programatically. Neither required any user interaction beyond tapping the screen or waiting. I have put myself on a personal deadline of wanting to ship this project before Sunday, May 6th. There are a lot of more custom interactions I would like to add, but I need to see if I have time or not. This is minimum viable product time.

I originally intended to custom create different end scenes based on the winner of the game, but I started to get discombobulated by trying to figure out how to adjust things for different screens. I also realized this was inherently limiting and that I could use animations if I did everything in code.

First I need my properties that are going to be used to determine how this scene looks:

import Foundation
import SpriteKit

class GameOverScene: SKScene {
    let endState:GameEndState 
    let background = SKSpriteNode(imageNamed: "bg_ipad_portrait")
    let label = SKLabelNode(fontNamed: "Noteworthy-Bold")
    var iconNode = SKSpriteNode()

I need the end state to know who won the game or if it was a draw. I need to set the background as I did for all the other scenes in the game. I need a label showing who one. Lastly, I need an icon representing the winner.

I need to initialize these properties:

init(size: CGSize, endState: GameEndState) {
    self.endState = endState
    super.init(size: size)
		
    isUserInteractionEnabled = false
		
    anchorPoint = CGPoint(x: 0.5, y: 0.5)
		
    background.zPosition = -1
    addChild(background)
		
    let labelBackground = SKSpriteNode(
        imageNamed: "headerBacking")
    labelBackground.zPosition = 2
    labelBackground.size = CGSize(
        width: self.size.width, 
        height: 60.0)
    labelBackground.position = CGPoint(
        x: 0.0, 
        y: (self.size.width / 2.0) + 100)
    labelBackground.anchorPoint = CGPoint(x: 0.5, 
                                          y: 0.5)
    addChild(labelBackground)
		
    label.fontColor = SKColor.black
    label.fontSize = 40
    label.zPosition = 10
    label.position = CGPoint(x: 0.0, y: -20.0)
    labelBackground.addChild(label)
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

I need to set the winner label and the icon based on what game state is passed in:

override func didMove(to view: SKView) {
		
    switch endState {
	case .playerAWin:
	    iconNode = SKSpriteNode(imageNamed: 
                "pastry_donut_320")
	    label.text = "Player A Wins!"
	case .playerBWin:
	    iconNode = SKSpriteNode(imageNamed: 
                "pastry_starcookie02_320")
	    label.text = "Player B Wins!"
	case .draw:
	    iconNode = SKSpriteNode(imageNamed: 
                "pastry_starcookie02_320")
	    label.text = "Draw"
    }

I already had actions for animating a sprite into the scene that I could reuse for the game ending scene:

    let spritePosition = CGPoint(x: 0.0, y: 0.0)
    let spriteSize = CGSize(width: 320, height: 320)
		
    // Actions
    let fadeAction = SKAction.fadeIn(withDuration: 0.75)
    let scaleUpAction = SKAction.scale(to: 
	CGSize(width: spriteSize.width * 
	1.5, height: spriteSize.height * 1.5), 
	duration: 0.5)
    let scaleDownAction = SKAction.scale(to: spriteSize, 
                                   duration: 0.25)
    let soundEffect = SKAction.playSoundFileNamed(
	"pop.wav", 
	waitForCompletion: false)
    let scaleSequence = SKAction.sequence(
	[scaleUpAction, soundEffect, scaleDownAction])
    let actionGroup = SKAction.group(
        [fadeAction, scaleSequence])
		
    iconNode.setScale(0)
    iconNode.position = spritePosition
    iconNode.zPosition = 10
    addChild(iconNode)
    iconNode.run(actionGroup)
		
    let wait = SKAction.wait(forDuration: 5.0)
    let block = SKAction.run {
	if let scene = SKScene(fileNamed: "MainMenuScene") {
	    let reveal = SKTransition.flipHorizontal(withDuration:0.5)
	    self.view?.presentScene(scene, transition: reveal)
	}
    }
    self.run(SKAction.sequence([wait, block]))
}

This scene basically hangs around long enough to display the current winner. Then, after a sufficient amount of time, it navigates back to the main menu to allow the user to begin a new game.

This was a bit more code that I particularly wanted to have to maintain. One goal on this learning project was to try and get things done faster, so for the future scenes I wanted to try and take advantage of the SceneKit Editor.

Main Menu

I had an idea about how I wanted the main menu laid out, but I didn’t want to have to do this in code. Since I only need the user to tap on the screen, I just wanted to get things generally laid out.

I created a MainMenuScene.sks file along with a MainMenuScene.swift file. All of the graphics and UI stuff will be laid out in the .sks file while all of the user interactions and behaviors live in the .swift file.

I laid out the main menu to look like this:

Scene editor, very much like Interface Builder

For a while I could not get this to load and I couldn’t figure out why. I had forgotten that in IB and the Scene editor you need to connect objects to their correlating class. So be sure to set your scenes/custom nodes/etc… to their correlating class in the Inspector.

The only think I need the main menu to do is listen for a touch. If the player touches the screen, I want it to launch a new game. Here is the code for this:

import Foundation
import SpriteKit

class MainMenuScene: SKScene {
	
    override func didMove(to view: SKView) {

    }
	
    func sceneTapped() {
	let myScene = GameScene(size: size)
	myScene.scaleMode = scaleMode
	let reveal = SKTransition.doorway(withDuration: 1.5)
	view?.presentScene(myScene, transition: reveal)
    }
	
    override func touchesBegan(_ touches: Set,
	with event: UIEvent?) {
	sceneTapped()
    }
	
}

Choose Variation

For my variations scene I want the same background as the rest of the application but I want three buttons. SpriteKit doesn’t have SKButton objects. So far my understanding of how SpriteKit works is that everything is a node. I need three nodes with textures that look like buttons indicating each variation. I need to name them so that I can use touch recognition to see which version the player chose.

The class needs to keep track of which version of tic tac toe the user wants to play. I created a new enum to hold these values:

enum GameVariation {
    case normal
    case reversed
    case swap
}

Right now these are not doing anything. The last feature I want to add to the application is the ability to actually have different rules and functionality for these variations. Right now, this is basically a stubbed out method:

import SpriteKit
import GameplayKit

class TypeChoiceMenu: SKScene {
    override func didMove(to view: SKView) {

    }
	
    // Check for node type and pass into the initializer
    func sceneTapped(_ type: GameVariation) {
	// Update GameScene init for game type
	let myScene = GameScene(size: size, variation: type)
	myScene.scaleMode = scaleMode
	let reveal = SKTransition.doorway(withDuration: 1.5)
	view?.presentScene(myScene, transition: reveal)
    }
	
    override func touchesBegan(_ touches: Set,
	with event: UIEvent?) {
		
        guard let touch = touches.first else {return}
	let location = touch.location(in: self)
	let rawNodes = nodes(at: location)
	let tappedNodes = rawNodes.filter{return $0.name != nil}
		
	guard let node = tappedNodes.first as? SKSpriteNode else {
            return
        }
		
	switch node.name {
	case "RegularButton":
	    sceneTapped(.normal)
	case "ReverseButton":
	    sceneTapped(.reversed)
	case "TileSwap":
	    sceneTapped(.swap)
	default:
	    break
	}
    }
}

As with the code to check which tile is tapped in the main game, this checks the node name of the buttons in the scene. If one is selected, then it triggers a load of the main game scene and passes that choice along to the scene.

Conclusions

This wound up being a bit harder than I expected. After having done a few scenes in the editor, I am wondering why I didn’t do this sooner. However, when I first started this feature I was incredibly frustrated by the editor and wanted to scrap my plans to use it.

Sometimes you need to work through something that seems difficult or counterintuitive in order to find a better way to do things. If I had to do this project over again I would set up the entire game in the scene editor.

The final feature I want to implement before I declare this project ready to ship is a few variations on tic tac toe to make this game slightly more interesting. Playing through this I keep seeing more and more refinements I would like to make to this project, but the point of this was to get something done and to ship it. I don’t want to get sidetracked endlessly refining this learning project rather than moving on to a more complex project.

So far there has been a lot more to this game that I anticipated when I started. But part of the point of this was to work on all the non-obvious stuff. Until next time!

Tic Tac Toe: Implementing Artificial Intelligence

There are a few ways to implement turn based games as apps. You can either set up networking to play against a live opponent or you can set up an artificial intelligence to play against.

I am working under the assumption that no one is ever going to be super eager to play against a live opponent in tic tac toe, so the best option for a minimum viable product is to implement an AI. Setting up a network for live gameplay is a goal I have for my next project, but it’s overkill for this prototype project.

I want to make the AI good enough as opposed to perfect. It’s no fun playing tic tac toe where you can’t ever win. But it is also important that the AI behave somewhat logically, as opposed to these people.

GamplayKit AI

In 2015, Apple introduced a framework called Gameplay Kit. This framework took a bunch of commonly used concepts in game development and abstracted them out into a framework that could be used universally across the SDK instead of marooning it in either SpriteKit or SceneKit. The randomization algorithms are incredibly popular for applications outside of games.

One of their modules within Gameplay Kit is a set of strategists for opponent AI. The two strategists allow for both deterministic and probabilistic opponent gameplay to be added easily to a game.

I am opting not to use Apple’s built in AI implementation. I have two specific reasons for doing so:

  • I would have to refactor my application: Gameplay Kit was specifically designed around strong object oriented programming principles. In order to utilize any of Apple’s strategists, you have to have an object representing the game model, the player, and the game update. Right now, I am handling all of these things with stand alone functions and enums. In order to take advantage of Apple’s framework I would need to add a bunch of classes and code to my project and it is my personal preference to not do this.
  • I want to understand the math: I am interested in having an understanding of the math behind various strategists. In the next game I want to implement, I would like to be able to roll custom AIs based on various criteria to give virtual players their own personality. Even if that goal is unrealistic or could be accomplished using one of Apple’s built in classes, I want to gain the understanding of how this works by building it on my own.

The remainder of this post will be explaining the strategist algorithm I want to implement and how I was able to integrate it into my existing gameplay.

MiniMax Algorithm

One of the foundational algorithms in AI is the Minimax algorithm. This isn’t a “true” AI as it’s simply a decision tree generated algorithmically. This algorithm was the original AI strategist available when GameplayKit was introduced. It’s still the basis for most AI for games with “perfect” knowledge. Perfect knowledge means that everyone involved in the game knows everything about it. Poker does not involve perfect knowledge because each player only knows the cards they have in their own hands and there is an element of randomness associated with how the cards are dealt. Chess, checkers, and tic tac toe have perfect knowledge because all the pieces and moves can be seen and known by each player.

I based my implementation of the Minimax algorithm from the chapter on adversarial search in Artificial Intelligence: A Modern Approach, Second Edition.

The normal MiniMax decision tree is exhaustive, generating every possible outcome of any given game. This becomes overly complex for even a simple game like tic tac toe. Apple gets around this by allowing you to set a depth for the tree based on number of moves it has to plan ahead. The more moves you plan ahead, the better your AI will be, but each level grows the time exponentially.

This shows MiniMax in a pared down state to give the general idea of how it is implemented.

In order to implement an AI for a board game, you need the following pieces of information:

  • The current state of the board
  • A dictionary of legal moves along with their resulting board state
  • A test to determine if the game has ended (reached terminal state)
  • A payoff function that assigns values to terminal states. In a zero sum game like checkers the states would be +1 for a win, -1 for a loss, and 0 for a draw.

I am already tracking the board state for the UI and game logic and I already have a function checking for a win or a loss. I can reuse these but I still need to add a dictionary of legal moves/state and how to calculate those values.

Modifying the Algorithm in Swift

One of the main features of the MinMax strategist is that it builds decision trees multiple moves ahead. This is great and useful for games like chess where there are a vast multitude of contingencies that the players must keep track of. However, tic tac toe has a maximum of nine moves total. If you’re playing the game properly then no one can ever win. I want to create an AI that plays properly most of the time but doesn’t always play perfectly strategically.

When I play tic tac toe, I go through three levels of processing:

  1. Can I win on this move?
  2. Could my opponent win on this move?
  3. Outside of those outcomes, what is the best strategic move I can make?

My optimal move is to win the game on this move. If that is not possible, then my next best move is preventing my opponent from winning on this turn. After these possibilities are exhausted, there are some moderately strategic moves you can make. If you’re going first, it makes the most sense to squat on the center square. If you’re not going first, then choosing a corner tends to give you more options and opportunities.

I don’t really want my AI to be as sophisticated as a human player because it would be nice to win every once and a while. While creating my decision tree, I wanted to preserve the first two questions as the game would be idiotic if I didn’t. If you can neither win nor lose on this turn, then I wanted to add an element of randomness where the AI simply chooses an empty square. This introduces enough of an opening for the AI to play badly enough that the human player may be able to win every once in a while.

Integrating the Algorithm Into the Project

First up, I want to figure out whether a particular move is a good move or not. If a move results in me winning, that’s awesome and I want that to have a positive value. If a move results in my opponent winning, that’s kind of a bummer and I want to assign that a negative value. If the move doesn’t really impact things one way or another, then I don’t really care and it has a neutral value.

func moveState(currentPlayer: GameState, 
                currentBoard: [TileState], 
			move: Int) -> Int {
    var moveValue = 0
	
    let newState = makeMove(tile: move, 
                   currentPlayer: currentPlayer, 
                           board: currentBoard)

    guard let isWin = checkForWin(currentPlayer: currentPlayer, 
                                          board: newState) else {
        return moveValue
    }
	
    switch isWin {
    case .playerAWin:
	moveValue = -1
    case .playerBWin:
	moveValue = 1
    case .draw:
	moveValue = 0
    }
	
    return moveValue
}

The return value of this function will act as the value for our state dictionary. We’re going to create that next.

We now need our key to go with its value. The key is going to be the index of the move we are making. This allows us to keep track of which tile we are actually changing. We also need to make sure we are only checking valid moves. Finally we need to return a dictionary of valid moves and their correlating values:

func possibleMoveValues(currentPlayer: GameState, 
                         currentBoard: [TileState]) -> [Int:Int] {
    var moveValueTable = [Int:Int]()
	
    for (index, tile) in currentBoard.enumerated() {
	if tile == .notSelected {
	    let moveValue = moveState(currentPlayer: currentPlayer, 
                                       currentBoard: currentBoard, 
                                               move: tile.hashValue)
	    moveValueTable[index] = moveValue
	}
    }
	
    return moveValueTable
}

Finally, we need a way to make an AI move. We can utilize the function we already created for the player making a move. But in this case, instead of checking for a touch from the UI, we are generating it using the previous methods:

func makeAIMove(currentPlayer: GameState, board: [TileState]) -> ([TileState], Int) {
    var newBoard = board
    var move:Int
	
    let possibleImmediateWinValues = possibleMoveValues(
        currentPlayer: .playerB,
        currentBoard: board)

    let possibleImmediateLossValues = possibleMoveValues(
        currentPlayer: .playerA,
        currentBoard: board)
	
    if let immediateWin = possibleImmediateWinValues.
        filter({$1 == 1}).first {
	move = immediateWin.key
    } else if let immediateLoss = possibleImmediateLossValues.
        filter({$1 == -1}).first {
	move = immediateLoss.key
    } else {
	let possibleMoves = Array(possibleImmediateWinValues.keys)
	move = possibleMoves[Int(
               arc4random_uniform(UInt32(possibleMoves.count)))]
    }
	
    newBoard = makeMove(tile: move, 
               currentPlayer: currentPlayer, 
                       board: board)

    return (newBoard, move)
}

First I am creating a new board and a move value for our return tuple. We will be populating those later in the function.

Next, I am running the possibleMoveValues method twice, once for each player. The way I structured the possibleMoveValues method was to check for a specific player’s move. Based on how I structured checkForWin, it only checks against the current player, which is passed in as a parameter. This means that by passing in Player A as a parameter, you will only check for wins for Player A. To get the wins for Player B, you need to run the method again to check for those results. I know, this is complicated and I probably could have written this differently, but that had its own complexity. Every method has tradeoffs.

Next we need to check for wins and losses. We have a preference for a win for Player B, so we check the dictionary for any values that equal 1. Once we find one, we don’t care if there are any more because a win is a win. If a win value is found, we set our move to that.

If there are no wins possible, we check for the next best thing, which is preventing our opponent from winning. We check for a move that our opponent could make to win and if one is found, we make that move to block them from winning. Again, we don’t care if there is more than one winning move for our opponent because if there is, we can’t prevent it anyway.

If nothing we do immediately results in a win or a loss, we simply choose a random square as our move. This allows just enough wiggle room that it’s possible that the AI may choose a really poor strategic value.

So we have a new board and the index of the tile that needs to be changed. This needs to be updated in the UI.

Updating and Modifying the UI

Right now, we are assuming that both players are humans and are swapping the phone back and forth. We update the UI as follows:

if board[tiles.index(of: node)!] == .notSelected {
    switch currentPlayer {
    case .playerA:
	let playerTile = SKSpriteNode(imageNamed: "pastry_donut_320")
	playerTile.setScale(0)
	playerTile.position = spritePosition
	node.addChild(playerTile)
	playerTile.run(actionGroup)
	board[tiles.index(of: node)!] = .playerA
    case .playerB:
	let playerTile = SKSpriteNode(imageNamed: "pastry_starcookie02_320")
	playerTile.setScale(0)
	playerTile.position = spritePosition
	node.addChild(playerTile)
	playerTile.run(actionGroup)
	board[tiles.index(of: node)!] = .playerB
    case .notPlaying:
	node.color = UIColor.white
	board[tiles.index(of: node)!] = .notSelected
    }
}

Basically we have a Player object that tracks the current player. This is used to determine what cookie goes on a tile and who is winning. We don’t want to keep this switch statement any more because we want a move to happen automatically after the player is able to successfully complete a valid move. This requires us to disable user interaction until after the AI has completed its move and to replicate the animation on the tile chosen by the AI.

I updated this section of the code to look like this:

if board[tiles.index(of: node)!] == .notSelected {
    isUserInteractionEnabled = false
			
    // Human player's turn
    let playerTile = SKSpriteNode(imageNamed: "pastry_donut_320")
    playerTile.setScale(0)
    playerTile.position = spritePosition
    node.addChild(playerTile)
    playerTile.run(actionGroup)
    board[tiles.index(of: node)!] = .playerA

This part concerning the human player’s turn is mostly untouched. I simply pulled it out of the switch statement and put it directly in the block. It is being run if the player touches a tile that isn’t already selected. Next, I need to check if the player has won:

// Check for Human Player Win
if let isWin = checkForWin(currentPlayer: currentPlayer, board: board) {
    label.text = isWin.rawValue
    return
} else {
    currentPlayer = switchPlayer(currentPlayer: currentPlayer)
    label.text = "\(currentPlayer.rawValue)'s Turn"
}

If the player has won, we don’t want the AI to make a move. If the player has not won, we still want the UI to update to reflect the current player. Next, I had to modify the code used for the player’s move to work for how the AI is functioning:

    // AI's turn
    let aimove = makeAIMove(currentPlayer: currentPlayer, 
                                    board: board)
    board = aimove.board
    let aiTile = SKSpriteNode(imageNamed: "pastry_starcookie02_320")
    aiTile.setScale(0)
    aiTile.position = spritePosition
    tiles[aimove.move].addChild(aiTile)
    aiTile.run(aiActionGroup)
			
    if let isWin = checkForWin(currentPlayer: currentPlayer, 
                                       board: board) {
	label.text = isWin.rawValue
    } else {
	currentPlayer = switchPlayer(currentPlayer: currentPlayer)
	label.text = "\(currentPlayer.rawValue)'s Turn"
	isUserInteractionEnabled = true
    }
}

Instead of getting the chosen node through touch and then updating the game board, we are running a method that selects a move and returns a new board state. We need to set that board state to be the new board state. We also have to use the index of the move to tell the UI which tile to update. I added a new SKAction to wait a second before implementing the animations to make it look like the AI is thinking about the move.

Again, we need to check for an AI win. If the AI wins, we again show in the UI that the game has finished. If the game hasn’t finished, we need to switch the current player back to the human and reenable touch so that they can make their next move.

Conclusions

This blog post took a while to get done. I had a lot of travel and I had a rough couple of weeks recovering from travel. I find getting off of my routine makes it difficult for me to motivate myself to get things done. So that isn’t really part of the code, but it is part of my life. I have to do a lot of things to curate my mental health and when I don’t I am not able to get things done. I am trying to do better at self care so that I can get things done and feel good about it.

I think if I were doing a more complicated game than tic tac toe the Minimax algorithm looking more than a move ahead would work well. I have feelings about the game theory and economics that gave us this theorem, but it works effectively in this game. I have been deeply interested in game AI for a while and I was really excited to get a chance to implement one for this project. I am looking forward to getting more in depth with these algorithms in future projects.

The hardest part for me in dealing with this was changing how I think about how the UI gets updated. It was difficult wrapping my head around how the UI would respond to touch and know what the specific tile was. When I got to the part updating the AI’s tile, I had a similar cognitive issue of figuring out how we are tracking things. It was actually less complicated, but there are so many moving parts that are contained within one another that it can be difficult keeping everything straight in one’s mental map.

With this section completed, I have two more features I want to add to the game before I ship it. I want multiple scene for the app, so you have a main menu screen that you see before you begin playing. One reason I want this main menu scene is for the other feature, which is variations on tic tac toe. I want to add two variations. One will be simple and the other will be slightly more complicated.

When I have completed these features, I intend to submit this as a free app to the App Store. I want to be able to catalog what I needed to do on this blog. I think it’s likely that Apple will not allow this game on the store as it’s not particularly original. They have been cracking down on student projects and highly derivative apps on the store to try and keep the clutter down.

I understand their perspective, but it’s unfortunate because many employers require you to have an app on the store before they will consider hiring you. There is a limit to the complexity of an app you can create on your own in a limited amount of time without a paying job. By removing this as a platform where students can put portfolio projects, they’re hurting people who are just starting out and are not actually trying to gain a massive audience. There is no other distribution network for iOS applications and it’s onerous to expect employers to have Xcode and to build source code to device. I will see if I am able to get through this barrier or not. Until next time!

I bought this to be the featured image at the top, but WordPress cropped it so all you saw were boobs. Gall and brimstone!

Conferences for Spring 2018

I’ve gotten a little behind on my goals for this blog recently. I have several upcoming conference appearances that I am preparing for that are absorbing a bunch of my time.

In trying to keep with the spirit of posting at least once a week, I am announcing my future appearances so if you want to say hi you have the opportunity to do so and I get to keep my streak alive!

NVIDIA GPU Tech Conference (GTC): March 26-29

First up I have GTC in San Jose. I am leaving for this on Sunday.

GTC is the first conference I have attended in a while where I am simply an attendee. I don’t think I have been a conference attendee since 2013. I have always either volunteered to work the conference or spoken.

GTC is focused on cutting edge GPU technologies including VR, autonomous driving, and deep learning. There are like 600 sessions and various labs, both self directed and instructor led.

I am trying to branch out beyond just iOS programming conferences. I started that last year with GDC (the game developer conference.) This is the first GPU programming conference I will have attended. I am deeply interested in seeing all the use cases for GPU programming to get a better idea about how to channel my energies in this field. Right now I feel rather overwhelmed by what is out there and I am eager to see what possibilities exist in this space.

RWDevCon: April 5-7

Up next I have RWDevCon. I last spoke at RWDevCon in 2016, but I came as an inspirational speaker. This year I am tackling a much harder task. I will be leading a 90-minute guided tutorial on how to integrate Metal shaders into SceneKit code so that you’re not responsible for setting up the entire rendering pipeline.

I will also be recording a live podcast with my cohost on the Ray Wenderlich podcast, Dru Freeman. It’s going to be a hectic, busy conference, but if you’re a fan of the work the Ray Wenderlich team does, this is an invaluable opportunity to meet the team in real life.

UIKonf: May 13-16

UIKonf is my first European conference of the year. It’s also my first international conference in a country where English is not the native language. (I was privileged to speak at two conferences in the UK last year.)

I have not yet determined what I will be speaking about, so I can’t give a lot of details on this. Planning for RWDevCon is occupying most of my available free time and energy.

WWDC? Nope!

I delayed this blog post until after I had determined if I had won a ticket to WWDC. I did not win the lottery this year, which leaves my record and 0:3. I am trying not to be too disappointed or be upset in a few months when everyone is tweeting about the amazing time they are having. But I promise nothing!

Conclusions

As much as I enjoy going to conferences and seeing my friends, it’s really put a pin in the work I would like to be doing right now. I can’t finish my game because I have slides and presentations to finish. I am feeling incredibly listless and upset because I feel I am not accomplishing anything and it bothers me tremendously. I am hoping after I get these two conferences out of the way I can get back to doing things that make me happy and productive.

Looking forward to seeing friends old and new over the next few weeks!

Pizza and Video Games March 2018: Portal

The first entry in my Pizza and Video Game series was pretty much a no-brainer. I wanted a relatively short game that was iconic and not brutally hard. The best representation of all of my parameters is the game Portal.

Portal was released just over a decade ago. It is a fairly short puzzle game where you wake up in a laboratory and run through several experiments testing a new device that creates “portals” within the laboratory. You eventually control the entry and the ending point of these portals in an attempt to navigate through the levels of this experiment. Some surfaces are portal-able while others are not. Sometimes you need to utilize momentum and physics to fling yourself further.

There are a few common design elements for all of the puzzles in the game:

  • Moving blocks from one room/inaccessible space to another
  • Using physics to fling yourself by going through multiple portals or jumping off cliffs
  • Utilizing fireballs to hit inaccessible targets

These start easy, but then build on one another to create increasingly complex puzzles. The game is very well designed. There is no point during the game where you feel that things are unfair or require knowledge you have not accessed. You can figure out what you’re supposed to do without feeling like the designers were smoking The Crack.

One issue I personally had with Portal is that there was a point at which I could not continue with the game. I could only get through level 17 when the puzzles became too difficult. They weren’t difficult in regards to the logic required to figure out what the solution was. They were difficult because they required a degree of fine motor skills and coordination that I simply don’t possess.

I have tried getting through Portal several times, but I always got stuck at a certain point because I couldn’t do things fast enough to pass certain levels. The Boyfriend noticed that I tend to not use the controls properly. He noticed that I would work the camera and the movement controls independently rather than synchronously.

We are going to start working through the Halo because that is one of the first games to utilize the camera and movement controls together so that I can get more used to this design pattern in games.

Even beyond my lack of experience and comfort with the controls, the game becomes significantly more difficult in the later levels. I had spend several years hearing people tell me that Portal was a very quick and easy game. I went in with the expectation that it would be so, only to run into a brick wall towards the end of the game. I wound up having The Boyfriend complete the last two levels of the game for me. Otherwise I may not have finished. Or if I had it would have taken all weekend. There are a few incredibly fidgety puzzles that required an incredible amount of timing and precision. I know a lot of gamers really want a challenge, but it would really be nice to have something that would be accessible to people with physical impairments who can figure out the puzzle but can’t react as quickly.

It was interesting to see a lot of patterns in Portal that are “borrowed” by other games. The secret rooms with the warnings about the AI and the cute song at the end of the game feel kind of like the post-credit sequences in Marvel movies. They were a completely new thing a decade ago but have been used by so many people in the intervening years that it’s hard to remember how innovative it was at the time.

I did also appreciate that the two characters in the game were both female. The AI being female I understand. Between Siri and Alexa it’s just kind of a default for computers to have female voices, but the choice to make the protagonist female was really cool. I always appreciate it when creators don’t just default to male protagonists, even though in this case you only see Chell in passing if you see yourself before you go through the portal.

Conclusions

I feel our first Pizza and Video Game day was a success. I feel like Portal was the perfect kind of game to do for something like this. I am a little sad that so many gamers feel like games have to be a hundred hours long to be worth the money. I worry about the number of games that I can actually get done in a day, but I will worry about that another time. For now, I am glad I finally got to see all of Portal, even though I didn’t complete it myself. Until next time!

Monthly Pizza and Video Games

Back when I was a kid we didn’t have any video game consoles. My parents thought they rot your brain and were expensive, so we didn’t have a Nintendo.

My brother and I had a home daycare woman who had four kids and I swear bought every video game system ever. Every time a new system came out within a few weeks one would magically appear at their house. I was never allowed to play with it because it was “their” system, but I was allowed to watch them play from the couch.

One day that we had off from school the older kids went out and bought a bunch of junk food to eat in the basement. They had a bunch of friends over to play games and eat junk. They actually let the younger kids hang out with them and shared junk food. This was the only time in my childhood where I felt like I was part of a group of people doing normal things having fun. I told myself that when I was in high school I was going to have a gang of friends who would come to my house and play video games and eat junk food. I didn’t process that I lived in a rural town where I already knew all my future high school classmates and that I didn’t get along with any of them and that this would never come to pass.

It’s been a thing I revisit sometimes. My ex-husband decided he was over video games by the time we got together and wouldn’t play with me. I bought a few systems after the divorce and really got into the Persona series, but I didn’t have people to play games with. Luckily, my new boyfriend likes video games and I finally have someone to play games with.

So we decided to institute “Pizza and Video Games” days. The first Saturday of every month, we are ordering a pizza and playing a video game. We’re limiting the amount of junk food we do in a day because, frankly, my digestive system can’t handle it as well as it used to. We want to try all the various pizza places around us so we’re not just ordering from the same place every month.

We have a few parameters we’re looking for when considering a game for Pizza and Video Games day:

  • Console Game: Primarily looking for a game that would be played on the TV through either a PS3/PS4/Xbox 1/Steam. I have a vast multitude of 3DS/Vita games that I play in the bath or while I am traveling and these are not candidates for Pizza and Video Game days. Not sure about Switch games yet as they’re in a gray area.
  • Short: I’m looking for games that can mostly be played in a day. I’m sure the Assassin’s Creed games are awesome, but I wanted to focus on trying to find a game that could mostly be completed within a day.
  • Relatively Easy: I didn’t grow up playing video games, so I am not looking for the most brutally hard games I can find. So no Super Meat Boy or Celeste. These are probably awesome games, but I would die like two seconds in and that would not be fun.
  • Variety of Genres: I have mostly played adventure games in my time as a gamer. These are games that don’t really require a lot of coordination or motor skills. They just involve walking around solving puzzles. These are great games, but I am trying to expand outside my comfort zone and try different things I am less familiar with. We are not going to just do first person shooters, but I would like some experience with these as they’re a large chunk of the video game landscape.
  • Important Historically: There’s like 40 years of video game history that I need to work through to become familiar with current game design patterns. I’m basically trying to find someone’s top ten list of the most important video games and focus on those as a jumping off point so I can see how these games influenced the landscape.

We may not be able to satisfy all of these requirements. These are more like suggestions or guidance questions as opposed to set in stone rules. We’re also going to try to do more games together after work on a regular basis. There are longer games like Mass Effect that I would very much like to work through that I will be writing about in the future, but not as part of this series of articles.

These do not need to be new/recent games. I would like to go back and play through the Super Mario Brothers games on the original NES. Since I have an NES emulator, this shouldn’t be a problem.

Games were designed to be a social thing to bring people together. You can play on your own, but having a community of people to share your experiences with is a vital part of the gaming experience. I didn’t get to have fun game days in high school, but it’s never too late to find a community of people to have fun with. I’m glad I finally found one.

Tic Tac Toe: Graphics, Labels, and Animations

I have a roughed out version of my tic tac toe game running. If my point was to just get something working, I could call it a day at this point. However, the goal I have with this project is to put together a somewhat professional game. This requires a lot of polish and a lot more work.

The focus I have in this blog post is to do the biggest immediate thing I can do to make this look like a real game. This includes real graphics and not just colors that I used as placeholders. I also want to give the user feedback about whose turn it is and what the state of the game is. Additionally I want to add some interest to the game with animations so it feels more responsive than it does now.

Graphics

This section will focus on incorporating graphics. I got a graphic design degree ten years ago and I haven’t used it much in the last decade. One of my longer term goals is to work more with graphics programs so I can get more comfortable with them. But for this project I am opting to use assets created by other people.

One resource I like a lot is Game Art Guppy. If you have worked through any tutorials from Ray Wenderlich, then the art on Game Art Guppy should look familiar. Ray’s wife Vicki did all of the art assets for the site for a number of years. Game Art Guppy is her market for low cost art assets for developers. Many assets on the site are free and none are over $25.

Since my other major hobby is cooking, I decided to use the pastry icon set from the site for my squares. I know Xs and Os are traditional, but I want this to be whimsical. There is a correlating background that goes with this tile set. These assets were used in an epic Candy Crush tutorial on Ray’s site. I highly recommend it because I learned a lot from working through it.

First I placed the background image behind the board. When I initially added the background it covered the other parts of my board, so I made its z-position -1 so that it would appear behind the board:

let background = SKSpriteNode(imageNamed: "bg_ipad_portrait")
background.zPosition = -1
addChild(background)

I chose the donut and one of the sugar cookies for the Xs and Os because they kind of looked a little like Xs and Os. I want to keep the white background but just apply the texture on top of it. I also want to animate the tiles, but that will happen later. Here is the code I used to get this working:

switch currentPlayer {
    case .playerA:
	let playerTile = SKSpriteNode(imageNamed: "pastry_donut_320")
	playerTile.scale(to: node.size)
	playerTile.position = CGPoint(x: node.size.width / 2, 
				      y: node.size.height / 2)
	node.addChild(playerTile)
	board[tiles.index(of: node)!] = .playerA
    case .playerB:
	let playerTile = SKSpriteNode(imageNamed: "pastry_starcookie02_320")
	playerTile.scale(to: node.size)
	playerTile.position = CGPoint(x: node.size.width / 2, 
				      y: node.size.height / 2)
	node.addChild(playerTile)
	board[tiles.index(of: node)!] = .playerB
    case .notPlaying:
	node.color = UIColor.white
	board[tiles.index(of: node)!] = .notSelected
}

Each player has a pastry associated with them. If I just change the texture of the containing node to the pastry icon then they will appear to float in space, so I am making the pastry a new sprite and making it a child of the containing node. The pastry icon is way too large to fit inside the containing node, so it needs to be scaled to fit within the tile. Additionally, the anchor point of the tile is in the bottom left, so I am positioning the new sprite to sit in the middle of the sprite node.

Finally, I want to have a real app icon. I always forget to make a generic one for sample projects and tech talks and it constantly bothers me. When I see other people went to the trouble it makes me feel crappy and inadequate, so really wanted to make sure I did that on this project.

I chose the sugar cookie as my main focus on the app icon because I thought it was the more visually interesting sprite in the set. I used Illustrator to place the sprite in the view and exported it as PNG. I then used Photoshop to change the size and apply the correct labels to each size. I believe Illustrator has an option to do all of this in one step, or a least fewer than I did, but I didn’t figure out how to make that work. I have been told Sketch does this as well, but I don’t own it and I’m unfamiliar with it, so I used the thing I am comfortable with.

Labels

I want to use a label at the top of the screen to give information to the user. I want to be able to tell the user which player’s turn it is and how the game has ended. Right now I am just printing it out to the console, but that can only be seen by me when I run this in the simulator.

SpriteKit has a specific node for labels. I created one inside the class declaration but outside of any methods:

let label = SKLabelNode(fontNamed: "Noteworthy-Bold")

I created a backing image for the label, which I need to add as a sprite node to the main node hierarchy:

let labelBackground = SKSpriteNode(imageNamed: "headerBacking")
labelBackground.zPosition = 2
labelBackground.size = CGSize(width: boardSize, height: 60.0)
labelBackground.position = CGPoint(x: 0.0, y: (boardSize / 2.0) + 100)
labelBackground.anchorPoint = CGPoint(x: 0.5, y: 0.5)
addChild(labelBackground)

I need to add the label node as a child of the label background node. I set the anchor point for the label background to the middle of the node so that the text can be placed in the center of the node.

label.text = "Tic Tac Toe"
label.fontColor = SKColor.black
label.fontSize = 40
label.zPosition = 10
label.position = CGPoint(x: 0.0, y: -20.0)
labelBackground.addChild(label)

I want raw string values associated with both my player state and my win state so that I can post them in the label for the user. Here are my updates to my state enums:

enum GameState: String {
    case notPlaying
    case playerA = "Player A"
    case playerB = "Player B"
}

enum GameEndState: String {
    case playerAWin = "Player A Wins!"
    case playerBWin = "Player B Wins!"
    case draw = "Draw!"
}

I tried attaching an observer to the current user to update the label whenever the current user changed, but that not only resulted in never telling the user that the game was over, it also didn’t prevent the game from continuing. Instead, I explicitly update the label in the line of code after I update the user. I do this in the initializer but I also have to do that on the touch event:

if let isWin = checkForWin(currentPlayer: currentPlayer, board: board) {
    label.text = isWin.rawValue
    isUserInteractionEnabled = false
} else {
    currentPlayer = switchPlayer(currentPlayer: currentPlayer)
    label.text = "\(currentPlayer.rawValue)'s Turn"
}

Previously I was checking for each specific win condition, but since that is being tracked in the raw value I can just post the end state in the label. I don’t want the player to continue to play if the game is over, so I need to disable user interaction. If the game isn’t over, then the current player switches and the label updates.

Animations

Next I want to animate the tiles as they are selected. This works, but it’s a little boring. It’s also a little abrupt to just have an image pop up when you touch a tile. Adding an animation to the action really gives a bit of life to the application.

One thing that confused me greatly about SpriteKit was how animations were done. I knew that animations had to be a huge component of SpriteKit, but there was no SKAnimation class. I thought maybe this descends from UIKit and you would need to use Core Animation to get this to animate. After some digging I found that there is an animation class in SpriteKit, but it’s called SKAction. Why they changed it, I can’t say. People just liked it better that way.

At some point I would like to do a dedicated blog post to SKAction, but for this project I am trying to simply focus on doing what I need to for the effect that I want. I want to create some kind of transition in with the sprites so they don’t just pop out of nowhere on the tiles. I want the sprite to fade in. I also want my sprite to scale up and kind of pop out a little before scaling back to the proper size.

First, I pulled a few properties out of the code blocks that I need to calculate my actions:

let nodeSize = node.size
let largeNodeSize = CGSize(width: nodeSize.width + 30, 
			   height: nodeSize.height + 30)
let spritePosition = CGPoint(x: node.size.width / 2, 
			     y: node.size.height / 2)

Next, I created my action outside of my switch statement. I want to use the same actions for both Player A and Player B, so there isn’t any point in creating those in-line. I wanted to place them outside of the touches method, but there are properties on objects that I need to check inside that method, so the actions are declared there.

SKAction has two ways of grouping actions together: Groups and Sequences. Groups are actions that need to run together at the same time. Sequences are actions that run one after another. I need to utilize both groups and sequences for my sprite animations. The scale up and scale down need to be part of a sequence because one follows the other. That sequence has to be grouped with the fade in so that it sprite both fades in and scales simultaneously.

Here is my action code:

// Actions
let fadeAction = SKAction.fadeIn(withDuration: 0.75)
let scaleUpAction = SKAction.scale(to: largeNodeSize, duration: 0.5)
let scaleDownAction = SKAction.scale(to: nodeSize, duration: 0.25)
let scaleSequence = SKAction.sequence([scaleUpAction, scaleDownAction])
let actionGroup = SKAction.group([fadeAction, scaleSequence])

You may notice that there is no code here to specify what the starting scale is for the sprite. That needs to be set when the sprite is created. My refactored tile sprite code now looks like this:

case .playerA:
    let playerTile = SKSpriteNode(imageNamed: "pastry_donut_320")
    playerTile.setScale(0)
    playerTile.position = spritePosition
    node.addChild(playerTile)
    playerTile.run(actionGroup)
    board[tiles.index(of: node)!] = .playerA

Music and Sounds

The last bit of polish I want to add to the project is music and sound effects. One interest that I have in game development is doing music and sound effects. Before I went into programming, I went to school for audio engineering and video production. My specific area of interest was sound design. I loved to sit down with an animated scene and remove all the sound and add it back as a project. One of my sound design projects can be seen here.

I need more practice to get back up to speed with sound design, along with graphics and illustration. Those are concerns for another time. But needless to say, I understand the value of music and sounds to making something feel like a finished product. So I wanted to make sure I had nice sounds for the game.

I want background music and I want a nice little “popping” sound effect for when the sprite pops into the tile. I don’t have time right now to make my own sounds or music, so I needed to find decent free sounds and music to include in the project. I don’t assume that if you find something online that it can be used in any way. I make sure that the creator has given permission for the use I have. I am willing to buy music and sound effects, if anyone reading this has any suggestions about good places to find resources.

I found the tile popping sound at Sound Effects Plus. The sounds are free to download. Their licensing and restrictions are available here.

I found my music at Incompetech. I discovered this site through Paul Hudson. He mentions the site, along with a few other good resources, in his SpriteKit book, which I reviewed here.

For the tile popping sound, I want to make sure the pop happens at the right time. I tried simply calling it at the same time the animation was happening, but because the sound was so short, the “pop” was happening while the sprite was still growing. I resolved this by adding it to my scale sequence:

let soundEffect = SKAction.playSoundFileNamed("pop.wav", waitForCompletion: false)
let scaleSequence = SKAction.sequence([scaleUpAction, soundEffect, scaleDownAction])

Finally, I added my background music to the game. Not a lot of people have written much about audio mixing in SpriteKit, so that might be a thing I do in the future. I want to be able to lower the volume of the background music so that it doesn’t drown out the sound effects, but I am not certain how to make that work. I tried a few things but none of them worked, so for now I am simply adding the sound when the application begins:

run(SKAction.playSoundFileNamed("Carpe Diem.mp3", waitForCompletion: false))

I feel comfortable with my control of SKAction for animations, but I am not happy with my control of it for sounds and sound effects. Want to research this further.

Conclusions

You can see the current state of the project here.

In total I spent under ten dollars on assets for this game. The sound effect and background music were free. The tile set was nine bucks. I am honestly kind of shocked at how much better this looks with just a minimal amount of work using assets I found on the internet.

For now this isn’t completely done. I still don’t handle what happens when a game ends in a way that I find satisfactory, but that is a chunk of functionality I intend to tackle in a future blog post. However, this did come along pretty well and I am happy with the results so far.

Tic Tac Toe: Touches and Responses

Last time I set up the tic tac toe board with a set of nine tiles that will represent the board. This week, my goal is to make each tile responsive to touch so that we can connect our game logic to it.

I need to do the following steps:

  • Set up a touch observer to look for touches
  • Determine if the touch is located on a sprite representation of a tile
  • If so, which tile?
  • Figure out how that tile correlates to my array of game logic tiles
  • Change the state on the correlating game logic tile
  • Update the UI
  • Check for a win or a draw
  • Either end or continue the game

I have found that, for me personally, breaking tasks down into smaller chunks makes it easier to stay focused and get something done. Instead of worrying or freaking out about how I am going to set up multiple game scenes, which I intend to do later, I am focused on this one small chunk of the program. I am further dissecting this chunk into even smaller chunks so I don’t get confused about how I am going to get all of these things to work together.

Connecting the Model Game Tiles to the View Game Tiles

The first problem I would like to solve before I go any further is to figure out how to connect my model tiles to my view tiles. The view tiles are the objects that the player sees and can respond and detect touches, but they only know about what they look like and what is touching them. They don’t know that a certain color or image or state means anything outside of their own context. That is the responsibility of my model tiles. Those tiles know what state they are in and they provide data to my functions that determine if they are part of a win or not. I need some way to allow the model tiles to talk to the view tiles so they can both do their jobs.

There are a few ways to do this. I could have created a bunch of methods and structures to check the row and column of my board, but I only have nine objects to track. SpriteKit has a method of checking sprites by name, so I chose instead to create a single array of sprites and to give each a unique name that includes their index so that they can be found and tracked based on an identifier.

I created an array of model tiles that represent the state of the board. I am using their indices and positions in my game logic. I created a similar array to hold all of my sprite tiles. When I generated the sprite tiles, I generated them in the same order as I did for the model tiles and named them accordingly. The first tile in the sprite array should be the uppermost left tile, which correlates to the index and first tile in the model array. So the indices of each should line up. Keep that in mind as we walk through the rest of the steps.

I realized after I wrote this section when I was trying to get the next section to work that I don’t actually populate either of my arrays at this point in my explanation. I add the sprites to the board layer but I forget to add them to the array I created to hold them.

I added the following code within the nested loop in the initializer:

boardLayer.addChild(sprite)
tiles.append(sprite)

I had also added a method to populate the model array that I commented out because I wasn’t using it yet. It is this one:


board = resetBoard()

This is a good example of ways things can go wrong when you’re working with computers. You may intend to do something but unless you explicitly set it, then it won’t happen and you become frustrated. This is actually kind of true with people too…

Detecting Touches

UIKit has built in gesture recognition. One such gesture is touching. I generally haven’t used this because I use other elements, like buttons, that implement it automatically. But it’s useful for SpriteKit games, especially ones of a platform nature where you don’t necessarily need to hit a specific object in order to get a character to move on the screen. In fact, that would kind of defeat the purpose of having a touch screen over a controller of some kind.

One thing you have to remember (that I forgot and had to correct) is that you have to enable user interaction explicitly when you initialize the scene. You do this by putting this line of code somewhere after the call to super:

isUserInteractionEnabled = true

There are several methods for touch, but the default one is touchesBegan. This method kind of lurks around observing the screen waiting for a touch to happen. Once one does, it implements whatever game logic needs to be executed to respond to the touch.

The method doesn’t just bring in a single touch. It brings in an array of UITouch objects. So keep that in mind when you are using touchesBegan that it could potentially have many touches and not just one.

Here is my initial boilerplate touchesBegan method:

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
	if let touch = touches.first {
		let location = touch.location(in: self)
		let tappedNodes = nodes(at: location)
	}
}

At this point I started adding a bunch of loops and conditional logic to get my code to work. It didn’t. I got confused and frustrated. I went to The Boyfriend to ask for help debugging my code. No, I am not sexist Computer Engineer Barbie. The Boyfriend has 30 years of programming experience to my five.

We debugged the array issue I mentioned above and came up with this much nicer method for checking for touches in our tiles:

override func touchesBegan(_ touches: Set, with event: UIEvent?) {
	guard let touch = touches.first else {return}
	let location = touch.location(in: self)
	let rawNodes = nodes(at: location)
	let tappedNodes = rawNodes.filter{return $0.name != nil}
		
	guard let node = tappedNodes.first as? SKSpriteNode else {
            return
        }
	node.color = UIColor.black
	board[tiles.index(of: node)!] = .playerA
}

First we are ensuring that we actually have a touch. If there isn’t an eligible touch, we want to break out of the method. Next, we need to store the location of the touch. This location is used to get an array of all nodes that exist at that location. One thing I had forgotten when putting the board together was that the background and the game board are also SKSpriteNode objects. This meant that when I touched the screen three nodes were added to the raw nodes. Since we only care about the one we named, we need to remove those other sprites from the array. We do that by checking for a name. Since the board and the background are not named, they are removed from the array. Lastly, we’re checking to make sure that any node that is left in the array can be cast to SKSpriteNode. If not, we break out of the method early.

Now that we have ensured that the only node we can possibly have at this point are SKSpriteNodes, we can now set properties on the node such as the color. We can also use the node to find its index within the array of sprite kit tiles. This directly correlates to the index within the model of the tile state that needs to be updated. Voila!

Can touch a tile and switch it from red to black

Updating the UI

Right now this isn’t particularly interesting. I can tap on a tile once and it changes from red to black. I can’t switch back and forth between players. Yet.

I modified the bottom of the touchesBegan() method to the following:

if board[tiles.index(of: node)!] == .notSelected {		
	switch currentPlayer {
	case .playerA:
		node.color = UIColor.black
		board[tiles.index(of: node)!] = .playerA
	case .playerB:
		node.color = UIColor.red
		board[tiles.index(of: node)!] = .playerB
	case .notPlaying:
		node.color = UIColor.white
		board[tiles.index(of: node)!] = .notSelected
	}
}

I changed the default unselected color of the tiles to white to make the different players a little more dynamic. I want to make sure that if a tile has already been selected that it can’t be selected again. I check the index of the correlating tile in the model to see if it’s been selected or not. If the current player is Player A, the tile switches to black. If the current player is Player B, it switches to red. To ensure an exhaustive switch statement I simply leave the node color white, but this should never be called.

I noticed that the first time I tested this that the first tile I touched didn’t do anything. I realized that the first time I touched the board I was still in the .NotPlaying state. I had commented out the switchPlayer call at the end of the initializer, so I just had to delete the comment and we are nearly ready to go.

Can switch between players now

Checking for Win and Ending the Game

Finally, after the move has been completed, we need to check for whether or not someone won the game. I set this logic up before, so all we have to do is call our game over method:

if let isWin = checkForWin(currentPlayer: currentPlayer, board: board) {
	switch isWin {
	case .playerAWin:
		print("Player A wins")
	case .playerBWin:
		print("Player B wins")
	case .draw:
		print("No one wins. Everyone gets a participation trophy")
	}		
}

currentPlayer = switchPlayer(currentPlayer: currentPlayer)

I thought about trying to get an alert view going for these win cases, but then I would have to remove them later when we have better UI, so for the time being I am not concerned with how to tell the player that the game is over. I am simply printing the result to the console and making it so no one can play anymore because I am mean.

Have fun reading the tiny print on the console!! :p

If isWin falls through because the game is not yet over, we need to switch players, which is the last bit that we do at the end of this method.

Conclusions

My project so far can be seen here.

This was far easier to set up that I originally anticipated. All of the work I did over the last few weeks to separate the model from the view really paid off here. I could focus on simply checking what state the game is in and update the UI accordingly.

Most of the SpriteKit games I have done tutorials for are ones that are running continuously and thus have all of their logic in a game loop. Turn based applications are similar except you only update the game once someone has made a move. As someone who is primarily interested in turn based games, this is something for me to keep in mind.

I have broken this game out into three more chunks that need to be done before I feel like I have completed this game adequately:

  • Graphics, Labels, and Sounds: I have an art tile set that I want to apply to the game so it looks like a real game and not a minimalist painting. I want to update labels that say what the current state of the game is. Lastly, at a minimum, I want some kind of background music.
  • Implementing an AI: This game isn’t very interesting without someone or something to play against. I want to look into how to implement some kind of AI for this game, be it using GKStrategist or me just rolling my own AI.
  • Multiple Scenes and Variations: I want an actual main menu screen to explicitly start the game. I would like a game over screen to take you back to the main menu. I also have some ideas for variations on tic tac toe for the player to be able to choose because the base game is pretty boring. I want those options to be selectable in the main menu.

So just three more blog posts left on this project! Then it’s on to actually attempting something that people might actually want to play. Stay tuned!

SpriteKit vs Unity: Scripts

One of my goals this year was to learn Unity. There is a local indie game developer meet up that I attend with some awesome accomplished game developers. I started going while I was working on the Metal book to ask how to break into the game industry. The primary thing they told me was to know Unity. I thought that knowing Metal and programming would be enough to get into the industry, but I have found a lot of people don’t really know what Metal is.

Additionally, knowing programming and knowing how to work with an incredibly powerful and complex tool are two entirely different skills. As someone who spent two years learning Pro Tools and Photoshop, I am painfully aware of how important it is to have an idea about what a tool can do and how to best utilize it.

Also, honestly, if you’re not going to bother to learn something in your spare time, then it’s probably not that important to you. I can understand the barrier to entry being at least having a working sample project in a skill as opposed to just saying “I want to be a game designer!!” I understand that not everyone has vast amounts of free time to spend dicking around with every cool game engine out there. A lot of people are parents and have family obligations and I am in no way shaming those people because family is way more important than mucking around with programming 24/7. But if you do have a lot of free time and you spend it partying or whatever, then the cool thing is really not that important to you. There’s nothing wrong with that. I want to be in better shape but not enough to actually make time to go to the gym.

If you’ve been reading my blog, you know that right now I am trying to build a game in SpriteKit. I have been interested in SpriteKit since it was released several years ago, but it took me a while to come to grips with how it works. You learn best by having a project that you try to get working, so that is the point of the tic tac toe project. So most of my background in game development is doing native Apple game development with their frameworks, languages, and workflow.

One thing that massively confused me when talking to people who primarily came from Unity was scripting. With SpriteKit, everything I do is done in code. They have an Interface Builder-esque tool that I have not yet used in any real capacity, but beyond that everything is done in code. Sprites are placed and skinned in code. They are moved in code. Labels are created in code.

I asked about the point of scripting over coding. I was told it is easier to edit a script than it is to change things in code. That made no sense to me because if you have to edit something in Xcode it doesn’t really matter where it is, the amount of work is the same.

So one big thing I wanted to get out of learning Unity was to get a better idea about what is meant by scripting as opposed to what I am familiar with from SpriteKit. I have only been working with Unity for about two weeks. I am working through the Unity Games by Tutorials book from Ray Wenderlich. There will probably be things that I am missing in this post about scripting because I still haven’t used it much, but these are kind of my initial thoughts coming in from another perspective.

SpriteKit

The approach I have seen most people take in SpriteKit programming is to approach solutions in a third-person, God-like perspective. There is a single update() method that you code with everything you want to happen on each iteration of the game loop. There is a method to detect touches and within that method to express what you want to have happen when the user touches the screen.

You create subclasses of game scenes, but not really of SKSpriteNode. You create instances of SKSpriteNode named for the different objects you have in the game with different sizes and textures, but you tend to generally not subclass SKSpriteNode.

I will be showing a few examples of what I mean using the first project from Ray Wenderlich’s SpriteKit book. Yes, I use a lot of his books. No, I am not getting paid to shill them. They are good examples of showing how to put a completed project together and I find it useful.

The first game you build in that book is a 2D platformer called Zombie Conga. The point of the game is to bite cats to turn them into zombies while avoiding crazy cat ladies. You win when you reach a certain number of cats or you lose if you collide with too many cat ladies.

The project is architected with a lot of small methods that involve explaining an action you want to occur. One such action is move:

func move(sprite: SKSpriteNode, velocity: CGPoint) {
	let amountToMove = velocity * CGFloat(dt)
	sprite.position += amountToMove
  }

This is a reusable method that can have any instance of SKSpriteNode and any point passed into it. Within the project, there is actually only one instance where you are using this method, and it’s on the zombie protagonist:

move(sprite: zombie, velocity: velocity)

The entire project is composed of small methods that are abstracted away from the main game loop so that it’s not cluttered by every little thing it needs to do. Here is an example of an update() method in a game scene in SpriteKit:

override func update(_ currentTime: TimeInterval) {
	if lastUpdateTime > 0 {
	  dt = currentTime - lastUpdateTime
	} else {
	  dt = 0
	}
	lastUpdateTime = currentTime

	move(sprite: zombie, velocity: velocity)
	rotate(sprite: zombie, 
               direction: velocity, 
               rotateRadiansPerSec: zombieRotateRadiansPerSec)

	boundsCheckZombie()
	moveTrain()
	moveCamera()

	if lives <= 0 && !gameOver {
	  gameOver = true
	  print("You lose!")
	  backgroundMusicPlayer.stop()
	}
  }

You don’t necessarily have to understand everything this is doing, but just look at how this is laid out. The update is nearly entirely composed of method calls to abstracted methods within the game scene. You pass in the sprite you want to modify for some of these. Other void methods such as moveCamera() directly mutate a specific SKSpriteNode instance that is not subclassed. The way of thinking about a SpriteKit project is from a God-like perspective where you think about all of the things you want to do and how to move your pieces around to make it happen. You abstract out methods even if they are only called once and only work on one instance of SKSpriteNode.

Unity Scripts

Unity takes a fundamentally different approach to game objects than SpriteKit does. I mentioned a few times that in SpriteKit you don’t really subclass SKSpriteNode. This is not how Unity deals with game objects.

In Unity, game objects tend to start out as meshes that you import from a tool like Blender. These objects have meshes, materials, and animations associated with them. These can be composed of multiple meshes that are imported separately. All of these aspects are collected together into a single game object called a prefab. Instead of creating a generic Unity sprite node, you create instances of these prefabs in your game. You can apply a change to a prefab universally among all the instances of the prefab or you can create changes locally to a single instance of a prefab.

One fidgety and highly powerful feature of Unity is the ability to add components to both the prefabs and instances of the prefabs. These components include physics, rendering, and scripting.

Scripting is more like a first person perspective as opposed to the third person God perspective utilized in SpriteKit. Instead of thinking of your methods globally, you think about them as being the internal monologue of your game object. These scripts watch for input and respond to it rather than creating a method around the input method.

I have a script for a gun in the learning project I am working on. The update method in it’s script looks like this:

void Update () {

    if (Input.GetMouseButtonDown (0)) {
        if (!IsInvoking ("fireBullet")) {

            InvokeRepeating ("fireBullet", 0f, 0.1f);

        }

    }



    if (Input.GetMouseButtonUp (0)) {
        CancelInvoke ("fireBullet");

    }

}

The script is actively observing the mouse button input and making a determination about its behavior based on the button’s state. The script only knows about itself and anything that impacts its ability to function. Rather than having an update method that is controlling the gun, the alien, and the protagonist, each of these objects has their own self-encapsulated update method.

This is a different way of doing things. I can see how this would be more efficient when you reach a certain scale of project. Even within the small SpriteKit projects I have worked on, I have found project organization to be difficult. My logic always looks messy and I actively look for ways to abstract logic away from my main game scene.

I am not certain if this a pattern that can be applied to SpriteKit or not. I know in programming there isn’t anything that is impossible, but there are ways of working with and against a framework. I could completely recreate Android’s UI in iOS using views and so forth, but why would I want to?

I do know that Apple also has a supplementary framework called GameplayKit that includes an entity-component system. Ray Wenderlich’s SpriteKit book used to have several chapters on this system, but those chapters were replaced with tile maps in the latest version. A few of GameplayKit’s functions, such as state machines, seem to have been coopted by Swift’s architecture. I am uncertain if Swift protocols could fulfill a similar function to entity-components or if SpriteKit and Unity have incompatible design patterns. Either way, it’s a different way of approaching the problem of coordinating actions and behaviors on game objects.

Components vs @IBInspectable

I would be remiss in not explaining the single biggest feature that make scripts easier to work with in Unity. One big aspect of game development is the ability to tweak variables to tune the game. The line between the game being fun and impossibly hard isn’t very wide.

Having to open up a script and dig around in code to change a time or a number of spawned objects is a bad design pattern, especially if you are considering that your user base isn’t necessarily composed of programmers. Unity is designed to be worked on by large teams of people who do things other than programming. It’s important for a designer to be able to change variables easily on the fly.

Unity gets around this by integrating the scripts with the user interface. In your script, you can make a determination about what variables you have that may need to be changed to tune the game. These can be made public within the script:

Unity looks in these scripts to see what variables are public and exposes them within the UI so they can be modified and edited without having to open the script editor:

People can sell scripts on the Unity marketplace, so it’s possible for someone who has no programming experience at all to be able to buy a script written by someone else and use it effectively without looking at it once. The programmer part of me feels dirty when thinking about this, but there are many roles on a game development team that don’t require programming. Creating a system that allows these people to work quickly and effectively by abstracting away that unnecessary complexity is smart. I can also see why it would be a lot easier to just change a value in a field within the IDE than it would be to open the code and find the variable and edit that crap by hand.

The closest thing I think Xcode has to this design pattern is @IBDesignable and @IBInspectable. If you are creating custom views/buttons/etc… in iOS, you can tag your subclass as @IBDesignable. You can then publicly expose properties you want to tweak by tagging them as @IBInspectable. Xcode will see these tags and modify itself to allow you to change these within Interface Builder. There is a great tutorial about doing this with Core Graphics here.

Conclusions

I have really been enjoying getting familiar with Unity. Before I got into programming I spent a lot of time learning Photoshop and Illustrator. It always astonished me how much you can do with these complex and powerful tools. I can appreciate the fact that a lot of work is abstracted away that doesn’t really matter.

For the last few years I have felt somewhat creatively shut down. I dwelled on implementation details and mechanics because they were a comfortable place to be. Something either works or it doesn’t. You spend a lot of time thinking about how something works rather than thinking about what you want to create with it.

Going back and doing Unity and SpriteKit, and to a more limited extent Illustrator, has stimulated areas of my brain that had kind of shut down. I abandoned design because I thought it was too subjective and that I would never be good at it. I forgot how wonderful it feels to understand a tool well enough to use it to express something you’re thinking or feeling or imagining.

I am glad that I have gotten over my stubbornness about learning Unity. It’s a large and complex tool. I needed some time to mentally process the idea of jumping into this tool and to organize myself so I don’t just curl up in a ball and sob. I feel actively excited about scripting in Unity and I’m looking forward to figuring out some sample projects I can do with it.

Tic Tac Toe: Setting up the Visual Game Board

My goal in 2018 was to post to this blog at least once a week, but life happens. I got sick and I had some obligations for others that prevented me from reaching my goal. Sometimes you have a bad week, but you do your best and keep trying. So in the spirit of that, here is my post for the week.

Now that I have most of my game logic somewhat hammered out, I am going to put it on the back burner and focus on my user interface elements. I am choosing to think of each element as an independent piece rather than focusing on how everything is going to work together. I am hoping if I get each piece working properly, by the time I need to bring them together as an actual game I won’t have to worry too much about their implementation details.

One big question I have with SpriteKit over UIKit is placing elements on a screen. In UIKit we use auto layout to apply rules to the elements to tell them what size they are and how they exist within relation to one another. I know SpriteKit has an Interface Builder-esque scene builder, but I am a masochist and want to do my layout in code.

Game Board Layout

My intention for the game is to only be able to play it in portrait mode and not landscape. I want to think of this layout algebraically to try and get around the lack of auto layout. (Note: It may be possible that auto layout coexists with SpriteKit, but I am stubborn and want to pretend it doesn’t as a thought exercise and to prove a point. Don’t judge me.)

Since the phone is always going to be taller than it is wide, the width is my limiting factor here. I want my board to take up a square amount of space that spans from one side of the screen to the other. I also want the board to be centered in the screen with some space at the top or bottom which will include labels and such at a later state of the game.

Game Layers

So looking at my mock up, I have a board layer that is square and varies based on the width of the screen. Within that board layer, I have nine subviews representing the tic tac toe tiles. Those tiles exist relative to one another within the board layer. So I want to create two separate layers. I also want the tiles in my tile layer to exist relative to that layer and basically know nothing about the larger screen they exist within.

The board layer should be relatively straightforward. We know the length and width of the layer will be the same and that they are both constrained by the width of the screen.

First I need to create the sprite node that will represent the board:

// View Properties
let boardLayer = SKSpriteNode()

To create the view, we simply need to figure out the width of the screen. Next, we want to make the anchor point of the board layer the middle rather than one of the edges. Finally, we need to set the position of the anchor to the middle of the screen.

override init(size: CGSize) {
	super.init(size: size)
		
	anchorPoint = CGPoint(x: 0.5, y: 0.5)
		
	let background = SKSpriteNode(color: UIColor.white, size: size)
	addChild(background)

	let boardSize = size.width
	boardLayer.anchorPoint = CGPoint.zero
	boardLayer.position = CGPoint(x: -(boardSize / 2.0), y: -(boardSize / 2.0))
	boardLayer.size = CGSize(width: boardSize, height: boardSize)
	boardLayer.color = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.2)
	addChild(boardLayer)
}
	
required init?(coder aDecoder: NSCoder) {
	super.init(coder: aDecoder)
}

If you try to build and run this… nothing happens.

I got super confused and did a bunch of color debugging and changing the anchor points and sizes, but nothing was happening. After some digging and breakpointing, I realized that the game scene was never actually loading and that I needed to make some changes to the GameViewController class.

Game View Controller

I assumed that since this was an Apple template that it would just work, but either it doesn’t or I accidentally changed something to prevent it from doing so. I have been referring to a few SpriteKit tutorials on Ray Wenderlich’s site and in the ones I have seen, you need to declare a game scene property and explicitly let it, so that is what I did.

var scene: GameScene!

override func viewDidLoad() {
	super.viewDidLoad()
		
	let skView = view as! SKView
	skView.isMultipleTouchEnabled = false
		
	scene = GameScene(size: skView.bounds.size)
	scene.scaleMode = .aspectFill
		
	skView.presentScene(scene)
			
	skView.ignoresSiblingOrder = true
	skView.showsFPS = true
	skView.showsNodeCount = true
}

This now loads the game scene and you get a nice boring white background with a grey square. Later in this process I will be adding nice graphics, but this works for now. Next, we need to populate the game board with some tiles.

Game Tiles

Since I don’t know how wide my screen is going to be at any point in time, I don’t want to set hard values for the size of my tic tac toe tiles. I want to set their size proportionally as a percentage of a whole rather than hoping that 150 pixels will work well on all screens and adjusting the spaces between them.

The board is a grid of nine tiles. The tiles are all the same size and they form a square. The tiles are closer to one another than they are to the border of the game board. I need to determine how large they need to be and also how to place them within this space.

To determine their width/height, I am going to create an algebraic equation. I know that I need to fit three tiles into the board’s width, so I will be dividing the width by three. However, I also need to account for the spaces between each tile and padding at the edge. So, to determine how large the tiles are I need to do the following calculation:

tileWidth = (boardWidth - (outerPadding * 2) - (innerPadding * 2)) / 3

We now know how to calculate the size of each tile, but we need to actually create each one and make sure we give each one an identifier so that when the player taps the middle square the program knows how to identify it.

Tile Sprites

Earlier in this project I created an array of tile states. This was the game model. We are now working on the game view, so we need analogous view objects that correlate to the model objects.

We will need nine sprite objects that represent a tile in our array of tile state. Each sprite needs to be given a size (which we calculated above), a position, and an identifier. The position is determined relative to the other tiles and relative to the board view. The identifier is the way we will be able to track which sprite has been tapped while the game is being played.

SpriteKit Coordinate System

In order to place objects in space, it’s important to understand SpriteKit’s anchor points and coordinate system. We know how to calculate the size and shape of our tiles, but we also need to know how to explain to Xcode where we want each tile to be placed.

Back when I learned algebra, I became familiar with Cartesian coordinates:

Generic Cartesian coordinate space

It’s the idea that you have an X and a Y axis that intersect at a center point, or origin. Every point in the coordinate plane can be expressed in relation to that center point. Any point that is above the X axis is thought of as positive and anything below the X axis is thought of as negative. Anything to the right of the Y axis is also positive and anything to the left is negative.

In SpriteKit, the center point/origin of the screen is oriented at the bottom left corner:

SpriteKit’s default coordinate orientation

What that means is that every point you look at is effectively going be positive. In this scenario, if you wanted to place an element at the bottom of the screen, offset by twenty pixels, you would set the y-position to 20. If you wanted to place it at the top, offset by twenty pixels, you would set the y-position to screen.size.height - 20.

Alternately, you could place your anchor point at the top right corner of the screen:

Inverted SpriteKit anchor point. Everything on the screen is negative in relation to the anchor point.

This would work the opposite of the default. Instead of thinking of everything positively, you think of things negatively. If you wanted to place an element at the bottom of the screen, offset by twenty pixels, you would set the y-position to -screen.size.height + 20. If you wanted to place it at the top, offset by twenty pixels, you would set the y-position to -20.

For my purposes, I care about building my application from the center out. I have no idea how tall the screen is that my app will appear on, so I need to build everything from the middle out. This means my anchor point will need to split the difference between SpriteKit’s default anchor point and the inverted one:

Center anchor point. Half the coordinates will be positive in relation to the anchor and half will be negative.

This makes placement slightly tricky. Some of my coordinates exist in positive coordinate space and some exist in negative space. Anything to the left of the center of the screen is negative while anything to the right is positive.

Embedded Nodes and Relative Positioning

I have no idea how tall the iPhone displaying my game is going to be. For the last few years Apple has tried to get people to think of screens proportionally rather than absolutely. I can’t position my tiles in relation to the height of the iPhone because that is variable. I went to a bunch of trouble to create a square area at the center of the screen that adjusts its size based on the height of the iPhone. I know this will always be square and I am basing the size and position of my tiles relative to that object.

SpriteKit utilizes a node graph. What this means is that you can add a sprite node as a child of either the scene or of another sprite. The tic tac toe board will have nine sprites that I want to control as one object and place within their own relative context.

Anchor points greatly impact positioning of embedded objects.

Tile Code

First I need variables for the padding around my tiles. I use this in a few places and if I don’t like the way it looks I only want to change the value in one place.

let outerBorderPadding:CGFloat = 30.0
let betweenTilesPadding:CGFloat = 15.0

I am going to use these to calculate the size of my tiles:

let padding = (outerBorderPadding * 2) + (betweenTilesPadding * 2)
let tileSize = (boardSize - CGFloat(padding)) / 3

Next I need to place and name my tiles. I had a creepy convoluted rats nest of code because I was trying to avoid rows and columns, but then I talked through this with The Boyfriend and we came up with something less busted:

var tileCounter = 0

for yIndex in 0..<3 {
	for xIndex in 0..<3 {
		let sprite = SKSpriteNode()
		sprite.color = UIColor.red
		sprite.size = CGSize(width: tileSize, height: tileSize)
		sprite.name = "Tile\(tileCounter)"
				
		let xPosition = CGFloat(outerBorderPadding) + CGFloat(xIndex) * (tileSize + betweenTilesPadding)
		let yPosition = CGFloat(outerBorderPadding) + CGFloat(2 - yIndex) * (tileSize + betweenTilesPadding)

		sprite.anchorPoint = CGPoint.zero
		sprite.position = CGPoint(x: xPosition, y: yPosition)
		boardLayer.addChild(sprite)

		tileCounter += 1
	}
}

There is a tile counter outside of the nested loops so that I can ensure that my tile name correlates to the index it represents in the data model.

We have nested loops for the rows and columns. I was concerned I would need to create persistent objects to keep track of the row and column of each square. That is a valid design pattern that would utilize if I was doing something more complex, but with only nine objects I had hoped to just keep things simple.

For each tile, I need to label the tile so I know which one we are dealing with and I also need to place it properly in relation to the ones around it. Later I will add logic for the squares to have graphics associated with selection and deselection, but for now I simply want to establish that my layout works properly.

In the nested loops, I am creating a tile for a row and column. There are a few ways this could have been placed. In this implementation, I kept the default SpriteKit coordinate system for these sprites, which means the origin is in the lower left corner. We need to account for that in our positioning of the sprites. I am counting the indices of the tiles starting in the top left while the origin is in the bottom left. This doesn’t affect the x-position, but it does affect the y-position. This is why I’m subtracting two from the y-index. The sprite is added to the board and the tile counter is incremented.

Final output of the board.

Conclusion

The current state of the project is available here.

For me, the challenge of figuring out how to place elements programmatically is an incredibly important problem. My aim with a lot of my game development is to do work in board/card games. Since the screens I am working with are variable and the number of elements are variable, it is tremendously important to me to figure out how to emulate auto layout in SpriteKit.

The game logic is relatively simple compared to the amount of programming that goes into the UI. I feel like when people think about programming a game, the thing they focus on is the mechanics and not the layout. Graphics are the most intensive part of game development and there are a lot of problems to solve that you don’t think about because you just kind of expect things to work.