Pythonで数字当てゲームのGUIを作る」の後編です。最初のパートでは、推測ゲームをコマンドラインインターフェースで実装する方法について見てきました。この記事では、次のレベルとして、ユーザーと対話できるグラフィカル・ユーザー・インターフェース・アプリケーションを作成します。
前回の記事を読んでいない場合は、先にそちらを読むことをお勧めします。ゲームのロジックと主なソースコードの実装を説明しているからです。
この記事もチェック:Python Qtを使ってGUIアプリケーションを実装する方法
数当てゲームのGUIをデザインする
PythonにはTkinterと呼ばれるGUI用のライブラリがあります。Tkinterは比較的軽量で、私たちのPython環境に多くの基本的な3Dインタラクティブ要素を提供してくれます。そこで、この記事ではTkinterを使用することにします。読者は初級レベルのTkinterを理解していることが期待されます。
それでは、今日設計するアプリケーションのGUIをスケッチしてみましょう。以下は、GUIの基本的なレイアウトです。
- ゲームの名前を表示するタイトルがあります。
- 数字を入力するフォーム要素が1つあります。
- ゲームを開始するためのボタンが1つ
- GUIを閉じるためのボタンが1つ
これらのリストされたポイントのほとんどは、かなり直感的ですが、コーディングの前にこの設計は、将来の混乱や誤解を避けるのに役立ちます偉大な練習です。
ライブラリをインポートする
必要なライブラリをインポートします。GUI作成には先ほど説明したTkinterを、乱数生成にはrandomモジュールを使用する予定です。
import tkinter as tk
import random
|
この記事もチェック:Pythonのrandomモジュールを使って乱数を簡単に作成する方法
空白のウィンドウを作成する
まず最初に、テキストやインタラクティブな要素のない、任意の背景を持つ空白のウィンドウを作成します。
import tkinter as tk
import random
# Create a new windowwindow = tk.Tk()
# Set the dimensions of the created windowwindow.geometry("600x400")
# Set the background color of the windowwindow.config(bg="#065569")
window.resizable(width=False,height=False)
# Set Window Titlewindow.title('Number Guessing Game')
# The code for the buttons and text and other # interactive UI elements go here # Start the windowwindow.mainloop() |
# Create exit Button# We can customize the background(bg) and foreground(fg) color# Here we have chosen bg to be Red for visual aestheticexit_button = tk.Button(window,text="Exit Game",font=("Arial",14), fg="White", bg="#b82741", command=exit)
# Place the exit button at a suitable placeexit_button.place(x=300,y=320)
|
これは基本的なスクラッチパッドです。次のステップでは、このウィンドウの中に要素を追加していきます。クローズボタンがないので、今は強制的にウィンドウを閉じる必要があります。そこで、アプリケーションを優雅に終了させる終了ボタンを用意することが先決です。
終了ボタンの追加
ボタンを追加するには、tkinter.Button()関数を使用します。
# Heading of our gametitle = tk.Label(window,text="Guessing Game",font=("Arial",24),fg="#fffcbd",bg="#065569")
# Result and hints of our gameresult = tk.Label(window, text="Click on Play to start a new game", font=("Arial", 12, "normal", "italic"),fg = "White", bg="#065569", justify=tk.LEFT)
# Display labelstitle.place(x=170, y=50)
result.place(x=180, y=210)
|
# The play buttonplay_button = tk.Button(window, text="Play Game", font=("Arial", 14, "bold"), fg = "Black", bg="#29c70a")
# The guess button# This button initially disabled because we don't want the user to guess a number before the game has startedguess_button = tk.Button(window,text="Guess",font=("Arial",13), state='disabled', fg="#13d675",bg="Black")
# Place the buttons in the windowguess_button.place(x=350, y=147)
play_button.place(x=170, y=320)
|
Note : これで基本的な終了ボタンができましたので、残りの要素を追加し、ウィンドウを強制的に閉じずに再配置することができます。
残りの数字当てゲームGUIを追加する
ラベルの作成
このアプリケーションでは、2つのラベルが必要です。一つはGameラベル、もう一つは結果やヒントを表示するためのものです。
# The object that stores the value in the entry fieldguessed_number = tk.StringVar()
# Create entry field and attach it the guessed_number object that stores the valuenumber_form = tk.Entry(window,font=("Arial",11),textvariable=guessed_number)
# Place it in the windownumber_form.place(x=180, y=150)
|
ボタンの追加
ゲームをプレイする」、「ゲームを当てる」、「ゲームを終了する」の3つのボタンが必要です。使い勝手を考えて、「終了」ボタンを実装しています。
TARGET = 1.
RETRIES = 0
|
Note: ボタンは一般に、そのボタンがクリックされたときに実行されるコマンドと関連付けられています。ボタンに関連づけられたコマンドについては、次のセクションで説明します。
フォーム/エントリーフィールドの作成
最後に、ユーザーから数字の入力を受けるための入力フィールドが必要です。また、フォームに入力された値を格納するための変数も必要です。
def update_result(text):
result.configure(text=text)
|
def new_game():
# Change the state of guess button
guess_button.config(state='normal')
# Mention to use global variables
global TARGET, RETRIES
# Create a new target
TARGET = random.randint(0, 1000)
# Reset number of retires to 0
RETRIES = 0
update_result(text="Guess a number between)
|
ロジックの実装
UIを作ったら 今度はゲームのロジックを見てみましょう。推測ボタンと再生ボタンを押したときに何が起こるかを定義する必要があります。そこで、アプリケーションの2つのボタンに関連する関数を定義します。
まず、グローバル変数 TARGET と RETRIES を使ってターゲットとリタイアの数を格納し、両方に初期値を設定します。
def play_game():
global RETRIES
choice = int(number_form.get())
if choice != TARGET:
RETRIES += 1
result = "Wrong Guess!! Try Again"
if TARGET < choice:
hint = "The required number lies between 0 and {}".format(result)
else:
hint = "The required number lies between {} and 1000".format(choice)
result += "
+ hint
else:
result = "You guessed the correct number after {} retries".format(RETRIES)
# Set the state to disabled again
guess_button.configure(state='disabled')
result += " + "Click on Play to start a new game"
update_result(result)
|
次に、result ラベルを適宜更新する関数を定義します。
# Play Buttonplay_button = tk.Button(window, text="Play Game", font=("Arial", 14, "bold"), fg = "Black", bg="#29c70a", command=new_game)
# Guess Buttonguess_button = tk.Button(window,text="Guess",font=("Arial",13), state='disabled', fg="#13d675",bg="Black", command=play_game)
|
これで Play と Guess ボタンの関数を定義する準備が整いました。
再生ボタンはグローバル変数を適切な値で再初期化し、Guessボタンは通常状態にします。
import tkinter as tk
import random
# Create a new windowwindow = tk.Tk()
# Set the dimensions of the created windowwindow.geometry("600x400")
# Set the background color of the windowwindow.config(bg="#065569")
window.resizable(width=False,height=False)
# Set Window Titlewindow.title('Number Guessing Game')
# The code for the buttons and text and other # interactive UI elements go here TARGET = random.randint(0, 1000)
RETRIES = 0
def upate_result(text):
result.configure(text=text)
# Create a new gamedef new_game():
guess_button.config(state='normal')
global TARGET, RETRIES
TARGET = random.randint(0, 1000)
RETRIES = 0
update_result(text="Guess a number between)
# Continue the ongoing game or end itdef play_game():
global RETRIES
choice = int(number_form.get())
if choice != TARGET:
RETRIES += 1
result = "Wrong Guess!! Try Again"
if TARGET < choice:
hint = "The required number lies between 0 and {}".format(result)
else:
hint = "The required number lies between {} and 1000".format(choice)
result += "
+ hint
else:
result = "You guessed the correct number after {} retries".format(RETRIES)
guess_button.configure(state='disabled')
result += " + "Click on Play to start a new game"
update_result(result)
# Heading of our gametitle = tk.Label(window,text="Guessing Game",font=("Arial",24),fg="#fffcbd",bg="#065569")
# Result and hints of our gameresult = tk.Label(window, text="Click on Play to start a new game", font=("Arial", 12, "normal", "italic"),fg = "White", bg="#065569", justify=tk.LEFT)
# Play Buttonplay_button = tk.Button(window, text="Play Game", font=("Arial", 14, "bold"), fg = "Black", bg="#29c70a", command=new_game)
# Guess Buttonguess_button = tk.Button(window,text="Guess",font=("Arial",13), state='disabled', fg="#13d675",bg="Black", command=play_game)
# Exit Buttonexit_button = tk.Button(window,text="Exit Game",font=("Arial",14), fg="White", bg="#b82741", command=exit)
# Entry Fieldsguessed_number = tk.StringVar()
number_form = tk.Entry(window,font=("Arial",11),textvariable=guessed_number)
# Place the labelstitle.place(x=170, y=50)
result.place(x=180, y=210)
# Place the buttonsexit_button.place(x=300,y=320)
guess_button.place(x=350, y=147)
play_button.place(x=170, y=320)
# Place the entry fieldnumber_form.place(x=180, y=150)
# Start the windowwindow.mainloop() |
推測ボタンは入力フォームの入力を読み取り、それに応じた結果とヒントを与える。ユーザーが正しい結果を出した場合、推測ボタンの状態は再びdisabled`となり、ユーザーは既に終了したゲームを推測する代わりに、新しいゲームを開始するか、アプリケーションを終了するように強制されます。

ボタンコマンドの追加
さて、最後に各ボタンにコマンドを割り当てる必要があります。関数呼び出しの最後に command 変数を追加する必要があります。新しいボタンの定義は次のようになります。

ファイナルコード
さて、これがアプリケーションの最終的なコードブロックです。

以下は、私たちのゲームのグラフィカル・ユーザー・インターフェイスの例です。
ゲームのオープニングインスタンス

ユーザーがゲームを開始したときのUIインスタンス

ユーザーが間違った推測をしたときのUIインスタンス

ユーザーが数字を正しく推測したときのUIインスタンス

結論
ランダム・ゲッシング・ゲームに関するこの2部構成のチュートリアルは、これで終わりです。UIを微調整して、あなたの好みの色やUIにすることをお勧めします。また、このようなPythonの記事を楽しみにしていてください。