Now You Code In Class : Rock Paper Scissors Experiment

In this now you code we will learn to re-factor a program into a function. This is the most common way to write a function when you are a beginner. Re-factoring is the act of re-writing code without changing its functionality. We commonly do re-factoring to improve performance or readability of our code. Through the process we will also demonstrate the DRY (don't repeat yourself principle of coding).

The way you do this is rather simple. First you write a program to solve the problem, then you re-write that program as a function and finally test the function to make sure it works as expected.

This helps train you to think abstractly about problems, but leverages what you understand currently about programming.

Introducing the Write - Refactor - Test - Rewrite approach

The best way to get good at writing functions, a skill you will need to master to become a respectable programmer, is to use the Write - Refactor - Test - Rewrite approach. The basic idea is as follows:

  1. Write the program
  2. Identify which parts of the program can be placed in a function
  3. Refactor the code into a function. Extract the bits into a function into a new, separate cell independent of the original code.
  4. Test the function so you are confident it works, using the expect... actual approach from the lab.
  5. Re-Write the original program to call the function instead.

The Problem

Which Rock, Paper Scissors strategy is better? Random guessing or always choosing rock? Let's write a program which plays the game of Rock, Paper, Scissors 10,000 times and compares strategies. You can get the rock, paper scissors code from the previous lab.

Here's the algorithm:

  1. This 10,000 times
  2. player A's choice = use random strategy
  3. players B's choice = use name every time strategy
  4. play game with A and B's choices
  5. if player A wins increment their win count, else increment player b's win count
  6. print the A and B win counts after 10,000 games.

The Approach

  1. Write the program once
  2. refactor step 4 into its own function play_game(playera, playerb) which returns the winning player.
  3. test the function to make sure it works.
  4. re-write the main program to now call the function.
  5. repeat for the strategies in 2. and 3.
  6. If time, permits write a better strategy inside a function.

In [ ]: