Spaces:
Sleeping
Sleeping
File size: 17,261 Bytes
1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b 1391263 7d5b76b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 |
# Hugging Face Spaces対応 - クリック操作版
# app.py として保存
import gradio as gr
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
import json
from datetime import datetime
from io import BytesIO
from PIL import Image
class PennyPackerGame:
def __init__(self):
self.sector_center = (0, 0)
self.sector_radius = 4.0
self.coin_radius = 0.5
self.num_coins = 16
self.coins = []
self.initialize_coins()
self.selected_coin = 0 # デフォルトで最初のコインを選択
def initialize_coins(self):
"""4x4グリッドで初期配置"""
self.coins = []
spacing = 0.8
start_x = 0.5
start_y = 0.5
for i in range(4):
for j in range(4):
x = start_x + j * spacing
y = start_y + i * spacing
self.coins.append({'x': x, 'y': y})
def is_inside_sector(self, x, y):
"""コインが完全に扇形内にあるかチェック"""
max_distance = np.sqrt(x**2 + y**2) + self.coin_radius
if max_distance > self.sector_radius:
return False
if x - self.coin_radius < 0 or y - self.coin_radius < 0:
return False
return True
def check_overlap(self, coin_index):
"""指定したコインが他のコインと重なっているかチェック"""
coin1 = self.coins[coin_index]
for i, coin2 in enumerate(self.coins):
if i == coin_index:
continue
dx = coin1['x'] - coin2['x']
dy = coin1['y'] - coin2['y']
distance = np.sqrt(dx**2 + dy**2)
if distance < 2 * self.coin_radius - 0.001:
return True
return False
def evaluate_layout(self):
"""現在のレイアウトを評価"""
valid_coins = 0
for i in range(len(self.coins)):
coin = self.coins[i]
inside = self.is_inside_sector(coin['x'], coin['y'])
overlap = self.check_overlap(i)
if inside and not overlap:
valid_coins += 1
return valid_coins
def draw_figure(self):
"""Matplotlib図を生成"""
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_aspect('equal')
margin = 0.5
ax.set_xlim(-margin, self.sector_radius + margin)
ax.set_ylim(-margin, self.sector_radius + margin)
# 扇形の描画
sector = patches.Wedge(
center=self.sector_center, r=self.sector_radius,
theta1=0, theta2=90,
facecolor='lightblue', alpha=0.15,
edgecolor='blue', linewidth=2
)
ax.add_patch(sector)
ax.plot([0, self.sector_radius], [0, 0], 'b-', linewidth=2)
ax.plot([0, 0], [0, self.sector_radius], 'b-', linewidth=2)
theta = np.linspace(0, 90, 100)
x_arc = self.sector_radius * np.cos(np.radians(theta))
y_arc = self.sector_radius * np.sin(np.radians(theta))
ax.plot(x_arc, y_arc, 'b-', linewidth=2)
ax.plot(0, 0, 'ro', markersize=8)
ax.grid(True, alpha=0.3, linestyle='--')
# コインの描画
for i, coin in enumerate(self.coins):
inside = self.is_inside_sector(coin['x'], coin['y'])
overlap = self.check_overlap(i)
if inside and not overlap:
color = 'limegreen'
alpha = 0.9
elif inside:
color = 'orange'
alpha = 0.7
else:
color = 'lightcoral'
alpha = 0.5
# 選択されているコインを強調
if self.selected_coin == i:
edgecolor = 'red'
linewidth = 4
else:
edgecolor = 'darkgoldenrod'
linewidth = 2
circle = patches.Circle(
(coin['x'], coin['y']), self.coin_radius,
facecolor=color, edgecolor=edgecolor,
linewidth=linewidth, alpha=alpha
)
ax.add_patch(circle)
# コイン番号
ax.text(coin['x'], coin['y'], str(i+1),
ha='center', va='center',
fontsize=14, fontweight='bold', color='white',
bbox=dict(boxstyle='circle', facecolor='black', alpha=0.5, pad=0.3))
# 評価
valid_count = self.evaluate_layout()
if valid_count >= 16:
title = '🎉 SOLUTION FOUND! 🎉'
title_color = 'green'
else:
title = f'Penny Packer 16 - {valid_count}/16 valid'
title_color = 'darkblue'
ax.set_title(title, fontsize=18, color=title_color, weight='bold', pad=20)
ax.set_xlabel('X', fontsize=14, fontweight='bold')
ax.set_ylabel('Y', fontsize=14, fontweight='bold')
plt.tight_layout()
# 画像に変換
buf = BytesIO()
plt.savefig(buf, format='png', dpi=120, bbox_inches='tight')
buf.seek(0)
img = Image.open(buf)
plt.close(fig)
return img
def get_status_text(self):
"""ステータステキストを生成"""
valid_count = self.evaluate_layout()
text = f"## Status: {valid_count}/16 valid coins\n\n"
if valid_count >= 16:
text += "### 🎉 **SOLUTION FOUND!** 🎉\n\n"
else:
text += f"### Need {16 - valid_count} more valid coins\n\n"
text += f"**Selected Coin:** #{self.selected_coin + 1} at ({self.coins[self.selected_coin]['x']:.2f}, {self.coins[self.selected_coin]['y']:.2f})\n\n"
text += f"**Coin Radius:** {self.coin_radius:.2f}\n"
text += f"**Sector Radius:** {self.sector_radius:.2f}\n\n"
text += "**Legend:**\n"
text += "- 🟢 Green: Valid\n"
text += "- 🟠 Orange: Overlapping\n"
text += "- 🔴 Red: Outside\n"
text += "- **Red border**: Selected\n"
return text
# グローバルゲームインスタンス
game = PennyPackerGame()
# Gradioインターフェース関数
def update_display(coin_radius, sector_radius):
"""表示を更新"""
game.coin_radius = coin_radius
game.sector_radius = sector_radius
img = game.draw_figure()
status = game.get_status_text()
return img, status
def select_next_coin():
"""次のコインを選択"""
game.selected_coin = (game.selected_coin + 1) % 16
return game.draw_figure(), game.get_status_text(), f"Coin #{game.selected_coin + 1} selected"
def select_prev_coin():
"""前のコインを選択"""
game.selected_coin = (game.selected_coin - 1) % 16
return game.draw_figure(), game.get_status_text(), f"Coin #{game.selected_coin + 1} selected"
def select_coin_number(coin_num):
"""コイン番号で選択"""
if 1 <= coin_num <= 16:
game.selected_coin = coin_num - 1
return game.draw_figure(), game.get_status_text(), f"Coin #{game.selected_coin + 1} selected"
return game.draw_figure(), game.get_status_text(), "Invalid coin number"
def move_up():
"""選択したコインを上に移動"""
game.coins[game.selected_coin]['y'] += 0.1
return game.draw_figure(), game.get_status_text(), "Moved up"
def move_down():
"""選択したコインを下に移動"""
game.coins[game.selected_coin]['y'] -= 0.1
return game.draw_figure(), game.get_status_text(), "Moved down"
def move_left():
"""選択したコインを左に移動"""
game.coins[game.selected_coin]['x'] -= 0.1
return game.draw_figure(), game.get_status_text(), "Moved left"
def move_right():
"""選択したコインを右に移動"""
game.coins[game.selected_coin]['x'] += 0.1
return game.draw_figure(), game.get_status_text(), "Moved right"
def click_to_move(evt: gr.SelectData):
"""画像クリックでコインを移動"""
# Gradioの画像クリックイベントからピクセル座標を取得
# 画像サイズとプロット範囲から論理座標に変換
img_width = 1000 # 推定画像幅(DPI 120 x 10インチ ≈ 1200)
img_height = 1000
click_x = evt.index[0] # ピクセルX
click_y = evt.index[1] # ピクセルY
# おおよその座標変換(余白を考慮)
margin = 0.5
plot_range = game.sector_radius + 2 * margin
# 画像の有効範囲を推定(余白を除く)
effective_margin_px = 100 # 推定余白ピクセル
effective_width = img_width - 2 * effective_margin_px
effective_height = img_height - 2 * effective_margin_px
# ピクセル座標を論理座標に変換
logical_x = ((click_x - effective_margin_px) / effective_width) * plot_range - margin
logical_y = plot_range - ((click_y - effective_margin_px) / effective_height) * plot_range - margin
# 範囲チェック
if logical_x < -margin or logical_x > game.sector_radius + margin:
return game.draw_figure(), game.get_status_text(), "Click within the plot area"
if logical_y < -margin or logical_y > game.sector_radius + margin:
return game.draw_figure(), game.get_status_text(), "Click within the plot area"
# コインを移動
game.coins[game.selected_coin]['x'] = max(0, min(game.sector_radius, logical_x))
game.coins[game.selected_coin]['y'] = max(0, min(game.sector_radius, logical_y))
return game.draw_figure(), game.get_status_text(), f"Coin #{game.selected_coin + 1} moved to ({logical_x:.2f}, {logical_y:.2f})"
def reset_positions():
"""位置をリセット"""
game.initialize_coins()
game.selected_coin = 0
return game.draw_figure(), game.get_status_text(), "Positions reset"
def randomize_positions():
"""ランダム配置"""
for coin in game.coins:
coin['x'] = np.random.uniform(0.5, game.sector_radius - 0.5)
coin['y'] = np.random.uniform(0.5, game.sector_radius - 0.5)
return game.draw_figure(), game.get_status_text(), "Coins randomized"
def auto_arrange():
"""自動配置(六方格子パターン)"""
spacing = 2 * game.coin_radius * 1.02
dx = spacing
dy = spacing * np.sqrt(3) / 2
positions = []
for row in range(5):
for col in range(5):
row_offset = (row % 2) * dx * 0.5
x = 0.5 + col * dx + row_offset
y = 0.5 + row * dy
if x + game.coin_radius <= game.sector_radius and y + game.coin_radius <= game.sector_radius:
positions.append((x, y))
for i, (x, y) in enumerate(positions[:16]):
game.coins[i]['x'] = x
game.coins[i]['y'] = y
return game.draw_figure(), game.get_status_text(), "Auto-arranged in hexagonal pattern"
def check_solution():
"""解答チェック"""
valid_count = game.evaluate_layout()
result = "="*50 + "\n"
result += "SOLUTION CHECK\n"
result += "="*50 + "\n"
result += f"Valid coins: {valid_count}/16\n"
result += f"Coin radius: {game.coin_radius:.2f}\n"
result += f"Sector radius: {game.sector_radius:.2f}\n"
result += "="*50 + "\n"
if valid_count >= 16:
result += "✓ VALID SOLUTION FOUND!\n"
else:
result += f"✗ Need {16 - valid_count} more valid coins\n"
result += "="*50
return result
def export_json():
"""JSON出力"""
config = {
'coin_radius': game.coin_radius,
'sector_radius': game.sector_radius,
'coins': game.coins,
'valid_count': game.evaluate_layout(),
'timestamp': datetime.now().isoformat()
}
return json.dumps(config, indent=2)
def import_json(json_str):
"""JSON読み込み"""
try:
config = json.loads(json_str)
game.coin_radius = config['coin_radius']
game.sector_radius = config['sector_radius']
game.coins = config['coins']
return game.draw_figure(), game.get_status_text(), f"Configuration loaded ({config['valid_count']}/16 valid)"
except Exception as e:
return game.draw_figure(), game.get_status_text(), f"Error: {str(e)}"
# Gradio UIの構築
with gr.Blocks(title="Penny Packer 16", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🪙 Penny Packer 16 - Interactive Puzzle")
gr.Markdown("**Goal:** Fit all 16 coins into the quarter circle without overlaps!")
with gr.Row():
with gr.Column(scale=2):
image_output = gr.Image(label="🎮 Game Board (Click to move selected coin)", type="pil")
gr.Markdown("### 🎛️ Adjust Radii")
with gr.Row():
coin_radius_slider = gr.Slider(0.2, 1.0, value=0.5, step=0.01, label="Coin Radius")
sector_radius_slider = gr.Slider(2.0, 8.0, value=4.0, step=0.1, label="Sector Radius")
with gr.Column(scale=1):
status_output = gr.Markdown(value="Loading...")
gr.Markdown("### 🎯 Select Coin")
with gr.Row():
prev_btn = gr.Button("◀ Prev", size="sm")
coin_num_input = gr.Number(label="Coin #", value=1, minimum=1, maximum=16, precision=0)
next_btn = gr.Button("Next ▶", size="sm")
gr.Markdown("### ⬆️⬇️⬅️➡️ Move Selected Coin")
with gr.Column():
with gr.Row():
gr.Button("", visible=False, scale=1)
up_btn = gr.Button("⬆️ Up", scale=2)
gr.Button("", visible=False, scale=1)
with gr.Row():
left_btn = gr.Button("⬅️ Left")
center_text = gr.Markdown("**Move**", elem_classes="center")
right_btn = gr.Button("➡️ Right")
with gr.Row():
gr.Button("", visible=False, scale=1)
down_btn = gr.Button("⬇️ Down", scale=2)
gr.Button("", visible=False, scale=1)
gr.Markdown("### 🔧 Actions")
with gr.Row():
reset_btn = gr.Button("🔄 Reset", variant="secondary")
random_btn = gr.Button("🎲 Random", variant="secondary")
auto_btn = gr.Button("🤖 Auto-Arrange", variant="primary")
check_btn = gr.Button("✅ Check Solution", variant="primary")
message_output = gr.Textbox(label="📢 Message", lines=2)
with gr.Accordion("📊 Advanced", open=False):
with gr.Row():
with gr.Column():
gr.Markdown("### Export Configuration")
export_btn = gr.Button("📤 Export JSON")
json_output = gr.Textbox(label="JSON Output", lines=8)
with gr.Column():
gr.Markdown("### Import Configuration")
json_input = gr.Textbox(label="Paste JSON", lines=8)
import_btn = gr.Button("📥 Import JSON")
check_output = gr.Textbox(label="Check Result", lines=6)
# イベントハンドラ
coin_radius_slider.change(
update_display,
inputs=[coin_radius_slider, sector_radius_slider],
outputs=[image_output, status_output]
)
sector_radius_slider.change(
update_display,
inputs=[coin_radius_slider, sector_radius_slider],
outputs=[image_output, status_output]
)
# 画像クリック
image_output.select(
click_to_move,
outputs=[image_output, status_output, message_output]
)
# コイン選択
next_btn.click(select_next_coin, outputs=[image_output, status_output, message_output])
prev_btn.click(select_prev_coin, outputs=[image_output, status_output, message_output])
coin_num_input.change(select_coin_number, inputs=[coin_num_input], outputs=[image_output, status_output, message_output])
# 方向キー
up_btn.click(move_up, outputs=[image_output, status_output, message_output])
down_btn.click(move_down, outputs=[image_output, status_output, message_output])
left_btn.click(move_left, outputs=[image_output, status_output, message_output])
right_btn.click(move_right, outputs=[image_output, status_output, message_output])
# アクション
reset_btn.click(reset_positions, outputs=[image_output, status_output, message_output])
random_btn.click(randomize_positions, outputs=[image_output, status_output, message_output])
auto_btn.click(auto_arrange, outputs=[image_output, status_output, message_output])
check_btn.click(check_solution, outputs=[check_output])
# JSON操作
export_btn.click(export_json, outputs=[json_output])
import_btn.click(import_json, inputs=[json_input], outputs=[image_output, status_output, message_output])
# 初期表示
demo.load(lambda: update_display(0.5, 4.0), outputs=[image_output, status_output])
if __name__ == "__main__":
demo.launch() |