Creating a Basketball Simulation App With Swift: Part 1

We just have to create some players and teams first.

Making Our Players and TeamsLet’s return to our PlayerFunctions.

swift file.

We’ll be making a new function to create a random Player object whenever we need it:Function for making a random basketball player.

We’ll be randomizing the values for their offense and defense, but we want to make each generated player somewhat balanced in skill.

Therefore, their offense and defense scores will always add up to 100.

We should now come back to TeamFunctions.

swift.

For each team, the easy part will be adding the players to the roster.

We can just append five generated Players to the roster array of a Team.

Next will be determining the overall offense and defense team ratings.

For this, I just take the average ratings of all players on the roster.

The final function will look like this:Function for constructing a random basketball team.

Now, let’s see what this looks like.

Running Our Basketball GamesTo run this, let’s head back to our ViewController.

swift file.

The code in this file executes when running the app, specifically the code within the viewDidLoad method.

Within that method, we’ll run five different games, using the code we just wrote:Running five basketball games.

In each game, we’ll have different players and different teams.

Let’s run the app by clicking the Play icon near the top.

Here’s the result in Xcode’s console:Console result of five basketball game simulations.

Success!.We’ve got ourselves five pseudo-regulation basketball game results, and they look pretty decent.

We do have quite a bit of fluctuation with the total points scored for some games, but at least the games seem to be closely contested for the most part.

ConclusionI had a lot of fun coding this part up, and I’m glad I decided to make a blog entry about it.

Reading technical blogs has been a hobby of mine since sophomore year of college.

It’s fun when a random topic you search for already has detailed writing on it.

I’m not sure what the next stage of the app will be about, but I’ll try to make it just as interesting.

.

. More details

Leave a Reply