Unit 20: Final Project Flashcards

1
Q

Overview

A

In this lesson, you’ll use what you’ve learned throughout the course to ​
build a game: Rock, Paper, Scissors. If you haven’t heard of the game, it ​
works like this:
Two players face each other.
On the count of three, they both make a sign, at the exact same time, ​
with one hand. The sign is either a rock (closed fist), paper (open palm), ​
or scissors (two fingers, open like the victory sign).
Each sign can beat one (and only one) other:
Rock smashes scissors.
Scissors cut paper.
Paper covers rock.
If both players choose the same sign, the game is a draw.
In the game you’ll build, your opponent will be the app itself, so you won’t need to count to three. To play the game, you’ll tap one of the three signs: Rock, Paper, or Scissors.

The app then randomly chooses its own sign and shows the results:
Rock blunts scissors, you win!
The Play Again button goes back to the first screen.
Both screens are in fact the same. The components of the screen change depending on the state of the game.
In this lesson, you’ll build the game logic first, then the UI. Then you’ll put the two together. You won’t get step-by-step guidance, just an outline of what you should do to make the game work. By now you’ve learned everything you need to build the app on your own.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Getting Started

A

Create a new Xcode project using the Single View Application template. Name the app “RPS.”
The first thing is to build the types and rules that will drive the game. ​
This will help you think through everything the app will need to do.
There are three different signs that players can use for their turn. ​
A choice between a limited number of possible values is best represented ​
as an enum.
You’ll write the Swift code to define each new type in a separate file inside the project. Doing this keeps your project organized and easy to understand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Sign Enum

A

Choose File > New > File…, then choose the iOS template set and Swift File from the templates:
After clicking Next, choose the RPS group with the manilla folder icon, and name the file “Sign.swift”:

In the new file, create an enum with cases representing each sign. You can always choose your own names for things you add in this lesson, but it will be easier to follow along if you use names that match these instructions.
Name the enum Sign.
Add a calculated property to give the emoji that represents the Sign.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Game State

A

There are four different states that the game can be in:
Start. The game displays the three signs and is waiting for the player to ​
tap one of them.
Win. The player has won and the app displays each move and a winning message.
Lose. The player has lost and the app displays each move and a losing message.
Draw. The game was a draw and the app displays each move and a draw message.
Create another new Swift file to hold an enum with the four cases as named above. Name the file GameState.swift and the enum GameState.
The diagram to the left shows the relationship between the turns and the state of the game.
You need to be able to compare two Sign instances to give a GameState. ​
For example, a player’s .rock and the app’s .paper would give you .lose.
Add an instance method to Sign that takes another Sign, representing the opponent’s turn, as a parameter. The method should return a GameState based on a comparison between self and the opponent’s turn.
There are many ways that you could write this function. You may wish ​
to work in a playground first so you can check that all the possible combinations give the correct results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Random Sign

A
You need a way to generate a random Sign to act as the app’s turn. The GameplayKit framework contains an API to generate random numbers, as well as to build more complicated aspects of the game. Since you haven’t encountered this framework before now, you’ll get step-by-step instructions.
Add import GameplayKit to the top of the Sign.swift file.
The import statement makes the API from the framework available for you ​
to use.
Add the following line to the file at the top level (not inside any of the struct or enum definitions):
let randomChoice = GKRandomDistribution(lowestValue: 0, highestValue: 2)
If you call the nextInt() method on randomChoice, the GKRandomDistribution instance will give you a random Int between ​
the two values specified in the initializer.
Add this function to the file at the top level:
func randomSign() -> Sign {​
    let sign = randomChoice.nextInt()​
    if sign == 0 {​
        return .rock​
    } else if sign == 1 {​
        return .paper​
    } else {​
        return .scissors​
    }​
}
This function gets a random number, then uses it to create a new Sign instance.
You could now play a full game of Rock, Paper, Scissors by calling functions in a playground. But that’s not as much fun as playing it for real. It’s time to build the UI.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Building the UI

A

Switch to Main.storyboard. Drag a button from the object library onto the scene, and change the button’s title to the (“Fisted hand sign”) emoji. ​
Set the font size to System 70.0.
Duplicate the button twice and set the titles to the correct emoji: ​
(“Raised hand”) and (“Victory hand”).
Arrange the buttons in a rough horizontal line, then select them all and embed them in a stack view. Adjust the spacing so there’s a comfortable ​
gap between the buttons.
Drag in another button below the stack view. This will be the Play Again button.
Drag in a label above the stack view. This will tell the user what’s happening in the game.
Drag in another label at the top of all that. This will show the app’s sign. The font size of this label should be the same as you used for the emoji buttons.
Select the two labels, the stack view, and the button, then embed them in another vertical stack view. Add constraints to pin this stack view to the center of the scene. Adjust the spacing to give some room between the elements.
The final scene should look a little like the screen on the left.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Making Connections

A

Create the following outlets so that you can update the screen during play:
The topmost label, which represents the app’s sign
The next label, which represents the status of the game
One for each of the player sign buttons
One for the Play Again button
Create these actions to handle the button taps:
One for each player button
One for the Play Again button

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Putting it Together

A

In this part of the lesson, you’ll be adding code to ViewController.swift to tie together the game logic and the outlets and actions.
Update the user interface
When the game moves from one GameState to another, you have to update the UI.
Add a method on the ViewController class to update the UI based on a GameState parameter. The method should do the following things:
Set the status label’s text property to an appropriate message. Should ​
the text you use be a calculated property on the GameState enum, or ​
as a string literal inside the method you’re writing?
Set a different background color to the main view depending on the ​
state. UIColor is the type that represents a color.
If the game is in the .start state, do the following:
Reset the computer sign label to the emoji.
Hide the Play Again button by setting the value of the button’s ​
‘isHidden’ property.
Enable and show all of the player sign buttons. (This will make more ​
sense after you’ve implemented the game features to hide and disable these buttons in a later step.)
There are two places where you should call this method in code right now:
Add a call to the method you’ve just added from viewDidLoad().
Add a call to the method you’ve just added from the action method ​
linked to the Play Again button.
After you implement the code for when the player has chosen a sign, you’ll need to call this code to update the UI, as well as to create the app’s move and decide the outcome of the game.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Handle Player Button Taps

A

You should now have separate action methods for each of the player buttons. And each of those methods should call a new method called ‘play’, which takes a Sign parameter.
Add this new ‘play’ method. This method should do the following things:
Get a randomly selected Sign to represent the app’s turn.
Work out the GameState from the two signs, and call the update method you wrote earlier using the new GameState.
Set the app sign label to the appropriate emoji, using the calculated property on Sign you created earlier.
Disable all of the player sign buttons.
Hide all of the player sign buttons except the one the player tapped.
Show the Play Again button.
Make each of the player action methods call the play method, passing in an appropriate value of Sign.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Build and Run

A

Your game is now complete. Build, run, and have some fun. Congratulations!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

20.2: Meme Maker

Overview

A

Finally, you’re going to build an app that lets you add fun captions to a photo.
Selecting each one of the emoji will change the text above and below its image, so you can mix and match statements to suit your mood.
You’ll be using concepts and skills you’ve already learned. At the same ​
time, you’ll get to know a new control, the segmented control.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Getting Started

A

Before you dive in to making the app, spend some time thinking about ​
the content you’re going to use. The app will need the following:
An image to go in the center
Some text options to go above the image, and an emoji to represent ​
each one
Some text options to go below the image, and an emoji to represent ​
each one

Try to think of two, three, or four choices for the top and the bottom. It can be hard to think up working combinations of text. If you get stuck, here’s some inspiration:
Above the image
“You know what’s cool?” could be represented by
“You know what makes me mad?” could be represented by
“You know what I love?” could be represented by
Below the image
“Cats wearing hats” could be represented by
“Dogs carrying logs” could be represented by
“Monkeys being funky” could be represented by
Try to use emoji with different shapes. The segmented control makes them into silhouettes when they’re selected, and it can be hard to tell the difference between a lot of smiley faces.
Once you have your ideas, you can get started building.
Create a new Xcode project using the Single View Application template. Name it “MemeMaker.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Building the UI

A
Open Main.storyboard and add the following items, placing them one below the other:
A segmented control
A label
An image view
A label
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Segmented Control

A

Change the text of the top label to “Top Caption” and the bottom label to “Bottom Caption.” You’ll be changing these in code later, but this step will help to make your storyboard clear.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Segmented Controls

A

Segmented controls are used to offer a choice between a limited number of options. For example, a calendar app might have a segmented control to switch between day, week, and month views. Only one option can be selected at a time. You can control the number of segments and the title of each segment.
When the user taps one of the segments, the Value Changed control event is sent. You can access the index of the selected segment from your code. In this app, you’ll update the caption labels when a different option is chosen.
For now, just leave the segmented controls as they are. You’re going to set them up using code instead of in Interface Builder.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Adding the Image

A

Just as you did in the SinglePhoto lesson, you need to add an image to your project so that it can be displayed as part of the app.
Open the asset catalog and choose an image file to drag in.
Your image can be any shape or size, since the image view will automatically resize to fit it. But that won’t work very well here because you need enough room above and below the image to show your labels and segmented controls. You can configure the image view so that everything will fit on the screen. Switch back to Main.storyboard to add a constraint.
Select the image view and choose the Aspect Fit content mode in the Attributes inspector. (This is the same setting you used in the SinglePhoto lesson.)
With the image view still selected, click the Pin button at the bottom ​
of the Auto Layout screen, then check the Height constraint to set the image view’s height at 250. You may see some Auto Layout errors, but the next step should resolve them.
Finally, use the Attributes inspector to choose the image that you’ve added to the project.

17
Q

Finishing the Layout

A

Select everything you’ve added to the scene and embed it in a stack view. Add some spacing to make the layout more open.
Add constraints so the stack view is centered horizontally and vertically.

18
Q

Making Connections

A

Make outlets for the segmented controls to the ViewController.swift file. Name them topCaptionSegmentedControl and bottomCaptionSegmentedControl. Then name the labels topCaptionLabel and bottomCaptionLabel.
Create an action from one of the segmented controls, then connect the same action to the other segmented control.

19
Q

Defining Custom Types

A

This app has one basic component that powers its behavior: the choice the user makes about the captions. Each choice can be represented by an emoji (for the segmented control) and some words (for the label).
You’re going to define a struct called CaptionChoice to represent each possible choice.
Add a new Swift file to the app to hold the model. Name it “CaptionChoice.swift.”​

​Define a new struct with two properties: the emoji to represent the caption and the caption itself. Name the struct CaptionOption.

20
Q

Putting it Together

A

In this final part of the lesson, you’ll create arrays to hold caption choices, configure the segmented controls, and update the labels based on the options the user has selected. All of this will happen in ViewController.swift.

21
Q

Creating the Choices

A

Create two arrays inside the ViewController class, one to represent the top choices and one to represent the bottom choices. Each array should contain CaptionOption instances matching the ideas you came up with at the start of this project. Name the arrays topChoices and bottomChoices.

22
Q

Configuring the Segmented Controls

A

It makes sense to configure the segmented controls in code rather than using Interface Builder. That’s because the details of the configuration will come from the CaptionOption instances you’ve defined, which aren’t available to you in Interface Builder.
The segments of a segmented control have an index, like the elements of ​
an array. As with an array, the index starts at zero.
You’re going to loop through each array of choices and configure the segmented control along the way. This configuration will happen in viewDidLoad(), which is called once the components from the storyboard have been set up in the running app.

23
Q

Steps

A

First, remove all of the segments from the top control:
topCaptionSegmentedControl.removeAllSegments()
This removes the two default segments that were given when you dragged the segmented control onto the storyboard.
You add segments using the insertSegment(withTitle: at: animated:) method of UISegmentedControl. This has three parameters: The first one is the String that will be the title, the second is the index where the segment will be inserted, and the last is a Bool to say if the insertion should be animated or not.
The title will be the emoji property of each CaptionChoice.
The index can be the count of the topChoices array. (If you supply a number that’s greater than the highest segment index, it just gets added to the end.)
The animated option will be false. (This is all happening before the user gets to see anything, so there’s no point in animating it.)
Loop through the topChoices array and add the new segments in:
for choice in topChoices {​
topCaptionSegmentedControl.insertSegment(withTitle: choice.emoji, at: topChoices.count, animated: false)​
}
Because you removed all of the segments, the control no longer has a selected segment. You can set this with the selectedSegmentIndex property:
topCaptionSegmentedControl.selectedSegmentIndex = 0
The top segmented control now matches the top choices array exactly.
Follow the same pattern to configure the bottom segmented control.
At this point, build and run the project to check that everything you’ve done so far is working. You should see the segmented controls set up with the emoji labels matching your choices.

24
Q

Configuring the caption labels

A

You need a method to set the correct captions based on the selection ​
from each segmented control. The index of the selected segment is ​​
available via the segmented control’s selectedSegmentIndex property. This index can then be used to obtain the correct CaptionChoice from the topChoices or bottomChoices array.
Add a new method to the view controller. Use the selected index from each segmented control to get the correct CaptionChoice, then use it to set the text property of the appropriate label.
Call this method from viewDidLoad() to set up the labels when the app ​
is launched, and also from the action method linked to the segmented controls