(記述中...)
import pygame
import time
from random import *
import colorsys
# 初期化
pygame.init()
pygame.display.set_caption("pygame アプリ")
DISP_SIZE = (480, 480) # 横, 縦
surf = pygame.display.set_mode(DISP_SIZE)
# 色を定義しておく (タプル:固定)
COLOR_BG = (32, 32, 32)
# 座標, サイズ, 速度, 色 を管理するオブジェクトを定義
class MyRect:
def __init__(self, _pos, _size, _speed, _color):
self.pos = _pos
self.size = _size
self.speed = _speed
self.color = _color
def move(self):
self.pos[0] += self.speed[0]
self.pos[1] += self.speed[1]
# MyRect を格納するリスト
myRects = []
RECT_NUM = 30 # 作る個数
for i in range(RECT_NUM):
beautiful_RGB = []
# HSV で RGB の色を生成
# 1.色合い (0.00:赤, 0.33:緑, 0.66:青)
# ※今回は橙色(0.07~0.17)にした
# 2.鮮やかさ (0.0:薄い, 1.0:濃い)
# 3.明るさ (0.0:暗い, 1.0:明るい)
for x in colorsys.hsv_to_rgb(0.07 + (random() * 0.1), 1.0, 1.0):
# hsv_to_rgb は、例えば (1.0, 0.25, 0.5) といった具合で、
# 3つの小数のタプルで 赤,緑,青 の値を返す。
# 対して pygame は (255, 64, 127) といった具合で、
# 3つの整数(0~255)で 赤,緑,青 を扱うので、255 倍する。
beautiful_RGB.append(x * 255)
# 四角形を生成し、四角形リストに追加していく
myRects.append(
MyRect(
[randint(0, DISP_SIZE[0]-1), randint(0, DISP_SIZE[1]-1)], # 座標
[64, 64], [4, 4], # サイズ, 速度
beautiful_RGB # HSVで生成した色
))
# 閉じるを押すまでループ
running = True
while running:
for myRect in myRects:
# 座標更新
myRect.move()
# もし画面端にたどり着いた場合は反転
if myRect.pos[0] > (DISP_SIZE[0] - myRect.size[0]) or myRect.pos[0] < 0:
myRect.speed[0] *= -1
if myRect.pos[1] > (DISP_SIZE[1] - myRect.size[1]) or myRect.pos[1] < 0:
myRect.speed[1] *= -1
# 描画
surf.fill(COLOR_BG)
for myRect in myRects:
pygame.draw.rect(surf, myRect.color, (*myRect.pos, *myRect.size))
pygame.display.update()
# ウェイト
time.sleep(0.016)
# イベント
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False