Rock Paper Scissors Python Lab Project Dan McElroy This presentation is offered under the (CC BY-NC-SA 4.0) Creative Commons Attribution Non-Commercial Share license. Hello everyone. Welcome to an introduction to programming. I am using a Python program that plays the Rock Paper Scissors game for this discussion. This discussion covers how to use a development system to enter and run a Python program. 1 The Rock Paper Scissors Game Rock-Paper-Scissors is also known as Roshambo. How the game is played. Two people play against each other by raising their arms slightly and as they each bring one hand down on the count of three. Each person makes a sign that indicates Rock with a fist, Paper with a flat palm and fingers together, or Scissors with two fingers sticking out. Both people need to make their sign known at the same time. You can't change your sign once you start seeing your opponent's sign when you think you might lose. If both people make the same sign, it's a tie. Otherwise, rock crushes scissors and wins. 2 Paper covers rock and wins. Scissors, cuts paper and wins. It's kind of difficult to play this game by yourself. 2 Rock Paper Scissors Project Discussion • • • • • • The Rock Paper Scissors Game The onlineGDB development system Python code for the game Random numbers, arrays, if…elif…else statements How to enter and run the program Document the project in the lab report For your lab assignment, you just need to type in the Python program, make it work and complete the lab report. I am providing a fairly detailed description of the inner workings of the program to give you an idea of how programs work and how programmers design a solution to a problem. I have provided similar projects to students in programming classes with a partial solution to help get started. Some students came up with a solution that was completely different from the sample solution. Wow! Their solution was totally cool, super short to write but very abstract. This presentation covers. The Rock Paper Scissors Game. 3 The onlineGDB development system. Python code for the game. Random numbers, arrays, if…elif…else statements. How to enter and run the program. Document the project in the lab report. 3 Creative Commons License The solution provided here is a modification of the Rock Paper Scissors program at https://TheHelloWorldProgram.com/python/pythongame-rock-paper-scissors/ A big thank you to the people at "TheHelloWorldProgram.com" for sharing their work through the Creative Commons Non-Commercial ShareAlike 4.0 International license. This license permits people to modify the code for the program provided that appropriate credit is given, people can't make money off it and any modifications must be shared using the same license. 4 Other types of software distribution include. Freeware - free to use and distribute, but you don't get a copy of the source code. Shareware - you get a free copy of the software, but you are expected to pay if you choose to use it. Open Source - the source code is available. Sometimes restrictions exist that you are required to pay if you use it. Propriety - source code is not provided, it is protected by copyright and remains the property of the creator. 4 Run the Rock Paper Scissors Game I ran the Rock Paper Scissors program and played five times. The first time I chose Rock and the computer chose Paper. I lost, because paper covers rock. I played again and this time chose Paper. So did the computer and it was a tie game. Then I chose Scissors and so did the computer. It was another time game. I chose Scissors again the next time, but the computer chose Rock. Rock crushes scissors and I lost. Then I tried to be fancy and choose rock but didn't capitalize 5 the R. It didn't like my spelling. Stupid game. It looks like capitalization matters when I make my choice. 5 Rock Paper Scissors Project Write a program to play the rock-paper-scissor game. The user chooses either Rock, Paper or Scissors, and the computer chooses Rock, Paper or Scissors. The program announces either a tie or the winner and the basis for determining the outcome. Paper covers rock, Rock breaks scissors, Scissors cut paper, or a tie game. The program should include a loop that lets the user play again and again until program is stopped. Here is the project definition. Write a program to play the rock-paper-scissor game. The user chooses either Rock, Paper or Scissors, and the computer chooses Rock, Paper or Scissors. The program announces either a tie or the winner and the basis for determining the outcome. 6 Paper covers rock, Rock breaks scissors, Scissors cut paper, or a tie game. The program is to include a loop that lets the user play again and again until program is stopped. 6 Truth-Table A Truth-Table is used to simplify the design and to make sure that all conditions are tested. A Truth-Table lists each possible combination for player and computer. Possible entries for player are along the left side. Possible choices for the computer are along the top. This is a 3 by 3 grid with 9 possible results. Entries are placed in the truth table to show the result for each combination of Player and Computer. 7 List All Possible Combinations Option 1 – Test Each Individually There are nine possible results when playing the game. The program can be written to individually test the possibility of each outcome. This would mean nine separate tests. 8 List All Possible Combinations Option 2 – Three groups of three The program could also be written by dividing the results into three groups of three combinations. If the player selects Rock, then what are the three possible results for the computer's selections. Similar for when the player selects Paper or Scissors. The program code could be organized this way, but there would still be nine tests. 9 List All Possible Combinations Option 3 – Test for TIE, then others The code provided by TheHelloWorldProgram.com has the program organized this way. First, the code checks to see if the player and computer selected the same choice. If this is true, then it is a tie game. If not, keep going down the list. If the player selected Rock, then check the computer's selection for Paper or Scissors. We don't need to check the computer for Rock, because we already know that if both are the same, that condition has already been tested. If the computer selected Paper, then the computer wins. The only other possible computer selection is Scissors. If that happened, then the player won because Rock breaks Scissors. 10 Do something similar for when the player selects Paper or Scissors. Just make sure that the winning and losing combinations are listed correctly. If the program is coded with this combination of tests, then there are only 7 tests necessary, not 9. When the program runs, you will probably never notice any difference how it works or how fast it runs. So! Which is the best way to code the program? It really doesn't matter as long as the program works and produces the correct results. It's like if I asked two people to write an essay on the exact topic. The essays may cover the same information, but they would be written differently. The same thing happens when programmers write code. 10 Python Code for the Game Download an image of the code from Canvas or the web https://program-info.net/ PythonRockPaperScissors.png Description of the program Arrays Loops Random Numbers if…elif…else statements print statements Get a copy of the code either from the class Canvas website, or directly from the web. An image of the code and the lab report form are available at https://program-info.net/PythonRockPaperScissors.png The code for the project is a modification of the code provided by TheHelloWorldProgram.com You need to enter the code that I am providing, not the code available from TheHelloWorldProgram.com 11 Literals and Variables List of variables in the program possibleSelection - an array that holds "Rock", "Paper", "Scissors" playerSelection - holds the player's selection from the keyboard computerSelection - holds the computer's random selection from the possibleSelection array. Literals and variables print("Computer selects", computer) A literal is a notation for representing a fixed value in source code. Literals can be numeric values such as 57, -3, etc. or a string of characters such as "Hello". A variable sets aside a place in memory to hold data that can be changed while the program is running. Variables are given names by the programmer to make programming easier. Here is a list of the variables used in the Rock Paper Scissors program. possibleSelection - an array that holds "Rock", "Paper", "Scissors" playerSelection - holds the player's selection from the keyboard 12 computerSelection - holds the computer's random selection from the possibleSelection array, "Rock", "Paper", or "Scissors". This print statement contains both a literal, "Computer selects" and a variable named computer. If the computer selection was "Paper" then the print statement combines the literal and variable together and displays, "Computer selects Paper". Python uses the word print to display messages to the video console. Early computers used a printing Teletype device as the console and the word Print has stuck around since then. 12 Arrays The position in an array is called an index An array contains a list of similar data items. This program uses an array of three elements to hold the character strings: "Rock", "Paper" and "Scissors". The name of the array is possibleSelection. This array is declared as possibleSelection = ["Rock", "Paper", "Scissors"] An array contains a list of similar data items. This program uses an array of three elements to hold the character strings: "Rock", "Paper" and "Scissors". The name of the array is possibleSelection. This array is declared as possibleSelection = ["Rock", "Paper", "Scissors"] 13 Arrays possibleSelection = ["Rock", "Paper", "Scissors"] array name index Access the contents of an array by its name and index value possibleSelection[1] This is equal to "Paper" The position in an array is called the index. The first element in an array is at index position 0. This array has three elements and index values from 0 to 2. The contents of an array can be accessed by using the name of the array, an open square-bracket [ the index value, and a closing square-bracket. For example, possibleSelection[1] contains the value "Paper" 14 Structured Programming Sequence Selection Repetition Process Decision Loop? No Yes Process Process Process Process Process The concept of structured programming states that all programs can be created with only three constructs: Sequence, Selection and Repetition or a combination of any of them. Sequence is the easiest to understand. Program steps are executed sequentially, one after another. Many times, the order in which the steps are executed is very important. Other times it does not matter. For example, if I were baking a cake, it may not matter very much whether I put the egg in the bowl and then the flour or reversed the two before mixing them with water. However, it would make a lot of difference if I put the cake batter in a 9 x 13 baking dish and placed it in an oven for 1 hour and 30 minutes, took it out and then turned the oven on to 350 degrees. Yuck. 15 The selection structure is commonly implemented with if…else if…else statements. The decision is made with a logical expression or test that evaluates to true or false. In Python, the else…if words are combined into elif. The repetition structure gives the ability for the program to repeat a sequence of statements over and over again. The test for looping can be either at the beginning or the end of code that belongs to the loop. In most cases, something in the code attached to the loop should cause the loop to end. We need to look at the Rock Paper Scissors code to see if it will have a condition to cause the loop to end. 15 Use a Loop to Repeat the Game Line 11 in the code has the while has a block of code attached that will loop as long as the condition while playerChoice is equal to False. The double == operator is a test for equality to see if both sides of == are the same. We can see on line 9 that playerChoice is set to False and line 11 says to loop if playerChoice is False, so it loops. All of the code after the while statement is indented, which means that this is the block of code that will loop. 16 Input the User's Selection playerChoice = input("Rock, Paper, Scissors? ") On the screen when the program runs Prompt message User Input saved in playerChoice Several things happen with this statement on line 14. The single equal sign = is the assignment operator. Everything on the right side of the = is evaluated first then the result is placed in the variable on the left side of the = operator. input("Rock, Paper, Scissors? ") does two things. The text inside the double-quotes " is the prompt message which is displayed on the screen asking the user to input something. The input(. . .) function collects the keys typed at the keyboard. The assignment operator takes the result from the input(. . .) function and places it in the playerChoice variable. Putting all this together, a message is displayed, "Rock, 17 Paper, Scissors? " and waits for the user to type something. If the user types, "Paper", then the word "Paper" is saved in the playerChoice variable. 17 Random Number Generator The program is using Python's random number generator to choose a selection for the computer. The first executable line in the program is from random import randint This gives the program the ability to use the randint( ) function which is available from Python's library of functions. Line 15 has computerChoice = possibleSelection[randint(0,2)] The first thing executed is randint(0,2) which randomly chooses a number from 0 to 2. Which means the values 0, 1 or 2 will be chosen. The program then uses that choice to pick either Rock, 18 Paper or Scissors from the possibleSelection array. The assignment operator = then saves that value in the computerChoice variable. 18 Flowchart to Determine a Tie or Winner START while Loop Player "Rock" No Input from user Yes Computer selection Computer "Paper" Tie? Yes Tie "Tie Game" No Yes No Lose Win Paper covers Rock breaks Rock Scissors Player "Paper" Yes No Computer "Scissors" Yes Lose Scissors cut Paper No Win Paper covers Rock Player Scissors Yes No X Computer "Rock" Yes Lose Rock breaks Scissors No Win Scissors cut Paper Here is a flowchart giving a visual presentation of how the program works. Actually, the while statement is coded to cause the program to loop forever. You need to click the STOP button at the top of the development system to stop the program. Later in this presentation, we can examine possible enhancements on stopping the program a different way. The code flows down sequentially to get the user's input, a random selection for the computer, then test to see if they are both the same. If the user's and the computer's selection are the same, then it is a TIE game. 19 A message is displayed, then the program goes back to the top of the loop. If it isn't a tie game, the program checks to see if the player entered "Rock" If not, see if the player entered "Paper" If not, see if the player entered "Scissors" For any of those three entries by the user, drop down and determine a winner or loser based on what the computer's random selection was. If the player entered something other than Rock, Paper or Scissors, then display an error message and ask the user to re-enter their choice. I ran out of room on the page when that happens, So, do me a favor and pretend that it's there. 19 Determine a Tie, Winner or Loser Use a combination of if…elif…else statements to determine if it is a tie, the user wins or the computer wins the game. In Python, the if statement needs a condition that evaluates to TRUE or FALSE. If the condition is true, do one thing, otherwise, do something different. For example, if I was writing a program for an ATM machine, if withdrawal request is less than the balance on the account, give the money, else display a message, "insufficient funds for the transaction". Program complexity can increase with a series of if. . .elif. . .elif. . .else statements. Each of the if and elif statements need to have a condition that evaluates to TRUE or FALSE. If any of them evaluate to TRUE, the its block of code is 20 executed and the rest of the elif and else statements are skipped. The else statement does test for any condition. The else statement is at the end of the sequence and executes as a default if nothing else passed. 20 Input Validation Your program still needs to verify that only selections of Rock, Paper or Scissors were entered by the user. Display a message indicating illegal input if anything except those three selections were entered. Remember the red 'X' on the flowchart where I ran out of room? This is covered by the last else statement and processes the default when the user entered anything except "Rock", "Paper" or "Scissors". When that happens, the program displays a message, "That's not a valid play. Check your spelling!" This will happen even if the user types "rock" without the capital-R. If you are the programmer, make your error messages polite and don't insult the intelligence of the people using the software. Maybe, that error message wasn't very polite. 21 The onlineGDB.com development system • What is onlineGDB.com • Starting onlineGDB.com • Select the language • Adjusting window sizes Writing the code is only the first step. You also need a compiler or interpreter program to actually run the program. One of the best tools I have found is onlineGDB.com It can run C, C++, HTML, Python and code from several other programming languages. You don't need to install any other applications on your computer to use onlineGDB.com It runs on the cloud, somewhere in the world. Use any browser and put onlineGDB.com in the address bar. When it starts, select Python 3 as the language. Enter the program in the code window. After the code is entered, click the RUN button at the top of the window. 22 If there are any errors, go back and fix them. Error messages will appear at the bottom in the console window which has white letters on a black background. The error messages indicate the line where the error was detected. Sometimes the actual error occurred on a previous line but was only detected later. Be careful when typing and make sure that capital letters and small letters are entered correctly. For example, if a variable is declared as playerChoice with a capital-C and one time in the program a small-C was entered, Python will won't link these two names together and instead create two separate variables causing the program to not produce correct results. The console window is at the bottom. You can resize this window by grabbing the top of the window with your mouse or touch-pad and moving it up or down. 22 Indent Using the Tab Key Use the TAB key to indent a Python program. Don't use the space bar. Use Shift+TAB to indent to the left. No indentation. Level 0 Indentation Level 1 Indentation Level 2 Indentation Level 3 Some programming languages use words like "Begin" and "End" or open and close curly-braces { and } to identify a block of code. Python does neither. It uses indentation to space in blocks of code that belong to a higher level of code. For example, lines 10 through 36 are indented to level-1 indicating a block of code belonging to the while statement on line 9. The print statement on line 16 is indented to level-2 because it belongs to the if statement on line 15. The print statement on line 19 is indented to level-3 because it belongs to the if statement on line 18. 23 For best results when entering a Python program, use the TAB key to indent to the right for each level of code. Use Shift+TAB to move the indentation to the left. 23 Possible Enhancements • Ignore case during comparisons ("Rock" vs. "rock") • Game counter • Keep track of win/lose percentage 24 Comments Comments in Python start with the hash-mark # and stop at the end of the line. Comments are provided as a way of documenting the program and helping the next person who reads the code to understand it easier. For full credit on the project, you also need to enter all of the comments as shown on the provided code. Comments in Python start with the hash-mark # and stop at the end of the line. Comments are provided as a way of documenting the program and helping the next person who reads the code to understand it easier. For full credit on the project, you also need to enter all of the comments as shown on the provided code. 25 Save a Copy of Your Program After you have the program working correctly, make sure you save a copy to your computer and in the lab report. a) click the cursor in the code window, copy to the clipboard (Ctrl+A, Ctrl+C on Windows) or (Command+A, Command+C on macOS) then (Ctrl+V or Command+V) to paste it in your lab report. b) Use the download button on onlineGDB. This should save the code in the Downloads directory of your computer in a file named main.py After you have the program working correctly, make sure you save a copy to your computer and in the lab report. a) click the cursor in the code window, copy to the clipboard (Ctrl+A, Ctrl+C on Windows) or (Command+A, Command+C on macOS) then (Ctrl+V or Command+V) to paste it in your lab report. b) Use the download button on onlineGDB. This should save the code in the Downloads directory of your computer in a file named main.py 26 Document the Project in the Lab Report • Insert screenshots • Insert the Python code Instructions in the lab report have instructions on how to get a screenshot of your console window. Insert screenshots Insert the Python code Instructions in the lab report have instructions on how to get a screenshot of your console window. 27 And again, a great big welcome to the wonderful world of programming using Python. Dandalf signing off for now. 28