[PYTHON] Final task

Rock-paper-scissors against computer

** * Please read this page as the microphone cannot be used. sorry! ** **

The final task was to create a game to play rock-paper-scissors against a computer using the code learned in the number guessing game. From now on, I'll show you the simplest version of this game and the nice-looking version.

Simple version

It looks like this: basicresult.jpg When you start, the screen shown in the left photo will appear, and when you press the button, the pop-up shown in the right photo will notify you of the win or loss (or draw). Pressing Ok closes the pop-up but keeps the game window open.

Next, I will introduce the code of this game. First, use the following code.

import random
import tkinter as tk
import tkinter.messagebox as tmsg 

** Code meaning: ** ʻImport random Let the computer choose a random value ʻImport tkinter as tk tkinter ʻImport tkinter.messagebox as tmsg` Insert tkinter pop-up

Creating a window

Then use the following code.

root=tk.Tk()
root.geometry("600x400")
root.title("Rock Paper Scissors")
label=tk.Label(root,text="Pick One",font=("Helvetica",30))
label.place(x=200,y=20)

** Code meaning: ** root = tk.Tk () Name the window as root root.geometry("600x400") root.title ("Rock Paper Scissors") Specify window size and title label=tk.Label(root,text="Pick One",font=("Helvetica",30)) label.place (x = 200, y = 20) Specify window characters, fonts and positions

Creating a button

Then use the following code.

button0=tk.Button(root, text="rock", font=("Helvetica",20), command=ButtonClick0)
button0.place(x=100, y=60)

** Code meaning: ** ** button0 = tk.Button **(root, text = "rock", font = ("Helvetica", 20), command = ButtonClick0)Make button0 tk.Button to work as a button button0 = tk.Button (root, text = "rock", font = ("Helvetica", 20), command = ButtonClick0) Create button0 in the window, character, size, command Specify (ButtonClick0)

Create the above code for each button. The final shape of that part is as follows.

button0=tk.Button(root, text="rock", font=("Helvetica",20), command=ButtonClick0)
button0.place(x=100, y=60)`

`button1=tk.Button(root, text="paper", font=("Helvetica",20), command=ButtonClick1)
button1.place(x=200, y=60)`

`button2=tk.Button(root, text="scissors", font=("Helvetica",20), command=ButtonClick2)
button2.place(x=300, y=60)

Finally, create a command that will be executed when the button is pressed. The code for one command is as follows.

def ButtonClick0():
  player_number = 0
  comp = random.randint(0,2)
  if player_number == comp:
        tmsg.showinfo("Results", "tie")
  elif player_number == 0 and comp == 1:
    tmsg.showinfo("Results", "player chose rock, computer chose paper: computer wins")
  elif player_number == 0 and comp == 2:
        tmsg.showinfo("Results", "player chose rock, computer chose scissors: player wins")

** Code meaning: ** def ButtonClick0 (): Specifies the behavior of the command ButtonClick0 player_number = 0 Set the player's value to 0 when this button is pressed comp = random.randint (0,2) When this button is pressed, the computer will select a random number between 0-2 if player_number == comp: elif player_number == 0 and comp == 1: elif player_number == 0 and comp == 2: Specify the command for each condition (when the player number (0) is the same as the computer, when the computer value is 1 or 2) tmsg.showinfo("Results", "____") Specify the title and text of the pop-up that appears under each condition Write the above code for all the values that the player can select.

Finished product

The completed code is as follows. Screen Shot 2020-07-05 at 9.12.18 PM.png

A nice looking version

It looks like this: fancyresult.jpg

Code changes

First, let's insert a photo with from PIL import ImageTk, Image. Since all the images to be inserted are in the same file, create the string dir =" / Users / satokamimura / Desktop / school / uni / computer exercises / newgame / ". This will allow you to use dir + filename.png when inserting the image.

Next, change the code of label to the following code to change the character of the window.

title = ImageTk.PhotoImage(Image.open(dir+"text.png "))
titletext = tk.Label(root, image= title).place(x=100,y=20)

** Code meaning: ** title = ImageTk.PhotoImage Specify the image name as title titletext = tk.Label Name the next Label titletext (root, image = title) .place (x = 100, y = 20) Display in the root window, make the image the title you specified earlier, and specify the location on the window.

Next, change the code of the button as follows.

img = ImageTk.PhotoImage(Image.open(dir+"rock.png "))
button0=tk.Button(root, command=ButtonClick0, image = img).place(x=150, y=150)

** Code meaning: ** ʻImg = Image.Tk.PhotoImageSpecify the image name as img button0 = tk.ButtonSpecify the button name as button0 (root, command = ButtonClick0, image = img) .place (x = 150, y = 150)` Display in the root window, specify the command when clicked to ButtonClick0, specify the image to the previous img, button Specify the location of

If you do the same for the other two buttons, all the buttons will be images of their respective rock-paper-scissors.

Next, create a window to display the results. Here, specify only the part of the window format that does not change with any result.

def popup():
  global win
  win=tk.Toplevel()
  win.geometry("500x200")
  win.title('Results')
  tk.Button(win, text='Ok', command=win.destroy).place(x=190,y=172)
  tk.Button(win, text='End Game', command=root.destroy).place(x=250,y=172)

** Code meaning: ** global win Specify a new window'win'globally (by including this, you can use'win' in other parts of the code, which is useful in the part of the code that describes the result. Become.) Create a new window named win = tk.Toplevel () win win.geometry, win.title Specify window size and title tk.Button (win, text ='Ok', command = win.destroy) .place (x = 190, y = 172) Specifies the Ok button and its location to close a new window when pressed tk.Button (win, text ='End Game', command = root.destroy) .place (x = 250, y = 172) When pressed, the game window also closes Specify the End Game button and its location

Then modify the button command. Specifies the code that follows if, elif for all commands to display the new window created earlier from tmsg.showinfo and an image showing the results. ex.:

def ButtonClick0():
  player_number = 0
  comp = random.randint(0,2)
  popup()

** Code meaning: ** popup () Whatever the result, first get a popup to show the result

Then try to display the correct result for each possible pattern. The code is all the same except for the pattern name and image name, so only one example is given here.

if player_number == comp:
      rocktie= ImageTk.PhotoImage(Image.open(dir+"rocktie.png "))
      tk.Label(win, image=rocktie).place(x=0, y=0)
      popup.pack()

** Code meaning: ** rocktie = ImageTk.PhotoImage Specify the name of the image as rocktie tk.Label (win, image = rocktie) .place (x = 0, y = 0) Display the image in a window and specify the location popup.pack () Code needed to make a popup window pop up with an image

Create an image of all the resulting patterns and specify the above code for all the patterns. The images used are a total of 9 images for all patterns. Screen Shot 2020-07-07 at 3.42.27 AM.png

The completed code is as follows.

import random
import tkinter as tk
from PIL import ImageTk, Image

dir = "/Users/satokamimura/Desktop/school/uni/Computer exercises/newgame/"


root=tk.Tk()
root.geometry("600x400")
root.title("Rock Paper Scissors")

def popup():
  global win
  win=tk.Toplevel()
  win.geometry("500x200")
  win.title('Results')
  tk.Button(win, text='Ok', command=win.destroy).place(x=190,y=172)
  tk.Button(win, text='End Game', command=root.destroy).place(x=250,y=172)
  
def ButtonClick0():
  player_number = 0
  comp = random.randint(0,2)
  popup()
  if player_number == comp:
      rocktie= ImageTk.PhotoImage(Image.open(dir+"rocktie.png "))
      tk.Label(win, image=rocktie).place(x=0, y=0)
      popup.pack()
  elif player_number == 0 and comp == 1:
      rocklose= ImageTk.PhotoImage(Image.open(dir+"rocklose.png "))
      tk.Label(win, image=rocklose).place(x=0, y=0)
      popup.pack()
  elif player_number == 0 and comp == 2:
      rockwin= ImageTk.PhotoImage(Image.open(dir+"rockwin.png "))
      tk.Label(win, image=rockwin).place(x=0, y=0)
      popup.pack()

def ButtonClick1():
  player_number = 1
  comp = random.randint(0,2)
  popup()
  if player_number == comp:
    papertie= ImageTk.PhotoImage(Image.open(dir+"papertie.png "))
    tk.Label(win, image=papertie).place(x=0,y=0)
    popup.pack()
  elif player_number == 1 and comp == 0:
    paperwin= ImageTk.PhotoImage(Image.open(dir+"paperwin.png "))
    tk.Label(win, image=paperwin).place(x=0,y=0)
    popup.pack()
  elif player_number == 1 and comp == 2:
    paperlose= ImageTk.PhotoImage(Image.open(dir+"paperlose.png "))
    tk.Label(win, image=paperlose).place(x=0,y=0)
    popup.pack()

def ButtonClick2():
  player_number = 2
  comp = random.randint(0,2)
  popup()
  if player_number == comp:
    scissorstie= ImageTk.PhotoImage(Image.open(dir+"scissorstie.png "))
    tk.Label(win, image=scissorstie).place(x=0,y=0)
    popup.pack()
  elif player_number == 2 and comp == 0:
    scissorslose= ImageTk.PhotoImage(Image.open(dir+"scissorslose.png "))
    tk.Label(win, image=scissorslose).place(x=0,y=0)
    popup.pack()
  elif player_number == 2 and comp == 1:
    scissorswin= ImageTk.PhotoImage(Image.open(dir+"scissorswin.png "))
    tk.Label(win, image=scissorswin).place(x=0,y=0)
    popup.pack()

title = ImageTk.PhotoImage(Image.open(dir+"text.png "))
tk.Label(root, image= title).place(x=100,y=20)

img = ImageTk.PhotoImage(Image.open(dir+"rock.png "))
button0=tk.Button(root, command=ButtonClick0, image = img).place(x=150, y=150)

img1 = ImageTk.PhotoImage(Image.open(dir+"paper.png "))
button1=tk.Button(root, command=ButtonClick1, image=img1).place(x=270, y=150)

img2 = ImageTk.PhotoImage(Image.open(dir+"scissors.png "))
button2=tk.Button(root, command=ButtonClick2, image=img2).place(x=390, y=150)

root.mainloop()

Difficult part

I wanted to change the look of the resulting pop-up, but tkinter's showinfo has very limited changes, so I ended up creating a new window that looks like a pop-up. At that time, I didn't know how to make a new window, so that was the hardest part. Also, inserting the image was a little tricky at first. When I first made this game, I specified a new window for all the resulting patterns, so it was a tremendous number of lines of code. I summarized the basic code of the pop-up to omit it, but at first it was difficult because I could not cooperate with the code of displaying the image as I expected.

Points that I was happy to use

--Pattern command names --By associating the name of a command with the content of that command, you can see what it means at a glance at the code. ――When you use many commands that do similar things, you only have to copy and paste and change them a little, so you can save time and effort. --Collect related files into one folder --By grouping files (image files) used in the same project into one folder, you only need to copy and paste the code and change the file name when using multiple images. ――This is convenient because you don't have to retype the path of the file every time you insert an image. --Create another file to test your code ――The first time you use a code that you haven't used, it's better to first understand how the code can be used. ――Therefore, it is convenient to create a test file to try with only the new code.

References

https://stackoverflow.com/questions/45228664/tkinter-nameerror-name-toplevel-is-not-defined https://stackoverflow.com/questions/41574168/how-to-i-position-buttons-in-tkinter/41575504 https://stackoverflow.com/questions/10052410/tkinter-button-does-not-appear-on-toplevel https://stackoverflow.com/questions/16242782/change-words-on-tkinter-messagebox-buttons https://stackoverflow.com/questions/32060837/remove-border-of-tkinter-button-created-with-an-image https://www.geeksforgeeks.org/pyqt5-add-image-icon-on-a-push-button/?ref=rp https://stackoverflow.com/questions/25703446/whats-the-main-difference-between-if-and-else-if https://docs.python-guide.org/scenarios/imaging/

Recommended Posts

Final task
Final product
AHC task (2) append