Learning Python by Creating a Rock-Paper-Scissors Game!
by kdziubinski in Circuits > Software
384 Views, 2 Favorites, 0 Comments
Learning Python by Creating a Rock-Paper-Scissors Game!
Computer programming may sound hard or unappealing, but you may just have the wrong perspective of programming.
Programming allows you to make something, just like an artist paints, or a welder builds, a developer can create any program or software to solve problems, or just make fun games to enjoy. When you send time on an art piece, and then after a lot of hard work, it looks beautiful. You have an overwhelming amount of accomplishment and pride. When working on a program for a long time, and finally getting it to run the way you envisioned it, you get the same feeling. Once you are free from the fundamentals, you can create and explore endless possibilities.
Learning a programming language is kind of like learning a spoken language. There are grammatical rules you must follow but, it’s a little different then a spoken language. I will walk you through the very basics and you will see it’s not very hard.
Python is the language we will be learning. It’s such a great tool in our day in age. Python is the same language that SpaceX uses to send rockets into space. The same language that Google uses to allow information to be at our fingertips, and the same language that Netflix uses to help us all unwind and relax. Python is an amazing language, it’s the newest and simplest language.
Supplies
A computer, Internet, and a desire to learn something new!
Going to Python's Available Downloads
Travel to this link: https://www.python.org/downloads/ to download python on your system. Depending on your operating system (Windows, Mac, Linux), you will have to download a specific version of python. You should see this towards the top of the page. Click the “Windows”, “Linux/UNIX”, or “Mac” depending on what you are using. Since most people have a windows device, I will show the steps for that one specifically, but don’t worry because it’s the same regardless. Once you click the system you have, look for the title, “Python Releases for Windows”. Then a little below that you will see a subtitle that says, “Stable Releases”. This is where we are going to find the download we want.
Figuring Out Which Installer We Need
Now, we know the version of python we want, but we still have two options, the “windows installer (32-bit)” or the “windows installer (64-bit)”. This is easy to find out what one you need. Just hit ‘WINDOWS KEY + S’ and the windows search bar will pop up. Type “System Information” and hit enter.
You don’t have to click anything, the information is right there. Look 8 items down, and you should see
“System Type” and then to the right you will see either a “x64-based PC” or a “x32-based PC”.
Depending on the number of your system type, that will be the python installer you will download. In
my case I will be doing the 64-bit version. Now just click the download button and wait for it to be done.
The Installation Process
Once you download the installer, its now time to actually unpack python on your system and install it. The installation process is very simple, all of the settings will be kept at the default settings, and all you have to do is check one box, and choose where you want to house python on your computer if you don’t like the spot it suggests. Its not very big so just choose anywhere you feel is sufficient.
Start the Python Installer in your downloads file, or click the download at the bottom of your chrome tab to open it. Follow the red circles below to install Python. Make sure you select add Python to PATH, its optional but if you enjoy python you may need that feature selected in the future to install other software that enhances python development.
Once it says the installation was successful, we are in business. Close the installer.
Starting Up Python
Once again, open the windows search bar by hitting “WINDOWS KEY + S” and type “IDLE”
this is the development environment that you will be able to code python in. Its pretty bare bones, but its good for beginners because of its simplicity. It functions just like any other software where you create something, it has a file tab where you save your work and start new projects. First, we want to change one setting, and turn ON line numbers so when we get errors it tells us the exact line the program stopped on and we know what to fix. Click “Options”, then directly under, click “Configure IDLE”. Click the general tab at the top, it’s the 4th tab down. Then check the box to turn ON line numbers.
Its circled to help you locate the setting in the following image on the next page.
Once you turn on line numbers, click “Apply” and then click “OK”. Now we can start programming but first we must start a new project. Click the “File” tab, and under that, click “New File”. Now we have an empty screen, and this is where we will begin to type our code.
Coding Basics
Now that we finished all the boring stuff, we can start to get our hands dirty and get started. I will be teaching you good habits and not be a lazy programmer. This will help you be more organized and save you time later.
Syntax Tips
print(“Blah Blah Blah”) – This will tell output “Blah Blah Blah”. This print() statement is used to output values, or words.
X = 10 – this will tell the computer that x is now equal to 10. This means X is an integer or “INT” variable because it stores a number.
X = “I am x, rawr” – This will tell the computer that x is equal to “I am x, rawr”. This means X is a string variable because it stores words.
If x == 1: print(“x = 1”) – This is a condition. It says if X is equal to 1, then it will go into the if statement and do the code indented underneath. Its important to indent under condition statements, or loops that keep going until x does equal 1. Then it will move on.
NOTE: The tips above are case sensitive. If you capitalize Print() instead of print() It will give an error when you compile the code, or “run” the code. Also, in the rest of the instructions, type exactly what is in the blue text. Python is case sensitive, and you need to have every quote in the right spot. If you put something somewhere wrong, when you run the program, it will just tell you that you had invalid syntax and say what line its on.
Comments
Comments are used to introduce your program, and to type out what parts of code are used for. When you make a program with hundreds of lines, it helps to have comments because at the time you make it you know exactly what’s going on, but if you ever come back to it you will have no idea what’s going on.
Start by typing a hashtag (#) at the top type: “#FirstName LastName” (Obviously just type your first name and last name) then hit enter and type “#This program is a learning tutorial that teaches how to code python through rock-paper-scissors”. This is a comment, it makes no difference to the computer and the hashtag tells the computer to ignore anything on that line.
Starting the Code
Now you can hit enter a couple of times to move down some lines to make your code look a little cleaner. Try to move down a line or two every time you start a different section. Its optional but it just makes it look cleaner.
Now, Type: print(“Hello! Welcome to my game of Rock-Paper-Scissors!”)
Compile Your Code
This is so exciting; you now just finished your first python line of code. To see if your program works so far, you must compile it. This is commonly referred to as “run”-ing your program. This is the step where the computer reads through the program and looks for any grammatical errors or values not initialized. These errors are called “compile-time errors”. You can now run the program and it will type that out. Let’s see if it worked!
Click the “Run” tab at the top of the window, 4th tab down. Then click, “Run Module” which means compile the program. You will have to save the file first and since this is our first save, we will have to select where we want to save it. Make sure to make a new folder called “Python Programs” or something to keep all your programs together. You can also just save the program to your desktop so you can find it easier later and then move it to a folder when you’re done developing the program. You can name the program whatever you want but just don’t change the save type, it will default to “.py” or “.pyw” which is the one we want. I named my program: “Learning Python Rock-Paper-Scissors”. Once you click save, it will take you back to the Python shell, where we were before we started a new file and changed the settings. This is where you can actively interact with python and where the output of our program will show.
You can see the above image and that's what it should look like.
It worked! We can see it prints out “Hello! Welcome to my game of Rock-Paper-Scissors”
If you had any errors, it is 1 of 3 things, spelling, you didn’t put parentheses, or you didn’t put your quotes around the sentence. Having quotes tells the computer it’s a string and so it just prints out those words, and the print() tells the computer to run the print method.
Coding Our Game, the Introduction
Now is the fun part where you make it personable to you. Feel free to type whatever you want; you don’t need to say “Hello! Welcome to my game of Rock-Paper-Scissors!” it just seemed like a good start to me. You should try and have an introduction to your program regardless, so the user knows what the program is.
Next I did another print() statement and said “You are no match for me. I will destroy you!”
Code: print("You are no match for me. I will destroy you!")
You can also put both print() statements together like this and get the same result
Code: print("Hello! Welcome to my game of Rock-Paper-Scissors!\nYou are no match for me. I will destroy you!")
The “\n” makes the words following it on a new line. So, if you don’t want to have two print() statements but still want the second statement to be displayed on a new line, just add a “\n”. You can also have as many of them as you want. Having a “\n\n” will make it go down two lines. This little trick helps keep a minimum number of lines in your program, but still make the output structured.
Once you do the introduction, you want to tell them the rules of the game. This is once again another print() statement. I decided to just make another print() statement for this one since it’s the rules and not the introduction.
Type the rules out however you wish, but just include the core components, Rock beats Scissors, Paper beats Rock, and Scissors beats Paper.
Code: print('\nThe rules are simple, you can type: "Rock", "Paper", or "Scissors".\nRock beats Scissors, Paper beats Rock, and Scissors beats Paper.')
Notice how I have quotes in my rules. This is an important note because this shows exactly what they must type. But having multiple quotes in your print() statement will give an error because the computer won’t know what you want to print. So instead of enclosing everything in quotes, you can use single quotes ‘these things’ and it will just have the double quotes added to your output. Or you can put a forward slash in the front of the double quotes to tell the computer to ignore the quotes.
These two solutions look like this:
Double Quote with a Forward Slash– print(“Hello please don’t mess up this \“ or even this \” Thanks!”)
Single Quote – print(‘Hello please don’t mess up this “ or even this “ Thanks!’) In my program I just did the single quote solution because having forward slashes are confusing.
Taking User Input
So now it’s time for us to start making the code that won’t be output to the person playing. This is always most of the code because the only things the user should see are the instructions and when they must type things or hit a key.
First, we need create a variable to store the user input, and we can name the variable whatever we want. This is called initializing a variable. Basically, any time you create a new variable. It’s also important to note that you can’t have any spaces and must stick to letters when making variables. So, I named my variable userInput. Following coding ethics, you always lowercase the first letter of the first word then capitalize the rest of the first letter of the remaining words. For example, “thisNameIsValid”, or “justLikeThis”.
Now to tell the computer we want this variable named “userInput”, to store whatever the user types in, we have to set it equal to input() and its handy because instead of typing in a print() statement above the variable saying, “Now input whatever you want”, we can just put what we want to print inside of the input parentheses. Like this: input(“Now input whatever you want”)
Code: userInput = input("\n\nSo... its time to decide, what will it be? Rock, Paper, or Scissors?\n")
Now, userInput will equal whatever the user types in. Now we should test this and make sure we can type in a selection and hit enter. So, go ahead and run the code again. Now you should have another line being printed, and you should be able to type anything in. Once you type a word in, hit enter to initialize the variable.
Let’s see if it stored the word you typed. Type inside of the shell, where you just typed your word, and type “userInput” that will output the userInput.
See how It typed out what you entered. You typed the variable and it sent back what you entered. It worked. It successfully stored the variable. The shell acts as a python program almost in itself, you can say x = 10 and then type in x and it will output 10. Its great for checking if print statements print right or if variables are storing the correct values.
Computer Input
Now that we have our input, we need the computer to select their answer. We will do this by randomly generating a number between 1-3. The number 1 will be rock, Number 2 will be paper, and Number 3 will be scissors. To get a random variable we will have to use another method called randint(), but this method is in a class called random.
To better understand what a method is, imagine you work as a secretary and you have hundreds of folders. You use one of the folders all the time so you don’t need to specify where exactly it is, so you just give the method name like print() or input() and you can find it. But for more uncommon methods, you also need the class it’s from in front of the method. So, in this case we will say random.randint(). It’s in the class random, and it’s the method called randint() inside of random. Just like files and folders.
We also need to import the random class to have access to all its methods. We do this by simply typing import random. Again, following coding ethics, you want to put this at the top of your program. Either right under your comments or above that.
Code: import random
Now we have access to the class random and all of its methods including the randint() method that we will use.
Again, we must store the value that is generated so we can look at it. So, I created a new variable named “computerInput” and set it equal to “random.randint()”. To make the random number generated between 1 and 3, we will put “1,3” inside of the (). Quick side note, you cant just type in anything in the (), you have to enter the needed parameters that the method accepts. The print() method accepts any value (words, or numbers) and can even take multiple values. The randint() method accepts two int values. The first integer being the starting selection of random values, and the second integer is the ending number for the selection of random numbers. Hence why I typed a 1 and 3.
Code: computerInput = random.randint(1,3)
Now we want to make sure it runs properly and actually makes a random number from 1-3. So go ahead and run the program, and then type "computerInput" when the program is done running. It worked, but I'm not sure if its random. Just do the same things a few times and make sure they are different numbers. I made this process a little quicker by just adding print() and then putting computerInput inside to just print it out so I don’t have to type the variable name each time.
Code: print(computerInput)
NOTE: Since it’s a variable you don’t put quotes inside or it will just print out “computerInput” and not the value equal to computerInput. So after about 10 tries I saw computerInput equal to “1”, “2”, and “3”. So I know it works. Now remove the “print(computerInput)” from your code because it was only for testing.
Random Number Converted to Rock, Paper, or Scissors
Now we have to make the number 1 = rock, 2 = paper, and 3 = scissors. This is done by if statements. So if its 1, it will be rock or else paper, or else scissors. Because I know only one of these if statements will be true we will use an if statement, then an else if statement (elif) then an else statement. These are all if conditions, but it lets the computer run a little quicker because lets say the first if statement is true, it wont run through the other three because it knows those ones will be false. You can just do three if statements because this will only make it run a fraction of a second faster, but for huge programs thes small changes add up over time. See the code below.
Code:
3 If statements –
if computerInput == 1:
computerSelection = "rock"
if computerInput == 2:
computerSelection = "paper"
if computerInput == 3:
computerSelection = "scissors"
If, elif, else –
if computerInput == 1:
computerSelection = "rock"
elif computerInput == 2:
computerSelection = "paper"
else:
computerSelection = "scissors"
I will be doing the if, elif, and else simply because you type less that way. Be sure to test and
make sure computerSelection equals rock, paper, or scissors.
Win Conditions
We will use if statements again. But this time we will have to put multiple conditions inside of the if statement. We do this by putting the word “and”, or the word “or”. This makes it easier to have a bunch of if statements in one if statement.
For example:
If x == 1 or x == 2:
print(“x is 1 or x is 2”)
if (x == 1 or x == 2) and (y == 1 or y == 2):
print(“x and y are either 1 or 2”)
Time to elect a winner. So if userInput is rock and then the computer said scissors I win, or if I said paper and the computer said rock I win, or if I said scissors and the computer said paper I win. So if the if statement is true then you put a print under and say the user won.
So then you do a elif statement and have the same conditions but, switched so check if the computer wins and then print the computer won.
Lastly, just an else statement, because if the user didn’t win, and the computer didn’t win. Then they must have chose the same one. So you output there was a tie.
Code:
#conditions when the user wins
if (userInput == "rock" and computerSelection == "scissors")or(userInput == "paper" and computerSelection == "rock")or(userInput == "scissors" and computerSelection == "paper"):
print("\nI chose " + computerSelection + "! It seems you defeated me.. you are obviously cheating.\n")
#conditions when the computer wins
elif (userInput == "rock" and computerSelection == "paper") or (userInput == "scissors" and computerSelection == "rock") or (userInput == "paper" and computerSelection == "scissors"):
print("\nI chose " + computerSelection + "! HA HA HA! I win again, no surprise there.\n"
#conditions for a tie.
else:
print("\n I chose " + computerSelection + "! We tied... UNACCEPTABLE! We must play again so I can beat you!")
Also notice how I can put a variable in between two strings. You do this by separating the two stings with a plus sign. It just adds the variable in without spaces so you have to manage it.
Results
Above is what your code should look like.
We are done. Just run it and you should be able to play the game. These are just the basics but let me know if you want to learn how to add features like playing again, or checking if the user types the right thing because if you just type anything other then rock paper or scissors, it will result in a tie each time. But you just have to add a check to make sure they input either rock paper or scissors.
Thank you for following along and hopefully it wasn’t to long! I wanted to teach as well as show you how so I tried to not just tell you what to type exactly.
Please leave feedback, or ask any questions regarding issues you run into and I can help you out!