Card Game Mechanics in Sprite Kit with Swift

Update 10/8/2016: This tutorial has been updated for Xcode 8.0 and Swift 3.

For more than 20 years, people have played Collectible Card Games (CCGs). The Wikipedia entry gives a fairly thorough recount of how these games evolved, which seems were inspired by role playing games like Dungeons and Dragons; Magic the Gathering is one example of a modern CCG.

At their core, CCGs are a set of custom cards representing characters, locations, abilities, events, etc. To play the game, players must first build their own decks, then use their individual decks to play. Most players create decks that accentuate certain factions, creatures or abilities.

In this tutorial, you’ll use Sprite Kit to manipulate images that serve as cards in a CCG app. You’ll move cards on the screen, animate them to show which cards are active, flip them over and enlarge them so you can read the text — or just admire the artwork.

Getting Started

Since this is a card game, the best place to start is with the actual cards. Download the starter project which provides a SpriteKit project preset for an iPad in landscape mode, as well as all the images, fonts and sound files you’ll need to create a functional sample game.

Take a minute to look around the project to acquaint yourself with its file structure and content. You should see the following project folders:

System: Contains the basic files to set up a SpriteKit project. This includes AppDelegate.swift, GameViewController.swift, and the storyboard files.

Game: Contains an empty main scene GameScene.swift, and an empty class Card.swift which will manage the game content.

Assets: Contains all of the images, fonts, and sound files you’ll use in the tutorial.

This game just wouldn’t be as cool without the art, so I’d like to give special thanks to Vicki from gameartguppy.com for the beautiful card artwork.

The Card Class

Since you can’t play a card game without cards, start by making a class to represent them. Card.swift is currently a blank Swift file, so find it and add:

You’re declaring Card as a subclass of SKSpriteNode. Since a card can be one of several different cards with their own statistics and image, it makes sense to define an enum. This way you can define a card as a wolf or a bear, and the appropriate values can be set. For now, the only thing different is the image for the card face.

To create a simple sprite with an image, you would use SKSpriteNode(imageNamed:). In order to keep this behavior, you use the inherited initializer which must call the designated initializer of the super class, init(texture:color:size:). The color value used does not matter since you use an image, but since it’s not defined as optional, you have to specify a value. You do not support NSCoding in this game, which is used by the visual designer for sks files.

Properties are defined to store the image for the card front and back. Since these are not optional, they must be initialized by the end of the init(texture:color:size:) method. The switch statement lets you set the image based on the CardType value.

To put some sprites on the screen, open GameScene.swift, and add the following code to the end of didMoveToView(_:):

Note: Depending on screen size, you may want to zoom the simulator window, using Window\Scale\50% to fit on the screen. You can also use the iPad 2 simulator, since its non-retina screen is smaller.

Looking at a couple of cards is fun and all, but the UI will be much cooler if you can actually move the cards. You’ll do that next.

Moving The Cards Around The Board

No matter the quality of the art, cards sitting on a screen won’t earn your app any rave reviews, because you need be able to drag them around like you can do with real paper cards. The simplest way to do this is to handle touches in the scene itself.

The location(in:) method converts the touch location into the scene coordinates.

Use atPoint(_:) to determine which node was touched. This method will always return a value, even if you didn’t touch any of the cards. In that case, you get some other SKNode class. The as? Card keyword then either returns a Card object, or nil if that node isn’t a Card. The if let then guarantees that card contains an actual Card, and not anything else. Without this step, you might accidentally move the background node, which is amusing, but not what you want.

Build and run the project, and drag those two cards around the display.

The cards now move, but sometimes slide behind other cards. Read on to fix the problem.

As you play around with this, you’ll notice several issues:

First, since the sprites are at the same zPosition, they are arranged in the same order they are added to the scene. This means the bear card is “above” the wolf card. If you’re dragging the wolf, it appears to slide beneath the bear.

Second, atPoint(_:) returns the topmost sprite at that point. So when you drag the wolf under the bear, atPoint(_:) returns the bear sprite and start changes its position, so you might find yourself moving the bear even though you originally moved the wolf.

While this effect is almost magical, it’s not the kind of magic you want in the final app.

To fix this, you’ll modify the card’s zPosition while dragging. Instead of hardcoding values, add the following to GameScene.swift, before the class definition.

The line to remove and add the card to the scene may look strange, but it prevents the wolf from jumping underneath the card for the bear if they overlap when the touch ends. The SKNodes are displayed in reverse order that they were added to the scene, with the later nodes on top. You can’t rearrange the order of nodes in SKNode‘s internal storage, but removing and adding the node again has the desired effect.

Build and run the project again, and you’ll see the cards sliding over each other as you would expect.

Cards now correctly move over each other, but looks a little plain. You’ll fix that next.

Pros & Cons Of Scene Touch Handling

Before going any further, let’s stop for a moment and muse upon some of the advantages and disadvantages of handling the touches at the scene level.

Touch handling at the scene level is a good place to start working with a project because it’s the simplest, easiest approach. In fact, if your sprites have transparent regions that should be ignored, such as hex grids, this may be the only reasonable solution.

However, it starts to fall apart when you have composite sprites. For example, these could contain multiple images, labels or even a health bar. It can also be unwieldy and complicated if you have different rules for different sprites.

One gotcha that comes into play when you use atPoint(_:) is that it always returns a node.

What if you drag outside of one of the card sprites? Because SKScene is a subclass of SKNode, if the touch location intersects no other node, the scene itself returns as a SKNode.

This tutorial will continue to do touch handling in the scene, but in your games, you might find it better to have the SKNode subclasses handle their own touches.

Tracking Damage

In many collectible card games, monsters like these have hit points associated with them, and they can fight each other.

To implement this, you’ll need a label on top of the cards so the user can track damage inflicted on each creature. In Card.swift, add the following to the property section at the top of the class:

var damage = 0
let damageLabel :SKLabelNode

Then, add the following to the init(texture:color:size:) method, before the call to super.init(texture:color:size:)

Finally, add this line after super.init(texture:color:size:) in the same method

addChild(damageLabel)

Since the damageLabel property is not optional, it has to be initialized before calling super.init(texture:color:size:). You can’t call instance methods until after super.init(texture:color:size:), so the addChild(_:) call has to be at the end.

This is the general pattern for initializing Swift objects. First, initialize all non-optional properties; then, call super.init(texture:color:size:); finally, call any instance methods needed to complete initialization.

Here you’re using the scale(to:duration:) method of SKAction to grow the width and height of the card to 1.2x its original size when clicked and back down to 1.0 when released. The removeAction(forKey:) call is to stop currently running pickup or drop animations if you tap and release quickly.

Build and run the project to see how this looks.

This simple animation gives the appearance of picking up a card and putting it back down. Sometimes the simplest animations are the most effective.

Tinker with the scale and duration values to find what the levels that look best to you. If you set the lift and drop durations as different values you can make it appear as though that card lifts slowly, then drops quickly when released.

Making The Card Wiggle

Dragging cards around now works pretty well, but you should add a bit of flair. Making the cards appear to flutter around their y-axis certainly qualifies as flair.

Since SpriteKit is a pure 2D framework, there doesn’t seem to be any way to do a partial rotation effect on a sprite. What you can do, however, is change the xScale property to give the illusion of rotation.

Again, you’ll add code to the touchesBegan(_:with:) and touchesEnded(_:with:) pair of functions. In touchesBegan(_:with:) add the following code to the beginning of the if let card section:

And similarly, in touchesEnded(_:with:) add the following before removing the pickup action:

card.removeAction(forKey: "wiggle")

This code makes the card appear to rotate back and forth — just a tad — as it moves around. This effect makes use of the run(_:) method to add a string name to the action so that you can cancel it later.

There is a small caveat to this approach: when you remove the animation, it leaves the sprite wherever it is in the animation cycle.

You already have an action to return the card to its initial scale value of 1.0. Since scale sets both the x and y scale, that part is taken care of, but if you use another property, remember to return the initial value in the touchesEnded(_:with:) function.

Build and run the project, so you can see the cards now flutter when you drag them around.

A simple animation to show that this card is currently active.

Challenge: In the bonus example game at the end of the tutorial, you’ll learn about using zRotation to make the cards wobble back and forth.

Try replacing the scaleXTo(_:duration:) actions with rotateByAngle(_:duration) to replace the “wiggle” animation with a “rocking” animation. Remember to make it a cycle, which means it needs to return to its starting point before repeating.

Try to reproduce this effect for the wiggle animation.

[spoiler]Replace the current wiggle code with the following in touchesBegan(_:with:):

This gives your cards a satisfying little wiggle, but there’s still one problem. Try dropping the card mid-cycle. Does it rotate incorrectly? Yes, and that’s your next problem to solve, by adding the following line to touchesEnded(_:with:) inside the if let card section:

Now you have a nice looking wiggle action that properly rotates itself when you let go of a card!
[/spoiler]

Flipping The Card

Finally, add some card-like actions to make the game more realistic. Since the basic premise is that two players will share an iPad, the cards need to be able to turn face down so the other player cannot see them.

An easy way to do this is to make the card flip over when you double tap it. However, you need a property to keep track of the card state to make this possible.

Open Card.swift and add the following property below the other properties:

var faceUp = true

Next, add a function to swap the textures that will make a card appears flipped:

Finally, in GameScene.swift, add the following to the beginning of touchesBegan(_:with:), just inside the if let card section.

if touch.tapCount > 1 {
card.flip()
}

Now you understand why you saved the front and back card images as textures earlier — it makes flipping the cards delightfully easy. You also hide damageLabel so the number is not shown when the card is face down.

Build and run the project and flip those cards by double-tapping.

Simple card flip by swapping out the texture. The little bounce is the pick-up animation triggered by the first touch.

The effect is ok, but you can do better. One trick is to use the scaleX(to:duration:) animation to make it look as though it actually flips.

The scaleX(to:duration) action shrinks only the horizontal direction and gives it a pretty cool 2D flip animation. The animation splits into two halves so that you can swap the texture halfway. The setScale(_:) function makes sure the other scale animations don’t get in the way.

Build and run the project to see the new “flip” effect in action.

Now you have a nice looking flip animation.

Things are looking great, but you can’t fully appreciate the bear’s goofy grin when the cards are so small. If only you could enlarge a selected card to see its details…

Enlarging The Card

The last effect you’ll work with in this tutorial is modifying the double tap action so that it enlarges the card. Add these two properties to the beginning of Card.swift with the other properties:

Finally, make a small update to touchesMoved(_:with:) and touchesEnded(_:with:) by adding the following line to each, just inside the if let card section:

if card.enlarged { return }

You need to add the extra property savedPosition so the card can be moved back to its original position. This is the point when touch-handling logic becomes a bit tricky, as mentioned earlier.

The tapCount check at the beginning of the function prevents glitches when the card is enlarged and then tapped again. Without the early return, the large image would shrink and start the wiggle animation.

It also doesn’t make sense to move the enlarged image, and there is nothing to do when the touch ends, so both functions return early when the card is enlarged.

Build and run the app to see the card grow and grow to fill the screen.

Basic card enlarging. Would look much better with some animation, and the enlarged image is fuzzy.

But why is it all pixelated? Vicki’s artwork is much too nice to place under such duress. You’re enlarging this way because you’re not using the large versions of the card images.

Using Large Images

Because loading the large images for all the cards at the beginning can waste memory, it’s best to make it so they don’t load until the user needs them.

Add this property to Card.swift at the end of the property section

let largeTextureFilename :String
var largeTexture :SKTexture?

Next, add the initializer for largeTextureFileName by making your switch statement in init(texture:color:size) look like

The card’s position saves before running an animation, so it returns to its original position. To prevent the pickup and drop animations from interfering with the animation as it scales up, you add the removeAllActions() function.

When the scale down animations run, the enlarged and zPosition properties don’t set until the animation completes. If these values change earlier, an enlarged card sitting behind another card will appear to slide underneath as it returns to its previous position.

Since largeTexture is defined as an optional, it can have a value of nil, or “no value”. The if statement tests to see if it has a value, and loads the texture if it doesn’t.

Note: Optionals are a core part of learning Swift, especially since it works differently than nil values in Objective-C.

Build and run the app once again. You should now see a nice, smooth animation from the card’s initial position to the final enlarged position. You’ll also see the cards in full, clean, unpixelated splendor.

Animating the card enlargement, and swapping to the large image make this look much nicer.

Final Challenge: Sound effects are an important part of any game, and there are some sound files included in the starter project. See if you can use SKAction.playSoundFileNamed(_:waitForCompletion:) to add a sound effect to the card flip, and the enlarge action.