スネークゲーム
矢印キーで操作するクラシックなスネークゲーム。Canvasとキーボードイベントの本格的な活用を学びます。
1. アプリ概要
矢印キーで操作するクラシックなスネークゲーム。Canvasとキーボードイベントの本格的な活用を学びます。
このアプリはゲームカテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ) で、難易度は ★★★ です。
Pythonでは tkinter を使うことで、クロスプラットフォームなGUIアプリを簡単に作成できます。このアプリを通じて、ウィジェットの配置・イベント処理・データ管理など、GUI開発の実践的なスキルを習得できます。
ソースコードは完全な動作状態で提供しており、コピーしてそのまま実行できます。まずは実行して動作を確認し、その後コードを読んで仕組みを理解していきましょう。カスタマイズセクションでは機能拡張のアイデアも紹介しています。
GUIアプリ開発は、プログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。アプリを作ることで、変数・関数・クラス・イベント処理など、プログラミングの重要な概念が自然と身についていきます。このアプリをきっかけに、オリジナルアプリの開発にも挑戦してみてください。
2. 機能一覧
- スネークゲームのメイン機能
- 直感的なGUIインターフェース
- 入力値のバリデーション
- エラーハンドリング
- 結果の見やすい表示
- キーボードショートカット対応
3. 事前準備・環境
Python 3.10 以上 / Windows・Mac・Linux すべて対応
以下の環境で動作確認しています。
- Python 3.10 以上
- OS: Windows 10/11・macOS 12+・Ubuntu 20.04+
4. 完全なソースコード
右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App50:
"""スネークゲーム"""
CELL = 20
COLS = 20
ROWS = 20
SPEED = 150 # ms
def __init__(self, root):
self.root = root
self.root.title("スネークゲーム")
self.root.configure(bg="#111")
self.root.resizable(False, False)
self._build_ui()
self.new_game()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#222", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🐍 スネークゲーム", font=("Noto Sans JP", 14, "bold"),
bg="#222", fg="#00ff88").pack(side=tk.LEFT, padx=12)
self.score_label = tk.Label(header, text="スコア: 0", font=("Noto Sans JP", 12),
bg="#222", fg="#fff")
self.score_label.pack(side=tk.LEFT, padx=16)
self.best_label = tk.Label(header, text="ベスト: 0", font=("Noto Sans JP", 10),
bg="#222", fg="#aaa")
self.best_label.pack(side=tk.LEFT)
# キャンバス
w = self.CELL * self.COLS
h = self.CELL * self.ROWS
self.canvas = tk.Canvas(self.root, width=w, height=h,
bg="#111", highlightthickness=0)
self.canvas.pack(padx=8, pady=4)
# フッター
footer = tk.Frame(self.root, bg="#111", pady=4)
footer.pack(fill=tk.X)
tk.Label(footer, text="矢印キー / WASD で操作 | Space でポーズ",
bg="#111", fg="#555", font=("Noto Sans JP", 9)).pack(side=tk.LEFT, padx=12)
ttk.Button(footer, text="リスタート", command=self.new_game).pack(side=tk.RIGHT, padx=8)
# キーバインド
self.root.bind("<Left>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<Right>", lambda e: self.change_dir((1, 0)))
self.root.bind("<Up>", lambda e: self.change_dir((0, -1)))
self.root.bind("<Down>", lambda e: self.change_dir((0, 1)))
self.root.bind("<a>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<d>", lambda e: self.change_dir((1, 0)))
self.root.bind("<w>", lambda e: self.change_dir((0, -1)))
self.root.bind("<s>", lambda e: self.change_dir((0, 1)))
self.root.bind("<space>", lambda e: self.toggle_pause())
self.best_score = 0
self._after_id = None
def new_game(self):
if self._after_id:
self.root.after_cancel(self._after_id)
cx, cy = self.COLS // 2, self.ROWS // 2
self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
self.direction = (1, 0)
self.next_dir = (1, 0)
self.score = 0
self.paused = False
self.game_over = False
self._place_food()
self._draw()
self._tick()
def change_dir(self, d):
dx, dy = d
if (dx, dy) != (-self.direction[0], -self.direction[1]):
self.next_dir = d
def toggle_pause(self):
if self.game_over:
return
self.paused = not self.paused
if not self.paused:
self._tick()
def _place_food(self):
free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS)
if (x, y) not in self.snake]
self.food = random.choice(free)
def _tick(self):
if self.paused or self.game_over:
return
self.direction = self.next_dir
head = (self.snake[0][0] + self.direction[0],
self.snake[0][1] + self.direction[1])
# 壁・自分に衝突
if (head[0] < 0 or head[0] >= self.COLS or
head[1] < 0 or head[1] >= self.ROWS or
head in self.snake):
self.game_over = True
self._draw()
return
self.snake.insert(0, head)
if head == self.food:
self.score += 10
if self.score > self.best_score:
self.best_score = self.score
self.score_label.config(text=f"スコア: {self.score}")
self.best_label.config(text=f"ベスト: {self.best_score}")
self._place_food()
else:
self.snake.pop()
self._draw()
speed = max(60, self.SPEED - self.score // 50 * 10)
self._after_id = self.root.after(speed, self._tick)
def _draw(self):
self.canvas.delete("all")
c = self.CELL
# グリッド(薄く)
for x in range(0, self.COLS * c, c):
self.canvas.create_line(x, 0, x, self.ROWS * c, fill="#1a1a1a")
for y in range(0, self.ROWS * c, c):
self.canvas.create_line(0, y, self.COLS * c, y, fill="#1a1a1a")
# フード
fx, fy = self.food
self.canvas.create_oval(fx*c+3, fy*c+3, (fx+1)*c-3, (fy+1)*c-3,
fill="#ff4444", outline="")
# スネーク
for i, (x, y) in enumerate(self.snake):
color = "#00ff88" if i == 0 else "#00cc66" if i < 4 else "#009944"
self.canvas.create_rectangle(x*c+1, y*c+1, (x+1)*c-1, (y+1)*c-1,
fill=color, outline="")
if self.game_over:
self.canvas.create_rectangle(0, 0, self.COLS*c, self.ROWS*c,
fill="", stipple="gray50", outline="")
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 - 20,
text="GAME OVER", fill="white",
font=("Arial", 24, "bold"))
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 + 20,
text=f"スコア: {self.score}", fill="#aaa",
font=("Arial", 14))
if self.paused and not self.game_over:
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2,
text="PAUSE", fill="white",
font=("Arial", 24, "bold"))
if __name__ == "__main__":
root = tk.Tk()
app = App50(root)
root.mainloop()
5. コード解説
スネークゲームのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。
クラス設計とコンストラクタ
App50クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App50:
"""スネークゲーム"""
CELL = 20
COLS = 20
ROWS = 20
SPEED = 150 # ms
def __init__(self, root):
self.root = root
self.root.title("スネークゲーム")
self.root.configure(bg="#111")
self.root.resizable(False, False)
self._build_ui()
self.new_game()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#222", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🐍 スネークゲーム", font=("Noto Sans JP", 14, "bold"),
bg="#222", fg="#00ff88").pack(side=tk.LEFT, padx=12)
self.score_label = tk.Label(header, text="スコア: 0", font=("Noto Sans JP", 12),
bg="#222", fg="#fff")
self.score_label.pack(side=tk.LEFT, padx=16)
self.best_label = tk.Label(header, text="ベスト: 0", font=("Noto Sans JP", 10),
bg="#222", fg="#aaa")
self.best_label.pack(side=tk.LEFT)
# キャンバス
w = self.CELL * self.COLS
h = self.CELL * self.ROWS
self.canvas = tk.Canvas(self.root, width=w, height=h,
bg="#111", highlightthickness=0)
self.canvas.pack(padx=8, pady=4)
# フッター
footer = tk.Frame(self.root, bg="#111", pady=4)
footer.pack(fill=tk.X)
tk.Label(footer, text="矢印キー / WASD で操作 | Space でポーズ",
bg="#111", fg="#555", font=("Noto Sans JP", 9)).pack(side=tk.LEFT, padx=12)
ttk.Button(footer, text="リスタート", command=self.new_game).pack(side=tk.RIGHT, padx=8)
# キーバインド
self.root.bind("<Left>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<Right>", lambda e: self.change_dir((1, 0)))
self.root.bind("<Up>", lambda e: self.change_dir((0, -1)))
self.root.bind("<Down>", lambda e: self.change_dir((0, 1)))
self.root.bind("<a>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<d>", lambda e: self.change_dir((1, 0)))
self.root.bind("<w>", lambda e: self.change_dir((0, -1)))
self.root.bind("<s>", lambda e: self.change_dir((0, 1)))
self.root.bind("<space>", lambda e: self.toggle_pause())
self.best_score = 0
self._after_id = None
def new_game(self):
if self._after_id:
self.root.after_cancel(self._after_id)
cx, cy = self.COLS // 2, self.ROWS // 2
self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
self.direction = (1, 0)
self.next_dir = (1, 0)
self.score = 0
self.paused = False
self.game_over = False
self._place_food()
self._draw()
self._tick()
def change_dir(self, d):
dx, dy = d
if (dx, dy) != (-self.direction[0], -self.direction[1]):
self.next_dir = d
def toggle_pause(self):
if self.game_over:
return
self.paused = not self.paused
if not self.paused:
self._tick()
def _place_food(self):
free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS)
if (x, y) not in self.snake]
self.food = random.choice(free)
def _tick(self):
if self.paused or self.game_over:
return
self.direction = self.next_dir
head = (self.snake[0][0] + self.direction[0],
self.snake[0][1] + self.direction[1])
# 壁・自分に衝突
if (head[0] < 0 or head[0] >= self.COLS or
head[1] < 0 or head[1] >= self.ROWS or
head in self.snake):
self.game_over = True
self._draw()
return
self.snake.insert(0, head)
if head == self.food:
self.score += 10
if self.score > self.best_score:
self.best_score = self.score
self.score_label.config(text=f"スコア: {self.score}")
self.best_label.config(text=f"ベスト: {self.best_score}")
self._place_food()
else:
self.snake.pop()
self._draw()
speed = max(60, self.SPEED - self.score // 50 * 10)
self._after_id = self.root.after(speed, self._tick)
def _draw(self):
self.canvas.delete("all")
c = self.CELL
# グリッド(薄く)
for x in range(0, self.COLS * c, c):
self.canvas.create_line(x, 0, x, self.ROWS * c, fill="#1a1a1a")
for y in range(0, self.ROWS * c, c):
self.canvas.create_line(0, y, self.COLS * c, y, fill="#1a1a1a")
# フード
fx, fy = self.food
self.canvas.create_oval(fx*c+3, fy*c+3, (fx+1)*c-3, (fy+1)*c-3,
fill="#ff4444", outline="")
# スネーク
for i, (x, y) in enumerate(self.snake):
color = "#00ff88" if i == 0 else "#00cc66" if i < 4 else "#009944"
self.canvas.create_rectangle(x*c+1, y*c+1, (x+1)*c-1, (y+1)*c-1,
fill=color, outline="")
if self.game_over:
self.canvas.create_rectangle(0, 0, self.COLS*c, self.ROWS*c,
fill="", stipple="gray50", outline="")
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 - 20,
text="GAME OVER", fill="white",
font=("Arial", 24, "bold"))
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 + 20,
text=f"スコア: {self.score}", fill="#aaa",
font=("Arial", 14))
if self.paused and not self.game_over:
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2,
text="PAUSE", fill="white",
font=("Arial", 24, "bold"))
if __name__ == "__main__":
root = tk.Tk()
app = App50(root)
root.mainloop()
LabelFrameによるセクション分け
ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App50:
"""スネークゲーム"""
CELL = 20
COLS = 20
ROWS = 20
SPEED = 150 # ms
def __init__(self, root):
self.root = root
self.root.title("スネークゲーム")
self.root.configure(bg="#111")
self.root.resizable(False, False)
self._build_ui()
self.new_game()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#222", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🐍 スネークゲーム", font=("Noto Sans JP", 14, "bold"),
bg="#222", fg="#00ff88").pack(side=tk.LEFT, padx=12)
self.score_label = tk.Label(header, text="スコア: 0", font=("Noto Sans JP", 12),
bg="#222", fg="#fff")
self.score_label.pack(side=tk.LEFT, padx=16)
self.best_label = tk.Label(header, text="ベスト: 0", font=("Noto Sans JP", 10),
bg="#222", fg="#aaa")
self.best_label.pack(side=tk.LEFT)
# キャンバス
w = self.CELL * self.COLS
h = self.CELL * self.ROWS
self.canvas = tk.Canvas(self.root, width=w, height=h,
bg="#111", highlightthickness=0)
self.canvas.pack(padx=8, pady=4)
# フッター
footer = tk.Frame(self.root, bg="#111", pady=4)
footer.pack(fill=tk.X)
tk.Label(footer, text="矢印キー / WASD で操作 | Space でポーズ",
bg="#111", fg="#555", font=("Noto Sans JP", 9)).pack(side=tk.LEFT, padx=12)
ttk.Button(footer, text="リスタート", command=self.new_game).pack(side=tk.RIGHT, padx=8)
# キーバインド
self.root.bind("<Left>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<Right>", lambda e: self.change_dir((1, 0)))
self.root.bind("<Up>", lambda e: self.change_dir((0, -1)))
self.root.bind("<Down>", lambda e: self.change_dir((0, 1)))
self.root.bind("<a>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<d>", lambda e: self.change_dir((1, 0)))
self.root.bind("<w>", lambda e: self.change_dir((0, -1)))
self.root.bind("<s>", lambda e: self.change_dir((0, 1)))
self.root.bind("<space>", lambda e: self.toggle_pause())
self.best_score = 0
self._after_id = None
def new_game(self):
if self._after_id:
self.root.after_cancel(self._after_id)
cx, cy = self.COLS // 2, self.ROWS // 2
self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
self.direction = (1, 0)
self.next_dir = (1, 0)
self.score = 0
self.paused = False
self.game_over = False
self._place_food()
self._draw()
self._tick()
def change_dir(self, d):
dx, dy = d
if (dx, dy) != (-self.direction[0], -self.direction[1]):
self.next_dir = d
def toggle_pause(self):
if self.game_over:
return
self.paused = not self.paused
if not self.paused:
self._tick()
def _place_food(self):
free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS)
if (x, y) not in self.snake]
self.food = random.choice(free)
def _tick(self):
if self.paused or self.game_over:
return
self.direction = self.next_dir
head = (self.snake[0][0] + self.direction[0],
self.snake[0][1] + self.direction[1])
# 壁・自分に衝突
if (head[0] < 0 or head[0] >= self.COLS or
head[1] < 0 or head[1] >= self.ROWS or
head in self.snake):
self.game_over = True
self._draw()
return
self.snake.insert(0, head)
if head == self.food:
self.score += 10
if self.score > self.best_score:
self.best_score = self.score
self.score_label.config(text=f"スコア: {self.score}")
self.best_label.config(text=f"ベスト: {self.best_score}")
self._place_food()
else:
self.snake.pop()
self._draw()
speed = max(60, self.SPEED - self.score // 50 * 10)
self._after_id = self.root.after(speed, self._tick)
def _draw(self):
self.canvas.delete("all")
c = self.CELL
# グリッド(薄く)
for x in range(0, self.COLS * c, c):
self.canvas.create_line(x, 0, x, self.ROWS * c, fill="#1a1a1a")
for y in range(0, self.ROWS * c, c):
self.canvas.create_line(0, y, self.COLS * c, y, fill="#1a1a1a")
# フード
fx, fy = self.food
self.canvas.create_oval(fx*c+3, fy*c+3, (fx+1)*c-3, (fy+1)*c-3,
fill="#ff4444", outline="")
# スネーク
for i, (x, y) in enumerate(self.snake):
color = "#00ff88" if i == 0 else "#00cc66" if i < 4 else "#009944"
self.canvas.create_rectangle(x*c+1, y*c+1, (x+1)*c-1, (y+1)*c-1,
fill=color, outline="")
if self.game_over:
self.canvas.create_rectangle(0, 0, self.COLS*c, self.ROWS*c,
fill="", stipple="gray50", outline="")
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 - 20,
text="GAME OVER", fill="white",
font=("Arial", 24, "bold"))
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 + 20,
text=f"スコア: {self.score}", fill="#aaa",
font=("Arial", 14))
if self.paused and not self.game_over:
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2,
text="PAUSE", fill="white",
font=("Arial", 24, "bold"))
if __name__ == "__main__":
root = tk.Tk()
app = App50(root)
root.mainloop()
Entryウィジェットとイベントバインド
ttk.Entryで入力フィールドを作成します。bind('
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App50:
"""スネークゲーム"""
CELL = 20
COLS = 20
ROWS = 20
SPEED = 150 # ms
def __init__(self, root):
self.root = root
self.root.title("スネークゲーム")
self.root.configure(bg="#111")
self.root.resizable(False, False)
self._build_ui()
self.new_game()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#222", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🐍 スネークゲーム", font=("Noto Sans JP", 14, "bold"),
bg="#222", fg="#00ff88").pack(side=tk.LEFT, padx=12)
self.score_label = tk.Label(header, text="スコア: 0", font=("Noto Sans JP", 12),
bg="#222", fg="#fff")
self.score_label.pack(side=tk.LEFT, padx=16)
self.best_label = tk.Label(header, text="ベスト: 0", font=("Noto Sans JP", 10),
bg="#222", fg="#aaa")
self.best_label.pack(side=tk.LEFT)
# キャンバス
w = self.CELL * self.COLS
h = self.CELL * self.ROWS
self.canvas = tk.Canvas(self.root, width=w, height=h,
bg="#111", highlightthickness=0)
self.canvas.pack(padx=8, pady=4)
# フッター
footer = tk.Frame(self.root, bg="#111", pady=4)
footer.pack(fill=tk.X)
tk.Label(footer, text="矢印キー / WASD で操作 | Space でポーズ",
bg="#111", fg="#555", font=("Noto Sans JP", 9)).pack(side=tk.LEFT, padx=12)
ttk.Button(footer, text="リスタート", command=self.new_game).pack(side=tk.RIGHT, padx=8)
# キーバインド
self.root.bind("<Left>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<Right>", lambda e: self.change_dir((1, 0)))
self.root.bind("<Up>", lambda e: self.change_dir((0, -1)))
self.root.bind("<Down>", lambda e: self.change_dir((0, 1)))
self.root.bind("<a>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<d>", lambda e: self.change_dir((1, 0)))
self.root.bind("<w>", lambda e: self.change_dir((0, -1)))
self.root.bind("<s>", lambda e: self.change_dir((0, 1)))
self.root.bind("<space>", lambda e: self.toggle_pause())
self.best_score = 0
self._after_id = None
def new_game(self):
if self._after_id:
self.root.after_cancel(self._after_id)
cx, cy = self.COLS // 2, self.ROWS // 2
self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
self.direction = (1, 0)
self.next_dir = (1, 0)
self.score = 0
self.paused = False
self.game_over = False
self._place_food()
self._draw()
self._tick()
def change_dir(self, d):
dx, dy = d
if (dx, dy) != (-self.direction[0], -self.direction[1]):
self.next_dir = d
def toggle_pause(self):
if self.game_over:
return
self.paused = not self.paused
if not self.paused:
self._tick()
def _place_food(self):
free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS)
if (x, y) not in self.snake]
self.food = random.choice(free)
def _tick(self):
if self.paused or self.game_over:
return
self.direction = self.next_dir
head = (self.snake[0][0] + self.direction[0],
self.snake[0][1] + self.direction[1])
# 壁・自分に衝突
if (head[0] < 0 or head[0] >= self.COLS or
head[1] < 0 or head[1] >= self.ROWS or
head in self.snake):
self.game_over = True
self._draw()
return
self.snake.insert(0, head)
if head == self.food:
self.score += 10
if self.score > self.best_score:
self.best_score = self.score
self.score_label.config(text=f"スコア: {self.score}")
self.best_label.config(text=f"ベスト: {self.best_score}")
self._place_food()
else:
self.snake.pop()
self._draw()
speed = max(60, self.SPEED - self.score // 50 * 10)
self._after_id = self.root.after(speed, self._tick)
def _draw(self):
self.canvas.delete("all")
c = self.CELL
# グリッド(薄く)
for x in range(0, self.COLS * c, c):
self.canvas.create_line(x, 0, x, self.ROWS * c, fill="#1a1a1a")
for y in range(0, self.ROWS * c, c):
self.canvas.create_line(0, y, self.COLS * c, y, fill="#1a1a1a")
# フード
fx, fy = self.food
self.canvas.create_oval(fx*c+3, fy*c+3, (fx+1)*c-3, (fy+1)*c-3,
fill="#ff4444", outline="")
# スネーク
for i, (x, y) in enumerate(self.snake):
color = "#00ff88" if i == 0 else "#00cc66" if i < 4 else "#009944"
self.canvas.create_rectangle(x*c+1, y*c+1, (x+1)*c-1, (y+1)*c-1,
fill=color, outline="")
if self.game_over:
self.canvas.create_rectangle(0, 0, self.COLS*c, self.ROWS*c,
fill="", stipple="gray50", outline="")
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 - 20,
text="GAME OVER", fill="white",
font=("Arial", 24, "bold"))
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 + 20,
text=f"スコア: {self.score}", fill="#aaa",
font=("Arial", 14))
if self.paused and not self.game_over:
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2,
text="PAUSE", fill="white",
font=("Arial", 24, "bold"))
if __name__ == "__main__":
root = tk.Tk()
app = App50(root)
root.mainloop()
Textウィジェットでの結果表示
結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App50:
"""スネークゲーム"""
CELL = 20
COLS = 20
ROWS = 20
SPEED = 150 # ms
def __init__(self, root):
self.root = root
self.root.title("スネークゲーム")
self.root.configure(bg="#111")
self.root.resizable(False, False)
self._build_ui()
self.new_game()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#222", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🐍 スネークゲーム", font=("Noto Sans JP", 14, "bold"),
bg="#222", fg="#00ff88").pack(side=tk.LEFT, padx=12)
self.score_label = tk.Label(header, text="スコア: 0", font=("Noto Sans JP", 12),
bg="#222", fg="#fff")
self.score_label.pack(side=tk.LEFT, padx=16)
self.best_label = tk.Label(header, text="ベスト: 0", font=("Noto Sans JP", 10),
bg="#222", fg="#aaa")
self.best_label.pack(side=tk.LEFT)
# キャンバス
w = self.CELL * self.COLS
h = self.CELL * self.ROWS
self.canvas = tk.Canvas(self.root, width=w, height=h,
bg="#111", highlightthickness=0)
self.canvas.pack(padx=8, pady=4)
# フッター
footer = tk.Frame(self.root, bg="#111", pady=4)
footer.pack(fill=tk.X)
tk.Label(footer, text="矢印キー / WASD で操作 | Space でポーズ",
bg="#111", fg="#555", font=("Noto Sans JP", 9)).pack(side=tk.LEFT, padx=12)
ttk.Button(footer, text="リスタート", command=self.new_game).pack(side=tk.RIGHT, padx=8)
# キーバインド
self.root.bind("<Left>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<Right>", lambda e: self.change_dir((1, 0)))
self.root.bind("<Up>", lambda e: self.change_dir((0, -1)))
self.root.bind("<Down>", lambda e: self.change_dir((0, 1)))
self.root.bind("<a>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<d>", lambda e: self.change_dir((1, 0)))
self.root.bind("<w>", lambda e: self.change_dir((0, -1)))
self.root.bind("<s>", lambda e: self.change_dir((0, 1)))
self.root.bind("<space>", lambda e: self.toggle_pause())
self.best_score = 0
self._after_id = None
def new_game(self):
if self._after_id:
self.root.after_cancel(self._after_id)
cx, cy = self.COLS // 2, self.ROWS // 2
self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
self.direction = (1, 0)
self.next_dir = (1, 0)
self.score = 0
self.paused = False
self.game_over = False
self._place_food()
self._draw()
self._tick()
def change_dir(self, d):
dx, dy = d
if (dx, dy) != (-self.direction[0], -self.direction[1]):
self.next_dir = d
def toggle_pause(self):
if self.game_over:
return
self.paused = not self.paused
if not self.paused:
self._tick()
def _place_food(self):
free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS)
if (x, y) not in self.snake]
self.food = random.choice(free)
def _tick(self):
if self.paused or self.game_over:
return
self.direction = self.next_dir
head = (self.snake[0][0] + self.direction[0],
self.snake[0][1] + self.direction[1])
# 壁・自分に衝突
if (head[0] < 0 or head[0] >= self.COLS or
head[1] < 0 or head[1] >= self.ROWS or
head in self.snake):
self.game_over = True
self._draw()
return
self.snake.insert(0, head)
if head == self.food:
self.score += 10
if self.score > self.best_score:
self.best_score = self.score
self.score_label.config(text=f"スコア: {self.score}")
self.best_label.config(text=f"ベスト: {self.best_score}")
self._place_food()
else:
self.snake.pop()
self._draw()
speed = max(60, self.SPEED - self.score // 50 * 10)
self._after_id = self.root.after(speed, self._tick)
def _draw(self):
self.canvas.delete("all")
c = self.CELL
# グリッド(薄く)
for x in range(0, self.COLS * c, c):
self.canvas.create_line(x, 0, x, self.ROWS * c, fill="#1a1a1a")
for y in range(0, self.ROWS * c, c):
self.canvas.create_line(0, y, self.COLS * c, y, fill="#1a1a1a")
# フード
fx, fy = self.food
self.canvas.create_oval(fx*c+3, fy*c+3, (fx+1)*c-3, (fy+1)*c-3,
fill="#ff4444", outline="")
# スネーク
for i, (x, y) in enumerate(self.snake):
color = "#00ff88" if i == 0 else "#00cc66" if i < 4 else "#009944"
self.canvas.create_rectangle(x*c+1, y*c+1, (x+1)*c-1, (y+1)*c-1,
fill=color, outline="")
if self.game_over:
self.canvas.create_rectangle(0, 0, self.COLS*c, self.ROWS*c,
fill="", stipple="gray50", outline="")
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 - 20,
text="GAME OVER", fill="white",
font=("Arial", 24, "bold"))
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 + 20,
text=f"スコア: {self.score}", fill="#aaa",
font=("Arial", 14))
if self.paused and not self.game_over:
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2,
text="PAUSE", fill="white",
font=("Arial", 24, "bold"))
if __name__ == "__main__":
root = tk.Tk()
app = App50(root)
root.mainloop()
例外処理とmessagebox
try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App50:
"""スネークゲーム"""
CELL = 20
COLS = 20
ROWS = 20
SPEED = 150 # ms
def __init__(self, root):
self.root = root
self.root.title("スネークゲーム")
self.root.configure(bg="#111")
self.root.resizable(False, False)
self._build_ui()
self.new_game()
def _build_ui(self):
# ヘッダー
header = tk.Frame(self.root, bg="#222", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🐍 スネークゲーム", font=("Noto Sans JP", 14, "bold"),
bg="#222", fg="#00ff88").pack(side=tk.LEFT, padx=12)
self.score_label = tk.Label(header, text="スコア: 0", font=("Noto Sans JP", 12),
bg="#222", fg="#fff")
self.score_label.pack(side=tk.LEFT, padx=16)
self.best_label = tk.Label(header, text="ベスト: 0", font=("Noto Sans JP", 10),
bg="#222", fg="#aaa")
self.best_label.pack(side=tk.LEFT)
# キャンバス
w = self.CELL * self.COLS
h = self.CELL * self.ROWS
self.canvas = tk.Canvas(self.root, width=w, height=h,
bg="#111", highlightthickness=0)
self.canvas.pack(padx=8, pady=4)
# フッター
footer = tk.Frame(self.root, bg="#111", pady=4)
footer.pack(fill=tk.X)
tk.Label(footer, text="矢印キー / WASD で操作 | Space でポーズ",
bg="#111", fg="#555", font=("Noto Sans JP", 9)).pack(side=tk.LEFT, padx=12)
ttk.Button(footer, text="リスタート", command=self.new_game).pack(side=tk.RIGHT, padx=8)
# キーバインド
self.root.bind("<Left>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<Right>", lambda e: self.change_dir((1, 0)))
self.root.bind("<Up>", lambda e: self.change_dir((0, -1)))
self.root.bind("<Down>", lambda e: self.change_dir((0, 1)))
self.root.bind("<a>", lambda e: self.change_dir((-1, 0)))
self.root.bind("<d>", lambda e: self.change_dir((1, 0)))
self.root.bind("<w>", lambda e: self.change_dir((0, -1)))
self.root.bind("<s>", lambda e: self.change_dir((0, 1)))
self.root.bind("<space>", lambda e: self.toggle_pause())
self.best_score = 0
self._after_id = None
def new_game(self):
if self._after_id:
self.root.after_cancel(self._after_id)
cx, cy = self.COLS // 2, self.ROWS // 2
self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
self.direction = (1, 0)
self.next_dir = (1, 0)
self.score = 0
self.paused = False
self.game_over = False
self._place_food()
self._draw()
self._tick()
def change_dir(self, d):
dx, dy = d
if (dx, dy) != (-self.direction[0], -self.direction[1]):
self.next_dir = d
def toggle_pause(self):
if self.game_over:
return
self.paused = not self.paused
if not self.paused:
self._tick()
def _place_food(self):
free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS)
if (x, y) not in self.snake]
self.food = random.choice(free)
def _tick(self):
if self.paused or self.game_over:
return
self.direction = self.next_dir
head = (self.snake[0][0] + self.direction[0],
self.snake[0][1] + self.direction[1])
# 壁・自分に衝突
if (head[0] < 0 or head[0] >= self.COLS or
head[1] < 0 or head[1] >= self.ROWS or
head in self.snake):
self.game_over = True
self._draw()
return
self.snake.insert(0, head)
if head == self.food:
self.score += 10
if self.score > self.best_score:
self.best_score = self.score
self.score_label.config(text=f"スコア: {self.score}")
self.best_label.config(text=f"ベスト: {self.best_score}")
self._place_food()
else:
self.snake.pop()
self._draw()
speed = max(60, self.SPEED - self.score // 50 * 10)
self._after_id = self.root.after(speed, self._tick)
def _draw(self):
self.canvas.delete("all")
c = self.CELL
# グリッド(薄く)
for x in range(0, self.COLS * c, c):
self.canvas.create_line(x, 0, x, self.ROWS * c, fill="#1a1a1a")
for y in range(0, self.ROWS * c, c):
self.canvas.create_line(0, y, self.COLS * c, y, fill="#1a1a1a")
# フード
fx, fy = self.food
self.canvas.create_oval(fx*c+3, fy*c+3, (fx+1)*c-3, (fy+1)*c-3,
fill="#ff4444", outline="")
# スネーク
for i, (x, y) in enumerate(self.snake):
color = "#00ff88" if i == 0 else "#00cc66" if i < 4 else "#009944"
self.canvas.create_rectangle(x*c+1, y*c+1, (x+1)*c-1, (y+1)*c-1,
fill=color, outline="")
if self.game_over:
self.canvas.create_rectangle(0, 0, self.COLS*c, self.ROWS*c,
fill="", stipple="gray50", outline="")
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 - 20,
text="GAME OVER", fill="white",
font=("Arial", 24, "bold"))
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 + 20,
text=f"スコア: {self.score}", fill="#aaa",
font=("Arial", 14))
if self.paused and not self.game_over:
self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2,
text="PAUSE", fill="white",
font=("Arial", 24, "bold"))
if __name__ == "__main__":
root = tk.Tk()
app = App50(root)
root.mainloop()
6. ステップバイステップガイド
このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。
-
1ファイルを作成する
新しいファイルを作成して app50.py と保存します。
-
2クラスの骨格を作る
App50クラスを定義し、__init__とmainloop()の最小構成を作ります。
-
3タイトルバーを作る
Frameを使ってカラーバー付きのタイトルエリアを作ります。
-
4入力フォームを実装する
LabelFrameとEntryウィジェットで入力エリアを作ります。
-
5処理ロジックを実装する
_calculate()メソッドに計算・処理ロジックを実装します。
-
6結果表示を実装する
TextウィジェットかLabelに結果を表示する_show_result()を実装します。
-
7エラー処理を追加する
try-exceptとmessageboxでエラーハンドリングを追加します。
7. カスタマイズアイデア
基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。少しずつ機能を追加することで、Pythonのスキルが飛躍的に向上します。
💡 ダークモードを追加する
bg色・fg色を辞書で管理し、ボタン1つでダークモード・ライトモードを切り替えられるようにしましょう。
💡 データのエクスポート機能
計算結果をCSV・TXTファイルに保存するエクスポート機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。
💡 入力履歴機能
以前の入力値を覚えておいてComboboxのドロップダウンで再選択できる履歴機能を追加しましょう。
8. よくある問題と解決法
❌ 日本語フォントが表示されない
原因:システムに日本語フォントが見つからない場合があります。
解決法:font引数を省略するかシステムに合ったフォントを指定してください。
❌ ウィンドウのサイズが変更できない
原因:resizable(False, False)が設定されています。
解決法:resizable(True, True)に変更してください。
9. 練習問題
アプリの理解を深めるための練習問題です。難易度順に挑戦してみてください。
-
課題1:機能拡張
スネークゲームに新しい機能を1つ追加してみましょう。どんな機能があると便利か考えてから実装してください。
-
課題2:UIの改善
色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしてみましょう。
-
課題3:保存機能の追加
入力値や計算結果をファイルに保存する機能を追加しましょう。jsonやcsvモジュールを使います。