PySimpleGUI Arkanoid Part 3: Tile

Posted by


In part 3 of our PySimpleGUI tutorial series on creating an arkanoid game, we will focus on creating the paddle. The paddle is a crucial element in the game as it allows the player to control the direction of the ball and prevent it from falling off the screen. By the end of this tutorial, you will have a fully functional paddle that can be moved left and right using the arrow keys.

To get started, make sure you have PySimpleGUI installed on your computer. If not, you can install it using pip:

pip install PySimpleGUI

Next, create a new Python file and import the necessary modules:

import PySimpleGUI as sg
import random

Now, let’s define some constants that we will use throughout the program:

WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 10
PADDLE_SPEED = 10
PADDLE_COLOR = 'blue'

Next, let’s create the main game window using PySimpleGUI:

layout = [
    [sg.Graph(canvas_size=(WINDOW_WIDTH, WINDOW_HEIGHT), background_color='black', key='canvas')],
]

window = sg.Window('Arkanoid', layout, resizable=True, finalize=True)
canvas = window['canvas']

Now, let’s create the paddle on the canvas:

paddle = canvas.DrawRectangle((WINDOW_WIDTH-PADDLE_WIDTH)//2, WINDOW_HEIGHT-PADDLE_HEIGHT-10, (WINDOW_WIDTH+PADDLE_WIDTH)//2, WINDOW_HEIGHT-10, fill_color=PADDLE_COLOR)

Next, we need to define a function that will move the paddle left or right when the arrow keys are pressed:

def move_paddle(event):
    if event == 'Left:37' and paddle.get_bbox()[0] > 0:
        canvas.move_figure(paddle, -PADDLE_SPEED, 0)
    elif event == 'Right:39' and paddle.get_bbox()[2] < WINDOW_WIDTH:
        canvas.move_figure(paddle, PADDLE_SPEED, 0)

Now, let’s add an event loop to listen for key presses and move the paddle accordingly:

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    move_paddle(event)

That’s it! You now have a functional paddle that can be moved left and right using the arrow keys. In the next part of this tutorial series, we will add the ball and collision detection to complete the arkanoid game. Stay tuned for more!