プログラミング言語「Python」で制作 Part58 | Photoshop CC Tutorials

今回はプログラミング言語の「Python」を使って作成しました。

 

脳トレアプリを開発しました。

 

■ プログラム

import traceback
 
try:

    import myUI
    import pygame
    import sys
    from pygame.locals import *
    import random

    inputBtn = None
    selectBtn = None
    calcBtns = None
    text = None
    PHASE = 0

    def phase1(pygame, screen):
        global calcBtns, selectBtn, text, PHASE, inputBtn
        # 計算画面ボタン
        inputBtn.setText('')
        text.setText('空白に何が入る?')
        selectBtn = None
        calcBtns[0].number = random.randint(1, 9)
        calcBtns[0].setText(calcBtns[0].number)
        calcBtns[2].number = random.randint(9, 18)
        calcBtns[2].setText(calcBtns[2].number)
        PHASE = 0

    def main():
        global inputBtn, selectBtn, PHASE, text, calcBtns

        pygame.init() # Pygameを初期化
        screen = pygame.display.set_mode((600, 650)) # 画面作成
        running = True # 実行継続フラグ

        # ボタンインスタンス作成
        buttons = [[0 for i in range(3)] for j in range(7)]
        for i in range(7):
            for j in range(3):
                button = myUI.Button(j*150 + 75, i*50 + 260, 150, 50, i*3 + j, 40, (0, 255, 0), screen, pygame)
                buttons[i][j] = button

        # フレームインスタンス作成
        frame = myUI.Frame(25, 25, 550, 200, (0, 255, 0), screen, pygame)

        # テキストインスタンス作成
        text = myUI.Text(25, 25, 550, 220, '空白に何が入る?', 0, 0, 40, (0, 255, 0), True, screen, pygame)
        text2 = myUI.Text(25, 25, 550, 320, '「脳トレゲーム 脳を鍛えよう!」', 0, 0, 20, (0, 255, 0), True, screen, pygame)

        # 計算画面ボタン
        calcBtn_00 = myUI.Button(150, 40, 60, 60, random.randint(1, 9), 40, (0, 255, 0), screen, pygame)
        # 計算画面テキスト
        calcText_00 = myUI.Text(210, 40, 60, 60, '+', 0, 0, 40, (0, 255, 0), True, screen, pygame)
        # 計算画面ボタン
        calcBtn_01 = myUI.Button(270, 40, 60, 60, '', 40, (255, 255, 0), screen, pygame)
        # 計算画面テキスト
        calcText_01 = myUI.Text(330, 40, 60, 60, '=', 0, 0, 40, (0, 255, 0), True, screen, pygame)
        # 計算画面ボタン
        calcBtn_02 = myUI.Button(390, 40, 60, 60, random.randint(9, 18), 40, (0, 255, 0), screen, pygame)

        inputBtn = calcBtn_01

        calcBtns = [0 for j in range(3)]
        calcBtns = [calcBtn_00, calcBtn_01, calcBtn_02]

        while running:
            pygame.display.update() # 画面を更新
            screen.fill(pygame.Color(0, 0, 0)) # 画面を塗りつぶす

            # ボタン描画
            for items in buttons:
                for button in items:
                    button.draw()

            frame.draw()  # 枠描画
            text.draw()   # テキスト描画
            text2.draw()   # テキスト描画

            for calcBtn in calcBtns:
                calcBtn.draw() # 計算画面ボタン描画

            calcText_00.draw() # 計算画面テキスト描画
            calcText_01.draw() # 計算画面テキスト描画

            for event in pygame.event.get(): # イベント
                if event.type == pygame.QUIT: running = False # 終了

                if event.type == pygame.MOUSEBUTTONDOWN:

                    if PHASE == 1:
                        phase1(pygame, screen)

                    else:
                        for items in buttons:
                            for button in items:
                                if button.collider(event):
                                    selectBtn = button

                        for calcBtn in calcBtns:
                            if calcBtn.collider(event):
                                inputBtn = calcBtn

                        inputBtn.col = (255, 255, 0)

            #------------------------------------------------------------
            # 計算
            #------------------------------------------------------------
            if PHASE == 0:
                if selectBtn and inputBtn is calcBtns[1]:
                    inputBtn.setText(selectBtn.number)
                    inputBtn.number = selectBtn.number
                    if (calcBtns[0].number + calcBtns[1].number) == calcBtns[2].number:
                        text.setText('正解!!')
                        PHASE = 1
                    else:
                        text.setText('不正解!!')
                        PHASE = 1

            pygame.display.flip() # 画面フリップ
        pygame.quit() # Pygameを終了

    if __name__=="__main__":
        main()

except Exception as e:
    # 文字列を取得する format_exec()メソッド
    print("エラー情報\n" + traceback.format_exc())

input()

 

from PIL import Image, ImageFont, ImageDraw
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator

class Button:

	# コンストラクタ
	def __init__(self, bx, by, bw, bh, text, fsize, col, screen, pygame):
		# creates a rect object
		self.button = pygame.Rect(bx, by, bw, bh)

		# フォントの用意  
		self.font = pygame.font.Font("ipaexg.ttf", fsize)

		# テキストの設定
		self.text = self.font.render(str(text), True, col)

		# テキスト幅
		textW, textH = self.getTextSize(str(text), fsize)

		# ボタンを中央に配置する
		self.tx = (bw - textW)/2 + bx
		self.ty = (bh - textH)/2 + by

		self.screen = screen
		self.pygame = pygame
		self.col = col
		self.bx = bx
		self.by = by
		self.bw = bw
		self.bh = bh
		self.fsize = fsize

		if type(text) == str:
			self.number = 0
		else:
			self.number = text

	def setText(self, text):

		# フォントの用意  
		self.font = self.pygame.font.Font("ipaexg.ttf", self.fsize)

		# テキストの設定
		self.text = self.font.render(str(text), True, self.col)

		# テキスト幅
		textW, textH = self.getTextSize(str(text), self.fsize)

		# ボタンを中央に配置する
		self.tx = (self.bw - textW)/2 + self.bx
		self.ty = (self.bh - textH)/2 + self.by

	def draw(self):
		self.pygame.draw.rect(self.screen, self.col, self.button, 5)
		self.screen.blit(self.text, (self.tx, self.ty))

	def getTextSize(self, text, fsize):
		img = np.zeros((30, 50, 3), np.uint8)            # 新規黒塗画像を作成
		message = text                                   # 文字列を定義

		img = Image.fromarray(img)                       # cv2(NumPy)型の画像をPIL型に変換
		draw = ImageDraw.Draw(img)

		# .textlengthで文字列のピクセルサイズを取得
		font_size = fsize
		font = ImageFont.truetype("ipaexg.ttf", size=font_size)
		txw = draw.textlength(message, font=font)
		txh = font_size

		return(txw, txh)

	def collider(self, event):
		if self.button.collidepoint(event.pos):
			self.col = (255, 255, 0)
			return True
		else:
			self.col = (0, 255, 0)
			return False

class Frame:

	# コンストラクタ
	def __init__(self, fx, fy, fw, fh, col, screen, pygame):
		self.background = pygame.Rect(fx, fy, fw, fh)
		self.screen = screen
		self.pygame = pygame
		self.col = col
		
	def draw(self):
		self.pygame.draw.rect(self.screen, self.col, self.background, 10)

class Text:

	# コンストラクタ
	def __init__(self, bx, by, bw, bh, text, tx, ty, fsize, col, center, screen, pygame):
		# フォントの用意  
		self.font = pygame.font.Font("ipaexg.ttf", fsize)

		# テキストの設定
		self.text = self.font.render(text, True, col)

		if center == True:
			# テキスト幅
			textW, textH = self.getTextSize(text, fsize)
			# テキストを中央に配置する
			self.tx = (bw - textW)/2 + bx
			self.ty = (bh - textH)/2 + by
		elif center == False:
			self.tx = tx
			self.ty = ty

		self.screen = screen
		self.pygame = pygame
		self.fsize = fsize
		self.col = col
		self.bx = bx
		self.by = by
		self.bw = bw
		self.bh = bh
		self.center = center

	def getTextSize(self, text, fsize):
		img = np.zeros((30, 50, 3), np.uint8)            # 新規黒塗画像を作成
		message = text                                   # 文字列を定義

		img = Image.fromarray(img)                       # cv2(NumPy)型の画像をPIL型に変換
		draw = ImageDraw.Draw(img)

		# .textlengthで文字列のピクセルサイズを取得
		font_size = fsize
		font = ImageFont.truetype("ipaexg.ttf", size=font_size)
		txw = draw.textlength(message, font=font)
		txh = font_size

		return(txw, txh)

	def setText(self, text):
		# フォントの用意  
		self.font = self.pygame.font.Font("ipaexg.ttf", self.fsize)

		# テキストの設定
		self.text = self.font.render(text, True, self.col)

		if self.center == True:
			# テキスト幅
			textW, textH = self.getTextSize(text, self.fsize)

			# テキストを中央に配置する
			self.tx = (self.bw - textW)/2 + self.bx
			self.ty = (self.bh - textH)/2 + self.by
		elif self.center == False:
			self.tx = self.tx
			self.ty = self.ty

	def draw(self):
		self.screen.blit(self.text, (self.tx, self.ty))

 

 

 

■ ゲーム用ライブラリ

「Pygame」

 

■ プログラミング言語