[PYTHON] Make a squash game

What is a squash game?

A squash game is a game in which a ball that hits the edge of the screen and bounces off is hit back with the mouse.


How to make

Step1: Let's create windows and canvas

# coding:utf-8
import tkinter as tk

#Creating a window
win = tk.Tk()
#Creating a canvas
cv = tk.Canvas(win, width=640, height=480 ,bg="white")
#Canvas display
cv.pack()

#Window display
win.mainloop()

Step2: Draw a ball and move it

Move the ball ➝ Show or hide the ball

Erase the ball

  1. Display a ball of the same color as the background
  2. Turn off all screens after displaying the ball ☜ This time

Step 1: Set variables

#Game initialization
ball_ichi_x = 300 
ball_ichi_y = 150
ball_idou_x = 30
ball_idou_y = -30
ball_size = 10

Step 2: Draw a screen

#Screen drawing
def draw_screen():
    #Clear screen
    cv.delete('all')← Command to turn off the screen
    #campus(screen)Creation
    cv.create_rectangle(0, 0, 640, 480, fill="white", width=0)

Step 3: Draw a ball

#Draw a ball
def draw_ball():
    cv.create_oval(ball_ichi_x - ball_size, ball_ichi_y - ball_size, ball_ichi_x + ball_size, ball_ichi_y + ball_size, fill="red", width=0)

Step 4: Move the ball

#Ball movement
def move_ball():
    global ball_ichi_x, ball_ichi_y, ball_idou_x, ball_idou_y

    #Judgment of hitting the left and right walls
    if ball_ichi_x + ball_idou_x < 0 or ball_ichi_x + ball_idou_x > 640:
        ball_idou_x *= -1
               ↓
     ball_idou_x = ball_idou_x * -1

    #Judgment of hitting the ceiling or floor
    if ball_ichi_y + ball_idou_y < 0 or ball_ichi_y + ball_idou_y > 480:
        ball_idou_y *= -1
    
    #Move the position of the ball
    if 0 <= ball_ichi_x + ball_idou_x <= 640:
        ball_ichi_x = ball_ichi_x + ball_idou_x
    if 0 <= ball_ichi_y + ball_idou_y <= 480:
        ball_ichi_y = ball_ichi_y + ball_idou_y
    
#Command for repeating game processing
def game_loop():
    draw_screen()
    draw_ball()
    move_ball()
    win.after(50, game_loop) #Timer setting

#Main processing of the game
game_loop()← Call a function

Set "global" when using variables set inside a function outside the function The unit of time of the timer is millimeter (1/1000) seconds


Execution result

tk-2020-07-08-11-44-27.gif


Step3: Let's remodel into a squash game

Step 1: Set variables

#Game initialization
def init_game():
    global is_gameover, ball_ichi_x, ball_ichi_y
    global ball_idou_x, ball_idou_y, ball_size
    global racket_ichi_x, racket_size, point, speed
    is_gameover = False #Confirmation of game end(False if not finished/True when finished)
    ball_ichi_x = 0
    ball_ichi_y = 250
    ball_idou_x = 15 
    ball_idou_y = -15 
    ball_size = 10
    racket_ichi_x = 0
    racket_size = 100
    point = 0 #point(Initially 0 points/Increase by 10 points)
    speed = 50 #Timer to adjust the speed of the game(The unit is milliseconds)
    win.title("Squash game:start!") #Display in title bar

You can initialize the game together by grouping the initial values of the variables with a function named "init_game ()".


Step 2: Draw a racket

#Draw a racket
def draw_racket ():
    cv.create_rectangle(racket_ichi_x, 470, racket_ichi_x + racket_size, 480, fill="yellow")

Step 3: Move the ball

#Ball movement
def move_ball():
    global is_gameover, point, ball_ichi_x, ball_ichi_y, ball_idou_x, ball_idou_y
    if is_gameover: return
    
    #Judgment of hitting the left and right walls
    if ball_ichi_x + ball_idou_x < 0 or ball_ichi_x + ball_idou_x > 640:
        ball_idou_x *= -1

    #Judgment of hitting the ceiling or floor
    if ball_ichi_y + ball_idou_y < 0:
        ball_idou_y *= -1
    
    #Judgment whether it hit the racket
    if ball_ichi_y + ball_idou_y > 470 and (racket_ichi_x <= (ball_ichi_x + ball_idou_x) <= (racket_ichi_x + racket_size)):
        ball_idou_y *= -1
        if random.randint(0, 1) == 0:
            ball_idou_x *= -1
        point += 10
        win.title("Score =" + str(point)) #Display of score
    
    #Judgment when making a mistake
    if ball_ichi_y + ball_idou_y > 480:
        is_gameover = True
        win.title("Score =" + str(point)) #Display of score
    
    #Move the position of the ball
    if 0 <= ball_ichi_x + ball_idou_x <= 640:
        ball_ichi_x = ball_ichi_x + ball_idou_x
    if 0 <= ball_ichi_y + ball_idou_y <= 480:
        ball_ichi_y = ball_ichi_y + ball_idou_y

Step 4: Mouse processing

#Handling mouse movements
def motion(event): #Check the position of the mouse pointer
    global racket_ichi_x 
    racket_ichi_x = event.x
    
def click(event): #Click to restart
    if event.num == 1:
        init_game()

#Confirmation of mouse movement and click
win.bind('<Motion>', motion)
win.bind('<Button>', click)

The command in "<>" is called "event" and you can check the movement of the mouse. ← Event name (capital letter at the beginning) "Motion" ← function name

--Mouse events --Button or ButtonPress ← Press the mouse button --ButtonRelease ← Release the mouse button --Mottion ← Mouse movement (acquisition of coordinates)


Step4: Optional

Let's make a sound and a message

    #Judgment of hitting the left and right walls
    if ball_ichi_x + ball_idou_x < 0 or ball_ichi_x + ball_idou_x > 640:
        ball_idou_x *= -1
        winsound.Beep(1300, 50)
    
    #Judgment of hitting the ceiling or floor
    if ball_ichi_y + ball_idou_y < 0:
        ball_idou_y *= -1
        winsound.Beep(1300, 50)

    #Judgment whether it hit the racket
    if ball_ichi_y + ball_idou_y > 470 and (racket_ichi_x <= (ball_ichi_x + ball_idou_x) <= (racket_ichi_x + racket_size)):
        ball_idou_y *= -1
        if random.randint(0, 1) == 0:
            ball_idou_x *= -1
        winsound.Beep(2000, 50)
        mes = random.randint(0, 3)
        if mes == 0:
            message = "good!"
        if mes == 1:
            message = "good!"
        if mes == 2:
            message = "nice!"
        if mes == 3:
            message = "Wow!"
        point += 10
        win.title(message + "Score =" + str(point)) #Display score and message
        
    #Judgment when making a mistake
    if ball_ichi_y + ball_idou_y > 480:
        mes = random.randint(0, 3)
        if mes == 0:
            message = "You made a mistake!"
        if mes == 1:
            message = "Donmai!"
        if mes == 2:
            message = "Damn shit!"
        if mes == 3:
            message = "Ah, I can't see it!"
        win.title(message + "Score =" + str(point)) #Display score and message
        winsound.Beep(240, 800)
        is_gameover = True

You can make a sound with "winsound.Beep (frequency of sound, time to make a sound)"


Let's change the speed of the ball

ball_idou_x = 15
    ball_idou_y = -15
 speed = 50 #Timer to adjust the speed of the game(The unit is milliseconds)

You can change the speed of the ball by changing these values


Source code

# coding:utf-8

#Squash game(Wall tennis)
#Module import
import tkinter as tk
import random
import winsound

#Creating a window
win = tk.Tk()
#Creating a canvas
cv = tk.Canvas(win, width=640, height=480 ,bg="white")
#Canvas display
cv.pack()

#Game initialization
def init_game():
    global is_gameover, ball_ichi_x, ball_ichi_y
    global ball_idou_x, ball_idou_y, ball_size
    global racket_ichi_x, racket_size, point, speed
    is_gameover = False #Confirmation of game end(False if not finished/True when finished)
    ball_ichi_x = 0
    ball_ichi_y = 250
    ball_idou_x = 15
    ball_idou_y = -15
    ball_size = 10
    racket_ichi_x = 0
    racket_size = 100
    point = 0 #point(Initially 0 points/Increase by 10 points)
    speed = 50 #Timer to adjust the speed of the game(The unit is milliseconds)
    win.title("Squash game:start!") #Display in title bar

#Screen drawing
def draw_screen():
    #Clear screen
    cv.delete('all') #Command to turn off the screen
    #campus(screen)Creation
    cv.create_rectangle(0, 0, 640, 480, fill="white", width=0)

#Draw a ball
def draw_ball():
    cv.create_oval(ball_ichi_x - ball_size, ball_ichi_y - ball_size, ball_ichi_x + ball_size, ball_ichi_y + ball_size, fill="red", width=0)

#Draw a racket
def draw_racket ():
    cv.create_rectangle(racket_ichi_x, 470, racket_ichi_x + racket_size, 480, fill="yellow")

#Ball movement
def move_ball():
    global is_gameover, point, ball_ichi_x, ball_ichi_y, ball_idou_x, ball_idou_y
    if is_gameover: return
    
    #Judgment of hitting the left and right walls
    if ball_ichi_x + ball_idou_x < 0 or ball_ichi_x + ball_idou_x > 640:
        ball_idou_x *= -1
        winsound.Beep(1300, 50)
    
    #Judgment of hitting the ceiling or floor
    if ball_ichi_y + ball_idou_y < 0:
        ball_idou_y *= -1
        winsound.Beep(1300, 50)

    #Judgment whether it hit the racket
    if ball_ichi_y + ball_idou_y > 470 and (racket_ichi_x <= (ball_ichi_x + ball_idou_x) <= (racket_ichi_x + racket_size)):
        ball_idou_y *= -1
        if random.randint(0, 1) == 0:
            ball_idou_x *= -1
        winsound.Beep(2000, 50)
        mes = random.randint(0, 3)
        if mes == 0:
            message = "good!"
        if mes == 1:
            message = "good!"
        if mes == 2:
            message = "nice!"
        if mes == 3:
            message = "Wow!"
        point += 10
        win.title(message + "Score =" + str(point)) #Display score and message
        
    #Judgment when making a mistake
    if ball_ichi_y + ball_idou_y > 480:
        mes = random.randint(0, 3)
        if mes == 0:
            message = "You made a mistake!"
        if mes == 1:
            message = "Donmai!"
        if mes == 2:
            message = "Damn shit!"
        if mes == 3:
            message = "Ah, I can't see it!"
        win.title(message + "Score =" + str(point)) #Display score and message
        winsound.Beep(240, 800)
        is_gameover = True

    #Move the position of the ball
    if 0 <= ball_ichi_x + ball_idou_x <= 640:
        ball_ichi_x = ball_ichi_x + ball_idou_x
    if 0 <= ball_ichi_y + ball_idou_y <= 480:
        ball_ichi_y = ball_ichi_y + ball_idou_y

#Handling mouse movements
def motion(event): #Check the position of the mouse pointer
    global racket_ichi_x 
    racket_ichi_x = event.x
    
def click(event): #Click to restart
    if event.num == 1:
        init_game()

#Confirmation of mouse movement and click
win.bind('<Motion>', motion)
win.bind('<Button>', click)

#Command for repeating game processing
def game_loop():
    draw_screen()
    draw_ball()
    draw_racket()
    move_ball()
    win.after(speed, game_loop) #Timer setting

#Main processing of the game
init_game()
game_loop() 
#Window display
win.mainloop()


Execution result

ミスしたね_得点=10-2020-07-08-17-30-12.gif


スカッシュゲーム (3).PNG


What I noticed

--The next window cannot be displayed unless the executed window is deleted. ⇒I was quite impatient with this. It didn't run well, so I wondered if there was a problem with Python and uninstalled it.

――There are various ways to write even a simple program such as creating a window or canvas. ⇒I was surprised that there were many things that could be omitted and written in different ways.


Question

import tkinter as tk 

In reference [1],

from tkinter import *

Since it was written, it can be executed by executing it with this, but a yellow wavy line is drawn under from, and the problem is 100. Why is this?

References

[1] Mitsuru Sugaya "learn the game center storm Introduction to Programming cartoon version of Hello Python" (2020) Nikkei BP [2] Fumitaka Osawa "The easiest Python introductory class" (2019) Sotec Co., Ltd.

Recommended Posts

Make a squash game
Make a Tetris-style game!
Let's make a rock-paper-scissors game
Let's make a shiritori game with Python
〇✕ I made a game
[Python] Make a game with Pyxel-Use an editor-
I want to make a game with Python
Make a function decorator
Make a cocos2d game in a pixel double window
Make a distance matrix
[Python] Make a simple maze game with Pyxel
Make a rock-paper-scissors game in one line (python)
I'll make a password!
Make a Nyan button
I tried to make a ○ ✕ game using TensorFlow
Make a Base64 decoder
How to make a shooting game with toio (Part 1)
Let's make a simple game with Python 3 and iPhone
Let's make a Discord Bot.
Make a Blueqat backend ~ Part 1
Make a Blueqat backend ~ Part 2
[Django] Make a pull-down menu
Make a LINE BOT (chat)
Make a bookmarklet in Python
Make a fortune with Python
Make Responder a daemon (service)
Make a fire with kdeplot
Make a math drill print
How to make a multiplayer online action game on Slack
How to make a simple Flappy Bird game with pygame
[Python] Make a simple maze game with Pyxel-Make enemies appear-
Let's make a number guessing game in your own language!
Let's make a remote rumba [Hardware]
How to make a Japanese-English translation
Make a Santa classifier from a Santa image
Let's make a remote rumba [Software]
Make a Tweet box for Pepper
Let's make a GUI with python.
Make a sound with Jupyter notebook
Let's make a spot sale service 2
Make a face recognizer using TensorFlow
How to make a slack bot
Let's make a breakout with wxPython
Let's make a spot sale service 1
How to make a crawler --Advanced
How to make a recursive function
Make C compilation a little easier
python / Make a dict from a list.
[Python] Make the function a lambda function
Make a recommender system with python
How to make a deadman's switch
[Blender] How to make a Blender plugin
Make Flask a Cloud Native application
Make a filter with a django template
Zura made like a life game
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
How to make a crawler --Basic
Make a model iterator with PySide
Make a nice graph with plotly
Make a curtain generator in Blender