import random
from js import setTimeout, document

#定数の定義
GAME_TURNS = 30 #ゲーム終了までのターン数
INTERVAL = 1000 #モグラ出現間隔
WIDTH = 50 #モグラサイズ一片の長さ

#info要素の取得
info = document.getElementById("info")
#canvas取得
canvas = document.getElementById("canvas") #キャンバスを取得
context = canvas.getContext("2d") #2D描画コンテキスト取得

#ゲーム全体の流れを辞書型変数で管理
game = {
    "turns": GAME_TURNS,
    "score": 0, #スコア
    "mx": 0, #座標
    "my": 0, 
    "hide": True, #隠れてるかどうか
}

def next_turn():
    """次のターンの処理を行う関数"""
    #残りターン表示
    if game["turns"] <= 0:
        game_over()
        return
    game["turns"] -= 1 #残りターンを-1
    #モグラの状態を変更して描画
    update_mogura()
    update_screen()
    #次回タイマーをセット
    setTimeout(next_turn,INTERVAL)

def update_mogura():
    """モグラの状態を変更する関数"""
    #頭を出すか更新
    game["hide"] = not game["hide"]
    if not game["hide"]:
        #モグラの位置をランダムに決定する
        game["mx"] = random.randint(0, canvas.width -WIDTH)
        game["my"] = random.randint(0, canvas.height -WIDTH)

def update_screen():
    """ゲーム画面の更新処理"""
    #画面クリア
    context.clearRect(0, 0, canvas.width, canvas,height)
    #モグラを描画
    if not game["hide"]:
        context.fillStyle = "brown"
        context.fillRect(game["mx"], game["my"], WIDTH, WIDTH)
    #スコア更新
    info.innerText = (f"スコア {game['score']})点 /"
                      f"残り時間 {game['turns']}")
    def game_over():
        """ゲーム終了処理"""
        info.innerText = f"モグラ叩き終了: スコア {game['score']}点"
        # ゲーム開始ボタンを有効化
        document.getElementById("start_button").disabled = False
        