#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2026/07/07 14:30:00 +0900> """ Ordering Table のサンプル(pygbag対応 + マウスクリック + Z値連動色変化版) Windows11 x64 25H2 + Python 3.10.10 64bit + pygame-ce 2.5.7 """ import asyncio import random import sys import pygame # 画面サイズと設定 SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 FPS = 60 # オーダリングテーブルの最大サイズ(Z値の範囲: 0 ~ 99) MAX_Z_LAYERS = 100 class CustomSprite: """独自のZ値を持つゲームオブジェクト""" def __init__(self, x, y, width, height, z): self.rect = pygame.Rect(x, y, width, height) self.z = z # 浮動小数点数などの任意の数値 # --- Z値(0.0〜99.9)に応じて色を計算 --- # 0.0で128、99.9で約32になるように補間 ratio = z / 100.0 color_val = int(192 - (160 * ratio)) self.color = (color_val, color_val, color_val) def draw(self, surface, font): # 描画処理(わかりやすいようにZ値もテキストで表示) pygame.draw.rect(surface, self.color, self.rect, 0) # 枠線描画 pygame.draw.rect(surface, pygame.Color(255, 255, 255, 255), self.rect, 2) text = font.render(f"Z: {self.z:.1f}", True, (255, 255, 255)) surface.blit(text, (self.rect.x + 5, self.rect.y + 5)) async def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Ordering Table Draw System") clock = pygame.time.Clock() font = pygame.font.Font(None, 24) initfg = True # メインループ running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False elif event.key == pygame.K_q: running = False elif event.key == pygame.K_r: initfg = True elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: initfg = True if initfg: # ---------------------------------------- # 1. オブジェクトの生成 # ---------------------------------------- sprites = [] for _ in range(15): x = random.randint(100, 600) y = random.randint(100, 400) z = random.uniform(0.0, 99.9) # colorの指定を無くし、内部でZ値から自動計算するように変更 sprites.append(CustomSprite(x, y, 100, 100, z)) initfg = False # 画面クリア screen.fill((0, 0, 0)) # ------------------------------------------------------------- # 2. オーダリングテーブルの初期化 # ------------------------------------------------------------- ordering_table = [[] for _ in range(MAX_Z_LAYERS)] # ------------------------------------------------------------- # 3. オブジェクトを整数値に変換したZ値のレイヤーに登録 # ------------------------------------------------------------- for sprite in sprites: z_index = int(sprite.z) z_index = max(0, min(z_index, MAX_Z_LAYERS - 1)) ordering_table[z_index].append(sprite) # ------------------------------------------------------------- # 4. オーダリングテーブルに基づいて奥から一気に描画 # ------------------------------------------------------------- for z_layer in reversed(ordering_table): for sprite in z_layer: sprite.draw(screen, font) pygame.display.flip() clock.tick(FPS) await asyncio.sleep(0) pygame.quit() sys.exit() if __name__ == "__main__": asyncio.run(main())