Pythonで簡単にアプリができる『Tkinter』
Pythonでアプリ(ゲーム)を簡単に作りたいなら、Tkinterを使おう!
Tkinterはココが素晴らしい
・Pythonが動けばほぼ動かすことができる。→すぐ開始できる。
・画面が作れるので達成感がある!
・ゲームのようなものも動かせる。
以上の3点からPythonで使える『Tkinter』はとっても楽しく便利!
うまくいくとこんなボールゲームも起動できます。
これがこのボールゲームのサンプルコード例だ!
下のコードはプログラムエディタにコピーとペーストですぐ動くようになる。
import tkinter as tk
import random
# ゲームの設定
WIDTH = 600
HEIGHT = 400
BALL_SPEED = 20
PAD_SPEED = 100
BLOCK_WIDTH = 60
BLOCK_HEIGHT = 20
NUM_BLOCKS = 5
# ボールの初期位置と速度
ball_x = WIDTH / 2
ball_y = HEIGHT / 2
ball_speed_x = BALL_SPEED
ball_speed_y = -BALL_SPEED
# パドルの初期位置と速度
paddle_x = WIDTH / 2 - 50
paddle_speed = 0
# Tkinterウィンドウのセットアップ
root = tk.Tk()
root.title("ボールとパドルゲーム")
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
blocks = []
for i in range(NUM_BLOCKS):
x = i * (BLOCK_WIDTH + 10)
y = 50
block = canvas.create_rectangle(x, y, x + BLOCK_WIDTH, y + BLOCK_HEIGHT, fill="green")
blocks.append(block)
paddle = canvas.create_rectangle(paddle_x, HEIGHT - 30, paddle_x + 100, HEIGHT - 20, fill="blue")
ball = canvas.create_oval(ball_x, ball_y, ball_x + 20, ball_y + 20, fill="red")
def update():
global ball_x, ball_y, ball_speed_x, ball_speed_y, paddle_x, paddle_speed
# ボールの移動
ball_x += ball_speed_x
ball_y += ball_speed_y
canvas.coords(ball, ball_x, ball_y, ball_x + 20, ball_y + 20)
# ボールの反射
if ball_x <= 0 or ball_x >= WIDTH - 20:
ball_speed_x = -ball_speed_x
if ball_y <= 0:
ball_speed_y = -ball_speed_y
# ボールとパドルの衝突
ball_pos = canvas.coords(ball)
paddle_pos = canvas.coords(paddle)
if ball_pos[2] >= paddle_pos[0] and ball_pos[0] <= paddle_pos[2] and ball_pos[3] >= paddle_pos[1] and ball_pos[3] <= paddle_pos[3]:
ball_speed_y = -ball_speed_y
# ボールとブロックの衝突
for block in blocks:
block_pos = canvas.coords(block)
if ball_pos[2] >= block_pos[0] and ball_pos[0] <= block_pos[2] and ball_pos[3] >= block_pos[1] and ball_pos[1] <= block_pos[3]:
ball_speed_y = -ball_speed_y
canvas.delete(block)
blocks.remove(block)
break
# パドルの移動
paddle_x += paddle_speed
if paddle_x <= 0:
paddle_x = 0
if paddle_x >= WIDTH - 100:
paddle_x = WIDTH - 100
canvas.coords(paddle, paddle_x, HEIGHT - 30, paddle_x + 100, HEIGHT - 20)
root.after(50, update)
# キーのイベント処理
def move_left(event):
global paddle_speed
paddle_speed = -PAD_SPEED
def move_right(event):
global paddle_speed
paddle_speed = PAD_SPEED
root.bind("<KeyPress-Left>", move_left)
root.bind("<KeyPress-Right>", move_right)
update()
root.mainloop()
まとめ
Pythonの中の標準ライブラリ、『Tkinter』を使うと簡単にウィンドウを作成出来て、ゲームアプリも起動ができる。
一度試しに上のボールパドルゲームを起動しあそんでみよう!