
【1215版】o1 vs o1 Pro vs Gemini-exp-1206
ご挨拶
ご覧いただき、ありがとうございます。AKと申します。
本記事では、2024年12月15日時点で「どの生成AIがゲーム開発に最も役立つか」を検証します。前回のテストで大きな差が見られたメンバーは除外し、今回は「GPT o1 Pro」「o1 Pro」「Gemini-exp-1206」の3モデルで再度チャレンジ!
本日も「ゲーム開発で生成AIを上手く活用できないかな?」とお悩みの方には、きっと有益な情報となるはずです。ぜひ最後までお楽しみください。
※前回記事は以下になります。
私のスキル感
普段は独学でコーディングを続けており、Godotを用いた開発経験はそこそこありますが、まだまだ試行錯誤の日々です。
私のスキル感を知っていただくため、以下に経歴を掲載しております。
学歴
・地方国立大 大学院卒 研究分野はAI関連
職業
・エンジニア2年目(元々は製造業→IT企業)
使用する生成AI
・ChatGPT、Claudeがメイン(だった)、Gemini
・GPT3.5が出てから、生成AIはほぼ親友に。会社でも独自の生成AI(モデルGPT4o)が使えるため、毎日AIを使用している状況。かなりノウハウは溜まっている。
検証方法
今回も、実際に開発中のゲームで直面している課題(特定の状態遷移に関連するバグ)と必要なコードを提示し、各生成AIが「どの程度迅速かつ正確に解決策を提示できるか」を比較します。つまり、単なる性能比較ではなく、実務的な問題解決力を重視したテストです。
理想的な挙動:
初期状態アクション1(移動)実施後
⇒状態1(移動完了)アクション2(待機ボタン押下)
⇒待機方向選択状態Zボタン押下1回目
⇒状態1へ戻るZボタン押下2回目
⇒初期状態へ戻る
現状の挙動:
初期状態アクション1(移動)実施後
⇒状態1(移動完了)アクション2(待機ボタン押下)
⇒待機方向選択状態Zボタン押下1回目
⇒状態1へ戻るZボタン押下2回目
⇒画面変化なしZボタン押下3回目⇒初期状態へ戻る

本来、Zボタンは直前の行動へ戻る機能を持たせています。しかし、待機ボタンを押した後、Zボタンを2回押すと元の位置へ戻るはずが、なぜか2回目の押下時には何も起こらず、3回目でようやく戻るというバグが発生中。
つまり、前回の状態取得が正しく行われず、2回目の「戻り」が無反応になる現象が確認されています。
実験開始
最初に投げるプロンプトは以下の通りです。
特に黒字だけでも読んで頂けると以降が分かりやすくなると思います。
現状の問題点を把握して解決策の認識合わせをしたいです。
ソースコードを分析のほどよろしくお願いいたします。
【現状の問題点】
・(理想)初期状態⇒アクション1 移動実施⇒状態1:移動完了⇒アクション2 待機ボタン押下⇒待機方向が選択できますよ状態⇒Zボタン押下⇒状態1:移動完了⇒2回目のZボタン押下⇒初期状態
・(現状)初期状態⇒アクション1 移動実施⇒状態1:移動完了⇒アクション2 待機ボタン押下⇒待機方向が選択できますよ状態⇒Zボタン押下⇒状態1:移動完了⇒2回目のZボタン押下⇒画面上変化なし⇒3回目のZボタン押下初期状態
・しかし、現状は2回目のZボタン押下では初期状態にならず、なぜか3回目のZボタン押下で初期状態に戻るようになってしまっている。
【バグ発生中ソース】
# grid_manager.gd
extends Node3D
class_name GridManager
const MovementRangeClass := preload("res://scripts/battle/movement_range.gd")
signal cell_selected(position: Vector2i)
signal cell_highlighted(position: Vector2i)
signal cell_unhighlighted(position: Vector2i)
signal turn_changed(team: int)
@onready var battle_ui: BattleUI = $"../BattleUI"
@export var grid_size: Vector2i = Vector2i(10, 10)
@export var cell_size: float = 1.0
enum Team { PLAYER = 0, ENEMY = 1 }
enum ActionType { ATTACK, MAGIC, WAIT }
# --- フィールド変数 ---
var attack_range: AttackRange
var movement_range: MovementRange
var turn_manager: TurnManager
var current_team: int = Team.PLAYER
var active_units: Dictionary = {
Team.PLAYER: [],
Team.ENEMY: []
}
var grid_data: Dictionary = {}
var visualization_node: Node3D
var selected_cell_indicator: MeshInstance3D = null
# ユニット関連
var units: Dictionary = {} # キー: Vector2i(位置), 値: Unit
var selected_unit: Unit = null
# 状態フラグ
var waiting_for_turn_end: bool = false
var selected_action: ActionType = ActionType.ATTACK
var waiting_for_direction: bool = false
var is_in_action: bool = false
# 状態保存用
var previous_state: Dictionary = {}
var selected_unit_previous_position: Vector2i = Vector2i(-1, -1)
var has_moved_previous_state: bool = false
var has_attacked_previous_state: bool = false
var has_acted_previous_state: bool = false
func _ready():
_initialize_grid()
_create_visualization()
_create_selection_indicator()
movement_range = MovementRangeClass.new()
movement_range.set_grid_manager(self)
add_child(movement_range)
attack_range = AttackRange.new()
attack_range.set_grid_manager(self)
add_child(attack_range)
turn_manager = TurnManager.new()
add_child(turn_manager)
_connect_turn_signals()
battle_ui.hide_action_buttons()
battle_ui.connect_action_buttons(self)
func _connect_turn_signals():
if not turn_manager.turn_changed.is_connected(_on_turn_changed):
turn_manager.turn_changed.connect(_on_turn_changed)
#==================================================
# 初期化系
#==================================================
func _initialize_grid():
for x in range(grid_size.x):
for y in range(grid_size.y):
var pos = Vector2i(x, y)
grid_data[pos] = CellData.new()
func _create_visualization():
visualization_node = Node3D.new()
add_child(visualization_node)
var material = StandardMaterial3D.new()
material.albedo_color = Color(0.8, 0.8, 0.8, 1.0)
var mesh = BoxMesh.new()
mesh.size = Vector3(cell_size * 0.9, 0.1, cell_size * 0.9)
mesh.surface_set_material(0, material)
for x in range(grid_size.x):
for y in range(grid_size.y):
_create_single_cell_visual(x, y, mesh)
func _create_single_cell_visual(x: int, y: int, mesh: BoxMesh):
var static_body = StaticBody3D.new()
var collision_shape = CollisionShape3D.new()
var box_shape = BoxShape3D.new()
box_shape.size = Vector3(cell_size * 0.9, 0.1, cell_size * 0.9)
collision_shape.shape = box_shape
var mesh_instance = MeshInstance3D.new()
mesh_instance.mesh = mesh
static_body.add_child(collision_shape)
static_body.add_child(mesh_instance)
static_body.position = grid_to_world(Vector2i(x, y))
visualization_node.add_child(static_body)
func _create_selection_indicator():
var material = StandardMaterial3D.new()
material.albedo_color = Color(1.0, 1.0, 0.0, 0.5)
material.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
var mesh = BoxMesh.new()
mesh.size = Vector3(cell_size * 0.95, 0.2, cell_size * 0.95)
mesh.surface_set_material(0, material)
selected_cell_indicator = MeshInstance3D.new()
selected_cell_indicator.mesh = mesh
selected_cell_indicator.visible = false
add_child(selected_cell_indicator)
#==================================================
# 入力処理
#==================================================
func _input(event):
if not turn_manager.is_player_turn():
return
if _handle_waiting_direction_input(event):
return
if _handle_key_z_input(event):
return
if _handle_key_space_input(event):
return
if _handle_mouse_left_click(event):
return
func _handle_waiting_direction_input(event) -> bool:
if waiting_for_direction and selected_unit and event is InputEventKey and event.pressed:
match event.keycode:
KEY_UP:
selected_unit.set_direction(Vector2i.UP)
KEY_DOWN:
selected_unit.set_direction(Vector2i.DOWN)
KEY_LEFT:
selected_unit.set_direction(Vector2i.RIGHT)
KEY_RIGHT:
selected_unit.set_direction(Vector2i.LEFT)
KEY_SPACE:
_finish_current_action()
return true
KEY_Z:
waiting_for_direction = false
battle_ui.show_action_buttons()
# ★ここでは敢えてsave_state()しない
# 理由:Zで戻った後にさらに戻る状態を増やさないため
return true
return false
func _handle_key_z_input(event) -> bool:
if event is InputEventKey and event.pressed and event.keycode == KEY_Z:
if is_in_action:
# 状態復元
restore_state()
is_in_action = false
# 状態復元後に攻撃選択中であれば攻撃範囲をクリア
if selected_action == ActionType.ATTACK:
cancel_attack() # 攻撃範囲非表示と3択表示を行う
else:
# 攻撃中でない場合は本来の再表示処理
_redisplay_ranges_after_restore()
return true
elif selected_unit:
# まずユニットが移動済みかチェックして、移動キャンセルを優先する
if selected_unit.has_moved:
cancel_movement()
# キャンセル直後はsave_state()を行わない
# 必要に応じて次の行動開始時にsave_state()
return true
# それ以外に攻撃アクション中なら攻撃キャンセル
elif selected_action == ActionType.ATTACK:
cancel_attack()
# 攻撃キャンセル直後はsave_state()せず、次の行動時に保存
return true
return false
func _redisplay_ranges_after_restore():
if not selected_unit:
return
var movement_cells = [] # ここで変数を宣言しておく
if not selected_unit.has_moved:
movement_cells = movement_range.calculate_movement_range(selected_unit)
movement_range.show_movement_range(selected_unit)
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(selected_unit, movement_cells)
elif selected_unit.has_moved and not selected_unit.has_attacked:
# ここではmovement_cells不要なら宣言不要
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(selected_unit)
func _handle_key_space_input(event) -> bool:
if event is InputEventKey and event.pressed and event.keycode == KEY_SPACE:
if waiting_for_turn_end:
_finish_turn()
# ターン終了後は現状が新たな基準点
save_state()
return true
elif selected_unit:
select_action(ActionType.WAIT)
return true
return false
func _handle_mouse_left_click(event) -> bool:
if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
var camera = get_viewport().get_camera_3d()
if camera:
var from = camera.project_ray_origin(event.position)
var to = from + camera.project_ray_normal(event.position) * 1000.0
var space_state = get_world_3d().direct_space_state
var query = PhysicsRayQueryParameters3D.create(from, to)
var result = space_state.intersect_ray(query)
if result:
var grid_pos = world_to_grid(result.position)
if is_valid_position(grid_pos):
_select_cell(grid_pos)
# セル選択後、この状態を新たな基準点として保存
save_state()
return true
return false
#==================================================
# ターン終了処理
#==================================================
func _finish_turn():
waiting_for_turn_end = false
battle_ui.hide_turn_end_button()
turn_manager.end_turn()
# ターン終了後の状態を基準点として再保存
save_state()
#==================================================
# 行動終了処理
#==================================================
func _finish_current_action():
if not selected_unit:
return
if waiting_for_direction:
_finish_wait_action()
else:
_finish_generic_action()
func _finish_wait_action():
waiting_for_direction = false
selected_unit.end_action()
selected_unit = null
_clear_ranges()
waiting_for_turn_end = true
battle_ui.show_turn_end_button()
# 待機完了後、この状態を基準点として再保存
save_state()
func _finish_generic_action():
selected_unit.end_action()
selected_unit = null
_clear_ranges()
waiting_for_turn_end = true
battle_ui.show_turn_end_button()
battle_ui.hide_action_buttons()
# アクション完了後、この状態を基準点として再保存
save_state()
func _clear_ranges():
movement_range.clear_range_display()
attack_range.clear_range_display()
#==================================================
# ユニット移動・アクション選択
#==================================================
func execute_movement(unit: Unit, target_pos: Vector2i):
_store_pre_movement_state(unit) # 移動前の状態を保存
if await move_unit(unit, target_pos):
unit.has_moved = true
_clear_ranges()
battle_ui.show_unit_info(unit)
if not unit.has_attacked:
battle_ui.show_action_buttons()
selected_action = ActionType.ATTACK
else:
_auto_end_turn_after_movement()
# 移動確定後この状態を記録
save_state()
# ここで行動完了とし、is_in_actionをfalseに
is_in_action = false
func _store_pre_movement_state(unit: Unit):
is_in_action = true
selected_unit_previous_position = unit.grid_position
has_moved_previous_state = unit.has_moved
has_attacked_previous_state = unit.has_attacked
has_acted_previous_state = unit.has_acted
func _auto_end_turn_after_movement():
selected_unit.end_action()
selected_unit = null
battle_ui.hide_unit_info()
turn_manager.end_turn()
battle_ui.hide_action_buttons()
# ターン終了直後にsave_state()はend_turn内で呼んでいるので追加は不要
func select_action(action_type: ActionType):
selected_action = action_type
is_in_action = true
save_state()
match selected_action:
ActionType.ATTACK:
battle_ui.hide_action_buttons()
if selected_unit:
# 攻撃モードのみ攻撃範囲表示
attack_range.show_attack_range(selected_unit)
ActionType.MAGIC:
_finish_current_action()
ActionType.WAIT:
battle_ui.hide_action_buttons()
waiting_for_direction = true # 向き選択モード
#==================================================
# ターン変更処理
#==================================================
func _on_turn_changed(_team: int):
selected_unit = null
_clear_ranges()
battle_ui.hide_action_buttons()
if not turn_manager.is_player_turn():
execute_enemy_turn()
# ターン開始後の状態を基準点として再保存
save_state()
#==================================================
# 敵ターン・AI関連
#==================================================
func execute_enemy_turn():
print("Execute enemy turn started")
print("Enemy units: ", turn_manager.active_units[TurnManager.Team.ENEMY].size())
for unit in turn_manager.active_units[TurnManager.Team.ENEMY]:
if not unit.has_acted:
_enemy_act(unit)
print("Enemy turn complete")
turn_manager.end_turn()
# 敵ターン終了後はend_turn()でsave_state()される
func _enemy_act(enemy_unit: Unit):
print("Enemy unit acting")
var target_pos = find_closest_player_unit_position(enemy_unit)
if target_pos != Vector2i(-1, -1):
_enemy_try_attack_or_move(enemy_unit, target_pos)
enemy_unit.end_action()
_clear_ranges()
battle_ui.hide_action_buttons()
func _enemy_try_attack_or_move(enemy_unit: Unit, target_pos: Vector2i):
var attack_cells = attack_range.calculate_attack_range(enemy_unit)
var can_attack = false
var target_unit = null
for attack_pos in attack_cells:
target_unit = get_unit_at(attack_pos)
if target_unit and target_unit.team == TurnManager.Team.PLAYER:
can_attack = true
break
if can_attack and target_unit:
enemy_unit.perform_attack(target_unit)
else:
# 移動して攻撃
var move_pos = calculate_movement_toward_target(enemy_unit, target_pos)
if await move_unit(enemy_unit, move_pos):
attack_cells = attack_range.calculate_attack_range(enemy_unit)
for attack_pos in attack_cells:
target_unit = get_unit_at(attack_pos)
if target_unit and target_unit.team == TurnManager.Team.PLAYER:
enemy_unit.perform_attack(target_unit)
break
func find_closest_player_unit_position(enemy_unit: Unit) -> Vector2i:
var closest_distance = 999
var closest_pos = Vector2i(-1, -1)
for unit in turn_manager.active_units[TurnManager.Team.PLAYER]:
var distance = calculate_grid_distance(enemy_unit.grid_position, unit.grid_position)
if distance < closest_distance:
closest_distance = distance
closest_pos = unit.grid_position
print("Found player unit at: ", closest_pos, " distance: ", closest_distance)
return closest_pos
#==================================================
# Utility系(計算系)
#==================================================
func calculate_grid_distance(from: Vector2i, to: Vector2i) -> int:
return abs(from.x - to.x) + abs(from.y - to.y)
func calculate_movement_toward_target(unit: Unit, target_pos: Vector2i) -> Vector2i:
var possible_moves = movement_range.calculate_movement_range(unit)
var best_move = unit.grid_position
var best_distance = 999
print("Calculating movement toward: ", target_pos)
print("Possible moves from movement range: ", possible_moves)
for move in possible_moves:
var distance = calculate_grid_distance(move, target_pos)
if distance < best_distance:
best_distance = distance
best_move = move
print("Found better move: ", best_move, " distance: ", best_distance)
return best_move
func calculate_attack_position(attacker: Unit, target_pos: Vector2i) -> Vector2i:
var target_unit = get_unit_at(target_pos)
if not target_unit:
return attacker.grid_position
var possible_positions = []
var directions = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
for dir in directions:
var pos = target_pos + dir
if is_valid_position(pos) and pos in movement_range._current_range:
possible_positions.append(pos)
var best_pos = attacker.grid_position
var best_distance = 999
for pos in possible_positions:
var distance = calculate_grid_distance(attacker.grid_position, pos)
if distance < best_distance:
best_distance = distance
best_pos = pos
return best_pos
#==================================================
# グリッド・ユニット管理系
#==================================================
func is_valid_position(pos: Vector2i) -> bool:
return pos.x >= 0 and pos.x < grid_size.x and pos.y >= 0 and pos.y < grid_size.y
func get_cell_data(pos: Vector2i) -> CellData:
return grid_data.get(pos)
func world_to_grid(world_pos: Vector3) -> Vector2i:
return Vector2i(int(world_pos.x / cell_size), int(world_pos.z / cell_size))
func grid_to_world(grid_pos: Vector2i) -> Vector3:
return Vector3(grid_pos.x * cell_size, 0, grid_pos.y * cell_size)
func place_unit(unit: Unit, pos: Vector2i) -> bool:
if not is_valid_position(pos) or has_unit_at(pos):
return false
_remove_unit_from_old_pos_if_needed(unit)
units[pos] = unit
unit.grid_position = pos
unit.position = grid_to_world(pos)
return true
func _remove_unit_from_old_pos_if_needed(unit: Unit):
if units.has(unit):
var old_pos = units.find_key(unit)
units.erase(old_pos)
func get_unit_at(pos: Vector2i) -> Unit:
return units.get(pos)
func has_unit_at(pos: Vector2i) -> bool:
return units.has(pos)
func move_unit(unit: Unit, new_pos: Vector2i) -> bool:
if not is_valid_position(new_pos) or has_unit_at(new_pos):
return false
var old_pos = unit.grid_position
units.erase(old_pos)
await unit.move_to_grid(new_pos)
if place_unit(unit, new_pos):
unit.unit_moved.emit(old_pos, new_pos)
return true
return false
#==================================================
# セル選択・行動処理
#==================================================
func _select_cell(grid_pos: Vector2i):
if not is_valid_position(grid_pos) or not turn_manager.is_player_turn():
battle_ui.hide_unit_info()
return
var target_unit = get_unit_at(grid_pos)
_update_ui_for_target_unit(target_unit)
if selected_unit:
if await _attempt_attack_if_possible(target_unit, grid_pos):
# 攻撃実行後の状態を基準点として再保存
save_state()
return
if _attempt_move_if_in_range(grid_pos):
# 移動後の状態を基準点として再保存はexecute_movement内で行う
return
if target_unit and target_unit.team == Team.PLAYER and not target_unit.has_acted:
_select_new_unit(target_unit)
# ユニット選択後の状態を再保存
save_state()
selected_cell_indicator.visible = true
selected_cell_indicator.position = grid_to_world(grid_pos)
cell_selected.emit(grid_pos)
func _update_ui_for_target_unit(target_unit: Unit):
if target_unit:
battle_ui.show_unit_info(target_unit)
else:
battle_ui.hide_unit_info()
func _attempt_attack_if_possible(target_unit: Unit, grid_pos: Vector2i) -> bool:
if selected_unit and target_unit and target_unit.team != selected_unit.team and attack_range.is_in_attack_range(grid_pos):
# 近接攻撃用に移動
if grid_pos in movement_range._current_range:
var attack_pos = calculate_attack_position(selected_unit, grid_pos)
if attack_pos != selected_unit.grid_position:
await execute_movement(selected_unit, attack_pos)
if selected_action == ActionType.ATTACK:
_execute_attack(target_unit)
return true
return false
func _execute_attack(target_unit: Unit):
is_in_action = false
selected_unit.perform_attack(target_unit)
selected_unit.has_attacked = true
_clear_ranges()
selected_unit.end_action()
selected_unit = null
battle_ui.hide_unit_info()
waiting_for_turn_end = true
battle_ui.show_turn_end_button()
battle_ui.hide_action_buttons()
# 攻撃終了後、この状態を基準点として再保存
save_state()
func _attempt_move_if_in_range(grid_pos: Vector2i) -> bool:
if selected_unit and movement_range.is_cell_in_range(grid_pos):
is_in_action = true
save_state()
execute_movement(selected_unit, grid_pos)
# execute_movement内で移動完了後save_state()を行うのでここは不要
return true
return false
func _select_new_unit(target_unit: Unit):
selected_unit = target_unit
is_in_action = false
if not target_unit.has_moved:
var movement_cells = movement_range.calculate_movement_range(target_unit)
movement_range.show_movement_range(target_unit)
# ATTACKアクション中のみ攻撃範囲を表示
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(target_unit, movement_cells)
elif not target_unit.has_attacked:
# ATTACKアクション中のみ攻撃範囲表示
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(target_unit)
#==================================================
# 状態保存・復元系
#==================================================
func save_state():
previous_state = {
"selected_unit": selected_unit,
"selected_unit_position": selected_unit.grid_position if selected_unit else null,
"has_moved": selected_unit.has_moved if selected_unit else false,
"has_attacked": selected_unit.has_attacked if selected_unit else false,
"has_acted": selected_unit.has_acted if selected_unit else false,
"waiting_for_direction": waiting_for_direction,
"waiting_for_turn_end": waiting_for_turn_end,
"selected_action": selected_action,
"action_buttons_visible": battle_ui.are_action_buttons_visible()
}
func restore_state():
if previous_state.is_empty():
return
if previous_state.selected_unit:
_restore_selected_unit_state()
waiting_for_direction = previous_state.waiting_for_direction
waiting_for_turn_end = previous_state.waiting_for_turn_end
selected_action = previous_state.selected_action
if previous_state.action_buttons_visible:
battle_ui.show_action_buttons()
else:
battle_ui.hide_action_buttons()
previous_state.clear()
_re_show_ranges_based_on_state()
# ★復元直後のsave_state()は削除
# 状態を戻した後に即再保存せず、「もう一段戻りたい」ときに必要以上にZキーを押す必要がないようにする。
func _restore_selected_unit_state():
selected_unit = previous_state.selected_unit
selected_unit.has_moved = previous_state.has_moved
selected_unit.has_attacked = previous_state.has_attacked
selected_unit.has_acted = previous_state.has_acted
if previous_state.selected_unit_position:
units.erase(selected_unit.grid_position)
selected_unit.position = grid_to_world(previous_state.selected_unit_position)
selected_unit.grid_position = previous_state.selected_unit_position
units[selected_unit.grid_position] = selected_unit
func _re_show_ranges_based_on_state():
if selected_unit:
# 攻撃アクション以外では攻撃範囲を表示しない
var show_attack = (selected_action == ActionType.ATTACK)
var movement_cells = []
if not selected_unit.has_moved:
movement_cells = movement_range.calculate_movement_range(selected_unit)
movement_range.show_movement_range(selected_unit)
if show_attack:
attack_range.show_attack_range(selected_unit, movement_cells)
elif selected_unit.has_moved and not selected_unit.has_attacked:
if show_attack:
attack_range.show_attack_range(selected_unit)
#==================================================
# キャンセル系
#==================================================
func cancel_movement():
if selected_unit and selected_unit_previous_position != Vector2i(-1, -1):
units.erase(selected_unit.grid_position)
selected_unit.position = grid_to_world(selected_unit_previous_position)
selected_unit.grid_position = selected_unit_previous_position
units[selected_unit.grid_position] = selected_unit
selected_unit.has_moved = has_moved_previous_state
selected_unit.has_attacked = has_attacked_previous_state
selected_unit.has_acted = has_acted_previous_state
selected_unit_previous_position = Vector2i(-1, -1)
_clear_ranges()
_re_show_ranges_after_cancel()
battle_ui.hide_action_buttons()
battle_ui.hide_unit_info()
func _re_show_ranges_after_cancel():
if selected_unit:
var show_attack = (selected_action == ActionType.ATTACK)
if not selected_unit.has_moved:
var movement_cells = movement_range.calculate_movement_range(selected_unit)
movement_range.show_movement_range(selected_unit)
if show_attack:
attack_range.show_attack_range(selected_unit, movement_cells)
elif selected_unit.has_moved and not selected_unit.has_attacked:
if show_attack:
attack_range.show_attack_range(selected_unit)
func cancel_attack():
attack_range.clear_range_display()
battle_ui.show_action_buttons()
# 攻撃キャンセル直後もsave_state()はしない
# 次の行動開始時にsave_state()する
func remove_unit(unit: Unit):
if unit.team in active_units:
active_units[unit.team].erase(unit)
if check_game_end():
print("Game has ended!")
func check_game_end() -> bool:
if active_units[Team.PLAYER].is_empty():
return true
if active_units[Team.ENEMY].is_empty():
return true
return false
func register_unit(unit: Unit):
if unit.team in active_units:
active_units[unit.team].append(unit)
func start_game():
print("================")
print("Turn 1 - Player's turn START")
print("Active units for current team: ", active_units[current_team].size())
_start_turn()
func _start_turn():
for unit in active_units[current_team]:
unit.reset_actions()
turn_changed.emit(current_team)
# ターン開始時点で状態を保存
save_state()
func end_turn():
print("Current turn ending check...")
for unit in active_units[current_team]:
if not unit.has_acted:
print("Turn cannot end - ", active_units[current_team].size(), " units haven't acted yet")
return
print(get_team_name(current_team), "'s turn END")
print("================")
current_team = Team.ENEMY if current_team == Team.PLAYER else Team.PLAYER
print("================")
print("Turn 1 - ", get_team_name(current_team), "'s turn START")
print("Active units for current team: ", active_units[current_team].size())
_start_turn()
# ターン終了後、_start_turn()で再度save_state()されるため、ここでは不要
func get_team_name(team: int) -> String:
return "Player" if team == Team.PLAYER else "Enemy"
func is_player_turn() -> bool:
return current_team == Team.PLAYER
func get_remaining_enemies() -> int:
return active_units[Team.ENEMY].size()
func end_game(is_player_victory: bool):
print("Game Over - " + ("Player Wins!" if is_player_victory else "Enemy Wins!"))
if battle_ui:
battle_ui.show_game_end_message(is_player_victory)
turn_manager.end_game()
※ギュギュっとまとめると、上記のプロンプトは以下の3つを実施しています。
①現状の問題点を正しく認識してもらう。
②ソースコードを提供する
③方向性の認識合わせをする。
つぎにその結果です。
順番はGPT o1 、o1 Pro 、Gemini-exp-1206です。
エントリーNo1:o1
まずは完全体となったo1の回答になります。
方向性の認識合わせをしています。
それっぽい内容は回答してくれました。
続いて上記を基に実装を依頼した結果が以下になります。
以下に現状の問題点および原因の考察、そして改善策の提案を示します。
問題の概要
理想的な挙動:初期状態
アクション1(移動)実施後⇒状態1(移動完了)
アクション2(待機ボタン押下)⇒待機方向選択状態
Zボタン押下1回目⇒状態1へ戻る
Zボタン押下2回目⇒初期状態へ戻る
現状の挙動:初期状態
アクション1(移動)実施後⇒状態1(移動完了)
アクション2(待機ボタン押下)⇒待機方向選択状態
Zボタン押下1回目⇒状態1へ戻る
Zボタン押下2回目⇒画面変化なし
Zボタン押下3回目⇒初期状態へ戻る
つまり、本来2回目のZ押下で初期状態へ戻りたいところが、現行のコードでは3回目のZ押下でようやく初期状態へ戻っている。
原因の考察
1. restore_state()後にprevious_stateをクリアしている問題
restore_state()関数内でprevious_state.clear()が呼ばれています。そのため、1回目のZ押下でrestore_state()を実行した後、previous_stateは空になり、2回目以降のZ押下で戻れる状態がなくなってしまいます。
本来、「Zボタンによる戻し」を複数段階行いたいのであれば、previous_stateをクリアせず、戻した後の状態を再度save_state()する必要があります。しかし、現在のコードではrestore_state()後に即save_state()を行わない方針が明記されており、その結果、2回目のZ押下時には状態が存在せず戻せないため、画面上の変化が起きません。
2. is_in_actionフラグやselected_unitの状態による分岐
_handle_key_z_input()内を見ると、Z押下時は以下のような条件分岐があります。if is_in_action: restore_state()を行いis_in_action = falseに戻す処理
そうでない場合、if selected_unit:
if selected_unit.has_moved: cancel_movement()
elif selected_action == ActionType.ATTACK: cancel_attack()
1回目のZ押下でrestore_state()をした後、is_in_actionはfalseになります。また、previous_stateがクリアされるので2回目のZ押下時点では戻せる状態がなく、かつselected_unitやselected_actionの状態によってはcancel_movement()やcancel_attack()が発火しない場合、その結果、何も起きない(画面変化なし)状態になります。
根本的な原因restore_state()後にprevious_stateがクリアされ、かつ再度save_state()されないため、2回目のZ押下で戻すための履歴がない。
状態復元後の分岐条件(is_in_actionやselected_unit)が次のZ押下で想定した状態フローに合わず、何も起こらない状態が発生している。
改善案restore_state()直後のsave_state()再実行
restore_state()実行後、すぐにsave_state()を行うことで、2回目のZ押下で更に一段階前に戻せるようにする。
デメリット: 戻り操作(Zキー)を行うたびにsave_state()で新たな状態を記録するため、無限ループ的な戻しができる危険性がある。
対策案: 戻し時はsave_state()するが、フラグを用いて「戻し操作直後に再び戻しが可能」かをコントロールするなどの工夫が必要。
previous_stateの扱いを見直す
restore_state()内でprevious_state.clear()を行わず、直前の状態を保持する。または、スタック形式で状態を管理し、Z押下するたびにポップする形にする。これにより、複数段階の取り消しが可能になる。
is_in_actionやselected_unitなどの状態管理ロジックを整理
Z押下時に何を戻すか、どの状態まで戻したいかを明確にし、restore_state()の呼び出し前後で必ずselected_unitやselected_actionなどの状態が整合性を保つようにする。
状態遷移図の整理
アクション開始、アクション終了、Z押下戻し処理、キャンセル処理などで、状態機械(ステートマシン)的な図を作成してロジックを明確化すると、どの段階でどの状態を保存・復元すべきかが明らかになる。
まとめ現状2回目のZ押下で初期状態に戻らず、3回目でようやく戻る原因は、restore_state()後にprevious_stateがクリアされ、状態保存が行われないため、2回目のZ押下で復元する情報がなくなっていることが主因です。
restore_state()後にsave_state()を行う、またはprevious_stateをクリアしない、もしくは状態管理フローを再検討するといったアプローチで問題解決が可能となります。
読んで頂けると分かるのですが、たしかに認識合わせとしてはまずまずいい線行ってるかな?というところ。
この時点では60点ぐらいの回答になります。
以降は具体的な修正コードをもらって実装を繰り返しながら進めていきます。
以下、コードの実装内容になります。
以下は、原因分析と提案を踏まえてコードに修正・ログ出力を追加した例です。主な修正点は以下の通りです。restore_state()後にprevious_state.clear()を行わないように変更
restore_state()後にsave_state()を行うように変更(複数段階の戻しが可能になる)
save_state()やrestore_state()、Zキー押下時の処理箇所などにprintログを追加し、状態遷移がわかりやすいようにする
戻し操作連続時に無限ループ的な戻しが発生しないように、restore_state()後に再保存する前に必要であれば追加の制御を検討可能(ここでは簡易的な実装に留める)
※ 下記コードは、ユーザー提供コードの該当箇所のみ修正例を示します。他の部分は基本的にユーザー提供のままです。
#================================================== # 状態保存・復元系 #================================================== func save_state(): print("[LOG] save_state() called") print("[LOG] Current selected_unit:", selected_unit, " position:", selected_unit.grid_position if selected_unit else "None", " has_moved:", selected_unit.has_moved if selected_unit else "N/A", " has_attacked:", selected_unit.has_attacked if selected_unit else "N/A", " selected_action:", selected_action, " waiting_for_direction:", waiting_for_direction, " waiting_for_turn_end:", waiting_for_turn_end) previous_state = { "selected_unit": selected_unit, "selected_unit_position": selected_unit.grid_position if selected_unit else null, "has_moved": selected_unit.has_moved if selected_unit else false, "has_attacked": selected_unit.has_attacked if selected_unit else false, "has_acted": selected_unit.has_acted if selected_unit else false, "waiting_for_direction": waiting_for_direction, "waiting_for_turn_end": waiting_for_turn_end, "selected_action": selected_action, "action_buttons_visible": battle_ui.are_action_buttons_visible() } print("[LOG] save_state() completed\n") func restore_state(): print("[LOG] restore_state() called") if previous_state.is_empty(): print("[LOG] No previous_state to restore.") return if previous_state.selected_unit: _restore_selected_unit_state() waiting_for_direction = previous_state.waiting_for_direction waiting_for_turn_end = previous_state.waiting_for_turn_end selected_action = previous_state.selected_action if previous_state.action_buttons_visible: battle_ui.show_action_buttons() else: battle_ui.hide_action_buttons() # 本来はclearしていたが、戻し操作を多段階で可能にするためクリアしない # previous_state.clear() _re_show_ranges_based_on_state() # ★復元直後にsave_state()を行い、次のZ押下でさらに戻せるようにする # これにより、2回目のZ押下でも一段階前の状態に戻せる。 save_state() print("[LOG] restore_state() completed and state re-saved.\n") func _handle_key_z_input(event) -> bool: if event is InputEventKey and event.pressed and event.keycode == KEY_Z: print("[LOG] Z key pressed") print("[LOG] Before handling Z, is_in_action:", is_in_action, " selected_unit:", selected_unit, " selected_action:", selected_action) if is_in_action: print("[LOG] Z pressed during is_in_action: Attempting to restore state.") restore_state() is_in_action = false if selected_action == ActionType.ATTACK: cancel_attack() else: _redisplay_ranges_after_restore() print("[LOG] Z handling (is_in_action) completed.\n") return true elif selected_unit: # 移動キャンセル優先 if selected_unit.has_moved: print("[LOG] Z pressed: selected_unit has moved, cancel_movement.") cancel_movement() print("[LOG] Movement cancelled.\n") return true # 攻撃アクション中なら攻撃キャンセル elif selected_action == ActionType.ATTACK: print("[LOG] Z pressed: selected_unit not moved but attack in action, cancel_attack.") cancel_attack() print("[LOG] Attack cancelled.\n") return true print("[LOG] Z pressed: No action taken.\n") return false
修正内容解説restore_state()でprevious_state.clear()を削除
これにより、一度戻した後もprevious_stateの情報は保持されます。
restore_state()後にsave_state()実行
状態を戻した直後に再度save_state()を行うことで、戻し操作を多段階にできます。この変更により、2回目のZ押下で初期状態(さらに前の状態)に戻すことが可能になります。
ログ追加 (print)
save_state()やrestore_state()など、状態管理に関する関数・分岐にログを追加。これにより、デバッグ時に状態がどのように変化しているかを把握しやすくします。
Zキー押下ハンドリング部にログ追加
Zキー押下前後のis_in_actionやselected_unit、selected_actionの状態を出力。どのルートを通ったかが分かりやすくなります。
この修正により、1回目のZ押下でrestore_state()が呼ばれた後、状態はprevious_stateを維持したままsave_state()し直すため、2回目のZ押下時にもrestore_state()が有効に機能し、理想挙動に近づきます。
しかし、ダメでしたので以降はデバックログとソースコードを提供しながら何度か再検討を繰り返してもらいます。
しかし、、、、
最終的に迷走してしまったのでo1脱落です。(笑)
感想ですが、o1は以下の画像のようにどこに追加したらええねん!が分からない箇所が散見されましたのでこの辺りからも評価は下がります。

さらに、コード修正の際になぜか「~の例」のように少し逃げている印象も非常にポイントダウンでした。
もちろんこれで治ればいいのですがバグは結果として解消されなかったのでますます悪く見えたというところです。


悔しい。。ただ、まだ我らが本命のo1 Proが残っています。
こちらを試していきましょう!
エントリーNo2:o1 Pro
さて、3万円の力をみせつけるときが来ました。
o1 Proの登場です。早速回答を見ていきましょう。
以下は、restore_state()終了時にsave_state()を行うようにし、加えてログを追加した修正例です。変更部分には# 変更箇所コメントを付与しています。
func restore_state(): if previous_state.is_empty(): print("[DEBUG] restore_state(): previous_state is empty, no state to restore.") # 変更箇所(ログ追加) return print("[DEBUG] restore_state(): Restoring state...") # 変更箇所(ログ追加) if previous_state.selected_unit: _restore_selected_unit_state() print("[DEBUG] restore_state(): Selected unit restored:", previous_state.selected_unit) # 変更箇所(ログ追加) waiting_for_direction = previous_state.waiting_for_direction waiting_for_turn_end = previous_state.waiting_for_turn_end selected_action = previous_state.selected_action print("[DEBUG] restore_state(): waiting_for_direction =", waiting_for_direction, ", waiting_for_turn_end =", waiting_for_turn_end, ", selected_action =", selected_action) # 変更箇所(ログ追加) if previous_state.action_buttons_visible: battle_ui.show_action_buttons() print("[DEBUG] restore_state(): Action buttons visible") # 変更箇所(ログ追加) else: battle_ui.hide_action_buttons() print("[DEBUG] restore_state(): Action buttons hidden") # 変更箇所(ログ追加) previous_state.clear() print("[DEBUG] restore_state(): previous_state cleared") # 変更箇所(ログ追加) _re_show_ranges_based_on_state() print("[DEBUG] restore_state(): Re-showing ranges based on restored state") # 変更箇所(ログ追加) # 復元後、状態を新たな基準点として保存 save_state() print("[DEBUG] restore_state(): State saved after restore.") # 変更箇所(ログ追加)
また、_handle_key_z_input内でrestore_state()後のフローが分かるように簡易的なログを追加します。
func _handle_key_z_input(event) -> bool: if event is InputEventKey and event.pressed and event.keycode == KEY_Z: print("[DEBUG] _handle_key_z_input(): Z key pressed") # 変更箇所(ログ追加) if is_in_action: print("[DEBUG] _handle_key_z_input(): Currently in action, restoring state...") # 変更箇所(ログ追加) restore_state() is_in_action = false if selected_action == ActionType.ATTACK: print("[DEBUG] _handle_key_z_input(): After restore, canceling attack (was in attack action)") # 変更箇所(ログ追加) cancel_attack() else: print("[DEBUG] _handle_key_z_input(): After restore, redisplaying ranges (not in attack)") # 変更箇所(ログ追加) _redisplay_ranges_after_restore() return true elif selected_unit: print("[DEBUG] _handle_key_z_input(): There is a selected unit. Checking if it has moved.") # 変更箇所(ログ追加) if selected_unit.has_moved: print("[DEBUG] _handle_key_z_input(): Unit has moved. Canceling movement.") # 変更箇所(ログ追加) cancel_movement() return true elif selected_action == ActionType.ATTACK: print("[DEBUG] _handle_key_z_input(): In attack action, canceling attack.") # 変更箇所(ログ追加) cancel_attack() return true return false
上記の修正によって、restore_state()後に必ずsave_state()が行われ、次回Z押下時に正しい状態戻りが行われるようになります。また、ログ出力によって状態復元やキャンセル処理時の流れがわかりやすくなります。
おや。。。。
ぱっと見o1とほぼ同じ回答に見えます。
とはいえ、どこかできっと違うはずなので修正コードを依頼すると以下の回答を頂けました。
以下は、restore_state()終了時にsave_state()を行うようにし、加えてログを追加した修正例です。変更部分には# 変更箇所コメントを付与しています。
func restore_state(): if previous_state.is_empty(): print("[DEBUG] restore_state(): previous_state is empty, no state to restore.") # 変更箇所(ログ追加) return print("[DEBUG] restore_state(): Restoring state...") # 変更箇所(ログ追加) if previous_state.selected_unit: _restore_selected_unit_state() print("[DEBUG] restore_state(): Selected unit restored:", previous_state.selected_unit) # 変更箇所(ログ追加) waiting_for_direction = previous_state.waiting_for_direction waiting_for_turn_end = previous_state.waiting_for_turn_end selected_action = previous_state.selected_action print("[DEBUG] restore_state(): waiting_for_direction =", waiting_for_direction, ", waiting_for_turn_end =", waiting_for_turn_end, ", selected_action =", selected_action) # 変更箇所(ログ追加) if previous_state.action_buttons_visible: battle_ui.show_action_buttons() print("[DEBUG] restore_state(): Action buttons visible") # 変更箇所(ログ追加) else: battle_ui.hide_action_buttons() print("[DEBUG] restore_state(): Action buttons hidden") # 変更箇所(ログ追加) previous_state.clear() print("[DEBUG] restore_state(): previous_state cleared") # 変更箇所(ログ追加) _re_show_ranges_based_on_state() print("[DEBUG] restore_state(): Re-showing ranges based on restored state") # 変更箇所(ログ追加) # 復元後、状態を新たな基準点として保存 save_state() print("[DEBUG] restore_state(): State saved after restore.") # 変更箇所(ログ追加)
また、_handle_key_z_input内でrestore_state()後のフローが分かるように簡易的なログを追加します。
func _handle_key_z_input(event) -> bool: if event is InputEventKey and event.pressed and event.keycode == KEY_Z: print("[DEBUG] _handle_key_z_input(): Z key pressed") # 変更箇所(ログ追加) if is_in_action: print("[DEBUG] _handle_key_z_input(): Currently in action, restoring state...") # 変更箇所(ログ追加) restore_state() is_in_action = false if selected_action == ActionType.ATTACK: print("[DEBUG] _handle_key_z_input(): After restore, canceling attack (was in attack action)") # 変更箇所(ログ追加) cancel_attack() else: print("[DEBUG] _handle_key_z_input(): After restore, redisplaying ranges (not in attack)") # 変更箇所(ログ追加) _redisplay_ranges_after_restore() return true elif selected_unit: print("[DEBUG] _handle_key_z_input(): There is a selected unit. Checking if it has moved.") # 変更箇所(ログ追加) if selected_unit.has_moved: print("[DEBUG] _handle_key_z_input(): Unit has moved. Canceling movement.") # 変更箇所(ログ追加) cancel_movement() return true elif selected_action == ActionType.ATTACK: print("[DEBUG] _handle_key_z_input(): In attack action, canceling attack.") # 変更箇所(ログ追加) cancel_attack() return true return false
上記の修正によって、restore_state()後に必ずsave_state()が行われ、次回Z押下時に正しい状態戻りが行われるようになります。また、ログ出力によって状態復元やキャンセル処理時の流れがわかりやすくなります。
コード修正にはかなり時間がかかったようですが、o1のように「例」がついていないので期待大です。


ただ、回答が非常にo1と酷似していたので念のためWinmergeで確認したところ一応異なっていました。まずは一安心です。
※winmergeは差分が黄色になるツールです。最強なのでぜひインストールしてみてください。

さて、これでは解消されなかったのでo1同様にデバックログを共有しながら修正活動を続けます。
以下は、現在のログとコードからわかったことと、次のステップとなるデバッグ方針です。
現状整理
期待する動き初期状態
アクション1(移動) ⇒ 状態1(移動完了)
アクション2(待機ボタン押下) ⇒ 待機方向選択状態
Zボタン押下 ⇒ 状態1(移動完了)へ戻る
2回目のZボタン押下 ⇒ 初期状態へ戻る
現在の動作1回目のZ押下でrestore_state()が呼ばれ、期待通り状態1に戻っている。(ログ上はここでrestore_state()成功)
しかし、2回目のZ押下時に画面上変化なし ⇒ 3回目のZ押下で初期状態へ
ログから確認すると、restore_state()呼び出し後に再度save_state()を行っており、「戻した後の状態」を新たな基準点として保存してしまっています。そのため、2回目のZ押下時は「既に戻った状態」が基準点になっているため、変化が起きない状況と推測できます。
以下のログが問題点を示しています。初回restore_state()実行後に[DEBUG] restore_state(): State saved after restore.と表示され、状態が再保存されているため、次のZ押下でもう一段階前には戻れなくなっています。
問題点の詳細restore_state()内でprevious_state.clear()した後、save_state()で同じ状態を再度保存しているため、状態が1段階戻った段階で固定化されてしまいます。つまり、もう1段階前(初期状態)に戻したいのに、次にZを押すと、今の戻った後の状態が「前の状態」として上書き保存されてしまっており、戻り先が無い状況です。
解決策
対応策1:restore_state()後のsave_state()削除
restore_state()内でsave_state()を行わないようにすることで、状態復元後に即座にその状態を基準点としてしまう問題を解消できます。これにより、2回目のZ押下ではさらに古い状態へ戻れるようになります。
func restore_state(): if previous_state.is_empty(): print("[DEBUG] restore_state(): previous_state is empty, no state to restore.") return print("[DEBUG] restore_state(): Restoring state...") if previous_state.selected_unit: _restore_selected_unit_state() print("[DEBUG] restore_state(): Selected unit restored:", previous_state.selected_unit) waiting_for_direction = previous_state.waiting_for_direction waiting_for_turn_end = previous_state.waiting_for_turn_end selected_action = previous_state.selected_action print("[DEBUG] restore_state(): waiting_for_direction =", waiting_for_direction, ", waiting_for_turn_end =", waiting_for_turn_end, ", selected_action =", selected_action) if previous_state.action_buttons_visible: battle_ui.show_action_buttons() print("[DEBUG] restore_state(): Action buttons visible") else: battle_ui.hide_action_buttons() print("[DEBUG] restore_state(): Action buttons hidden") previous_state.clear() print("[DEBUG] restore_state(): previous_state cleared") _re_show_ranges_based_on_state() print("[DEBUG] restore_state(): Re-showing ranges based on restored state") # ★ここでsave_state()を行わないようにする #save_state() #print("[DEBUG] restore_state(): State saved after restore.")
これで、1回目のZで戻した状態を即保存せず、2回目のZでさらにその前の状態(初期状態)に戻ることが可能になります。
対応策2:状態履歴のスタック化
もし将来的に複数段階のアンドゥ機能を実装する場合は、previous_stateを一つだけではなくスタック(配列)で管理し、push/popする仕組みに変更することも検討できます。しかし、今回の要件(2回戻る程度)であれば上記の対応策1が手っ取り早いです。
次のステップ対応策1の修正を行い、再度Zボタンを2回押して初期状態まで問題なく戻るかテストしてください。
もしこれで解決しない場合は、_redisplay_ranges_after_restore()内での表示処理、selected_actionやselected_unitの状態が正しく復元されているかを追加のログで確認するなど、さらなるデバッグが必要です。
以上で、デバッグ方針および修正案となります。
o1 proは解決策2で「状態履歴のスタック化」を提案してくれていました。これは少し評価できます。ただ、今回は2回しか戻らないので不要かなと言ってますね。
ただ、これでも治らなかったのでもう少し続けていきます。
すると、、、

ここで方針転換がありました。
このままだとバグが発生したので以降も何度か続けると・・・。
ダメでした。。。
本命だったのですが、ここで敗退です。
正直少し残念でしたが、Godotが苦手なだけの可能性もあるのでよしとします。
ちょっと今月はもう別の使い方を検討します。
エントリーNo3:Gemini-exp-1206(前回1位)
さて、o1 Proでも解決できなかった今回の問題。
あまり期待はせずに同じプロンプトを投げつけます。
すると、、、
現状のバグは、`_handle_key_z_input`関数で`is_in_action`が`true`の時に、`restore_state()`後に`is_in_action`を`false`に設定していることが原因のようです。このため、2回目のZボタン押下時には`is_in_action`が`false`であるため、`restore_state()`が呼ばれず状態が復元されません。
以下は、`_handle_key_z_input`関数の修正案です。
```gdscript
func _handle_key_z_input(event) -> bool:
if event is InputEventKey and event.pressed and event.keycode == KEY_Z:
if is_in_action:
# 状態復元
restore_state()
# is_in_action = false # この行を削除
# ... 省略 ...
return true
# ... 省略 ...
return false
```
この修正により、`is_in_action`が`true`の時に`restore_state()`が呼ばれた後も`is_in_action`が`true`のままとなり、2回目のZボタン押下時にも`restore_state()`が呼ばれるようになります。
これで、理想の動作に近づくはずです。
**変更箇所の詳細説明**
* `_handle_key_z_input` 関数内の `is_in_action = false` を削除しました。
**変更理由**
* `is_in_action` を `false` に設定してしまうと、2回目のZボタン押下時に `if is_in_action:` の条件が満たされず、`restore_state()` が実行されなくなります。
* `is_in_action` は、アクションの実行中か否かを表すフラグです。状態を復元した後も、アクションの実行中であることに変わりはないため、`is_in_action` を `false` に設定する必要はありません。
**その他の確認事項**
* `restore_state()` 関数内で、`previous_state` をクリアした後に `_re_show_ranges_based_on_state()` が呼ばれていることを確認してください。これにより、状態を復元した後に、移動範囲や攻撃範囲が正しく再表示されます。
**動作確認**
上記の修正を行った後、以下の手順で動作確認を行ってください。
1. 初期状態
2. アクション1: 移動実施
3. 状態1: 移動完了
4. アクション2: 待機ボタン押下
5. 待機方向が選択できますよ状態
6. Zボタン押下
7. 状態1: 移動完了
8. 2回目のZボタン押下
9. 初期状態
この手順で、2回目のZボタン押下時に初期状態に戻ることを確認してください。
**補足**
* `_handle_key_z_input` 関数内で、`is_in_action` が `false` の場合にも、`selected_unit.has_moved` や `selected_action == ActionType.ATTACK` の条件によって、状態の復元が行われる可能性があります。これらの条件によって状態の復元が行われた場合にも、`is_in_action` を `false` に設定しないように注意してください。
この修正で問題が解決することを願っています。もし他に質問があれば、遠慮なく聞いてください。
お?なんか似てはいますが少し違う回答です。
引き続きコードを依頼します。
するとほぼ全文くれました(笑)
# grid_manager.gd
extends Node3D
class_name GridManager
const MovementRangeClass := preload("res://scripts/battle/movement_range.gd")
signal cell_selected(position: Vector2i)
signal cell_highlighted(position: Vector2i)
signal cell_unhighlighted(position: Vector2i)
signal turn_changed(team: int)
@onready var battle_ui: BattleUI = $"../BattleUI"
@export var grid_size: Vector2i = Vector2i(10, 10)
@export var cell_size: float = 1.0
enum Team { PLAYER = 0, ENEMY = 1 }
enum ActionType { ATTACK, MAGIC, WAIT }
# --- フィールド変数 ---
var attack_range: AttackRange
var movement_range: MovementRange
var turn_manager: TurnManager
var current_team: int = Team.PLAYER
var active_units: Dictionary = {
Team.PLAYER: [],
Team.ENEMY: []
}
var grid_data: Dictionary = {}
var visualization_node: Node3D
var selected_cell_indicator: MeshInstance3D = null
# ユニット関連
var units: Dictionary = {} # キー: Vector2i(位置), 値: Unit
var selected_unit: Unit = null
# 状態フラグ
var waiting_for_turn_end: bool = false
var selected_action: ActionType = ActionType.ATTACK
var waiting_for_direction: bool = false
var is_in_action: bool = false
# 状態保存用
var previous_state: Dictionary = {}
var selected_unit_previous_position: Vector2i = Vector2i(-1, -1)
var has_moved_previous_state: bool = false
var has_attacked_previous_state: bool = false
var has_acted_previous_state: bool = false
func _ready():
_initialize_grid()
_create_visualization()
_create_selection_indicator()
movement_range = MovementRangeClass.new()
movement_range.set_grid_manager(self)
add_child(movement_range)
attack_range = AttackRange.new()
attack_range.set_grid_manager(self)
add_child(attack_range)
turn_manager = TurnManager.new()
add_child(turn_manager)
_connect_turn_signals()
battle_ui.hide_action_buttons()
battle_ui.connect_action_buttons(self)
func _connect_turn_signals():
if not turn_manager.turn_changed.is_connected(_on_turn_changed):
turn_manager.turn_changed.connect(_on_turn_changed)
#==================================================
# 初期化系
#==================================================
func _initialize_grid():
for x in range(grid_size.x):
for y in range(grid_size.y):
var pos = Vector2i(x, y)
grid_data[pos] = CellData.new()
func _create_visualization():
visualization_node = Node3D.new()
add_child(visualization_node)
var material = StandardMaterial3D.new()
material.albedo_color = Color(0.8, 0.8, 0.8, 1.0)
var mesh = BoxMesh.new()
mesh.size = Vector3(cell_size * 0.9, 0.1, cell_size * 0.9)
mesh.surface_set_material(0, material)
for x in range(grid_size.x):
for y in range(grid_size.y):
_create_single_cell_visual(x, y, mesh)
func _create_single_cell_visual(x: int, y: int, mesh: BoxMesh):
var static_body = StaticBody3D.new()
var collision_shape = CollisionShape3D.new()
var box_shape = BoxShape3D.new()
box_shape.size = Vector3(cell_size * 0.9, 0.1, cell_size * 0.9)
collision_shape.shape = box_shape
var mesh_instance = MeshInstance3D.new()
mesh_instance.mesh = mesh
static_body.add_child(collision_shape)
static_body.add_child(mesh_instance)
static_body.position = grid_to_world(Vector2i(x, y))
visualization_node.add_child(static_body)
func _create_selection_indicator():
var material = StandardMaterial3D.new()
material.albedo_color = Color(1.0, 1.0, 0.0, 0.5)
material.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
var mesh = BoxMesh.new()
mesh.size = Vector3(cell_size * 0.95, 0.2, cell_size * 0.95)
mesh.surface_set_material(0, material)
selected_cell_indicator = MeshInstance3D.new()
selected_cell_indicator.mesh = mesh
selected_cell_indicator.visible = false
add_child(selected_cell_indicator)
#==================================================
# 入力処理
#==================================================
func _input(event):
if not turn_manager.is_player_turn():
return
if _handle_waiting_direction_input(event):
return
if _handle_key_z_input(event):
return
if _handle_key_space_input(event):
return
if _handle_mouse_left_click(event):
return
func _handle_waiting_direction_input(event) -> bool:
if waiting_for_direction and selected_unit and event is InputEventKey and event.pressed:
match event.keycode:
KEY_UP:
selected_unit.set_direction(Vector2i.UP)
KEY_DOWN:
selected_unit.set_direction(Vector2i.DOWN)
KEY_LEFT:
selected_unit.set_direction(Vector2i.RIGHT)
KEY_RIGHT:
selected_unit.set_direction(Vector2i.LEFT)
KEY_SPACE:
_finish_current_action()
return true
KEY_Z:
waiting_for_direction = false
battle_ui.show_action_buttons()
print("Z pressed during waiting_for_direction. Showing action buttons.")
# ★ここでは敢えてsave_state()しない
# 理由:Zで戻った後にさらに戻る状態を増やさないため
return true
return false
func _handle_key_z_input(event) -> bool:
if event is InputEventKey and event.pressed and event.keycode == KEY_Z:
print("Z key pressed. is_in_action: ", is_in_action)
if is_in_action:
print("Restoring state due to Z key in action.")
# 状態復元
restore_state()
# is_in_action = false # この行を削除
# 状態復元後に攻撃選択中であれば攻撃範囲をクリア
if selected_action == ActionType.ATTACK:
cancel_attack() # 攻撃範囲非表示と3択表示を行う
else:
# 攻撃中でない場合は本来の再表示処理
_redisplay_ranges_after_restore()
return true
elif selected_unit:
print("Selected unit exists. Checking conditions for Z key.")
# まずユニットが移動済みかチェックして、移動キャンセルを優先する
if selected_unit.has_moved:
print("Cancelling movement due to Z key.")
cancel_movement()
# キャンセル直後はsave_state()を行わない
# 必要に応じて次の行動開始時にsave_state()
return true
# それ以外に攻撃アクション中なら攻撃キャンセル
elif selected_action == ActionType.ATTACK:
print("Cancelling attack due to Z key.")
cancel_attack()
# 攻撃キャンセル直後はsave_state()せず、次の行動時に保存
return true
return false
func _redisplay_ranges_after_restore():
if not selected_unit:
return
var movement_cells = [] # ここで変数を宣言しておく
if not selected_unit.has_moved:
movement_cells = movement_range.calculate_movement_range(selected_unit)
movement_range.show_movement_range(selected_unit)
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(selected_unit, movement_cells)
elif selected_unit.has_moved and not selected_unit.has_attacked:
# ここではmovement_cells不要なら宣言不要
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(selected_unit)
func _handle_key_space_input(event) -> bool:
if event is InputEventKey and event.pressed and event.keycode == KEY_SPACE:
if waiting_for_turn_end:
_finish_turn()
# ターン終了後は現状が新たな基準点
save_state()
return true
elif selected_unit:
select_action(ActionType.WAIT)
return true
return false
func _handle_mouse_left_click(event) -> bool:
if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
var camera = get_viewport().get_camera_3d()
if camera:
var from = camera.project_ray_origin(event.position)
var to = from + camera.project_ray_normal(event.position) * 1000.0
var space_state = get_world_3d().direct_space_state
var query = PhysicsRayQueryParameters3D.create(from, to)
var result = space_state.intersect_ray(query)
if result:
var grid_pos = world_to_grid(result.position)
if is_valid_position(grid_pos):
_select_cell(grid_pos)
# セル選択後、この状態を新たな基準点として保存
save_state()
return true
return false
#==================================================
# ターン終了処理
#==================================================
func _finish_turn():
waiting_for_turn_end = false
battle_ui.hide_turn_end_button()
turn_manager.end_turn()
# ターン終了後の状態を基準点として再保存
save_state()
#==================================================
# 行動終了処理
#==================================================
func _finish_current_action():
if not selected_unit:
return
if waiting_for_direction:
_finish_wait_action()
else:
_finish_generic_action()
func _finish_wait_action():
waiting_for_direction = false
selected_unit.end_action()
selected_unit = null
_clear_ranges()
waiting_for_turn_end = true
battle_ui.show_turn_end_button()
print("Wait action finished. Showing turn end button.")
# 待機完了後、この状態を基準点として再保存
save_state()
func _finish_generic_action():
selected_unit.end_action()
selected_unit = null
_clear_ranges()
waiting_for_turn_end = true
battle_ui.show_turn_end_button()
battle_ui.hide_action_buttons()
# アクション完了後、この状態を基準点として再保存
save_state()
func _clear_ranges():
movement_range.clear_range_display()
attack_range.clear_range_display()
#==================================================
# ユニット移動・アクション選択
#==================================================
func execute_movement(unit: Unit, target_pos: Vector2i):
_store_pre_movement_state(unit) # 移動前の状態を保存
print("Executing movement to ", target_pos)
if await move_unit(unit, target_pos):
unit.has_moved = true
_clear_ranges()
battle_ui.show_unit_info(unit)
if not unit.has_attacked:
battle_ui.show_action_buttons()
selected_action = ActionType.ATTACK
else:
_auto_end_turn_after_movement()
# 移動確定後この状態を記録
save_state()
print("State saved after movement.")
# ここで行動完了とし、is_in_actionをfalseに
is_in_action = false
func _store_pre_movement_state(unit: Unit):
is_in_action = true
selected_unit_previous_position = unit.grid_position
has_moved_previous_state = unit.has_moved
has_attacked_previous_state = unit.has_attacked
has_acted_previous_state = unit.has_acted
print("Pre-movement state stored. is_in_action: ", is_in_action)
func _auto_end_turn_after_movement():
selected_unit.end_action()
selected_unit = null
battle_ui.hide_unit_info()
turn_manager.end_turn()
battle_ui.hide_action_buttons()
# ターン終了直後にsave_state()はend_turn内で呼んでいるので追加は不要
func select_action(action_type: ActionType):
print("Selecting action: ", action_type)
selected_action = action_type
is_in_action = true
save_state()
print("State saved after selecting action. is_in_action: ", is_in_action)
match selected_action:
ActionType.ATTACK:
battle_ui.hide_action_buttons()
if selected_unit:
# 攻撃モードのみ攻撃範囲表示
attack_range.show_attack_range(selected_unit)
ActionType.MAGIC:
_finish_current_action()
ActionType.WAIT:
battle_ui.hide_action_buttons()
waiting_for_direction = true # 向き選択モード
#==================================================
# ターン変更処理
#==================================================
func _on_turn_changed(_team: int):
selected_unit = null
_clear_ranges()
battle_ui.hide_action_buttons()
if not turn_manager.is_player_turn():
execute_enemy_turn()
# ターン開始後の状態を基準点として再保存
save_state()
#==================================================
# 敵ターン・AI関連
#==================================================
func execute_enemy_turn():
print("Execute enemy turn started")
print("Enemy units: ", turn_manager.active_units[TurnManager.Team.ENEMY].size())
for unit in turn_manager.active_units[TurnManager.Team.ENEMY]:
if not unit.has_acted:
_enemy_act(unit)
print("Enemy turn complete")
turn_manager.end_turn()
# 敵ターン終了後はend_turn()でsave_state()される
func _enemy_act(enemy_unit: Unit):
print("Enemy unit acting")
var target_pos = find_closest_player_unit_position(enemy_unit)
if target_pos != Vector2i(-1, -1):
_enemy_try_attack_or_move(enemy_unit, target_pos)
enemy_unit.end_action()
_clear_ranges()
battle_ui.hide_action_buttons()
func _enemy_try_attack_or_move(enemy_unit: Unit, target_pos: Vector2i):
var attack_cells = attack_range.calculate_attack_range(enemy_unit)
var can_attack = false
var target_unit = null
for attack_pos in attack_cells:
target_unit = get_unit_at(attack_pos)
if target_unit and target_unit.team == TurnManager.Team.PLAYER:
can_attack = true
break
if can_attack and target_unit:
enemy_unit.perform_attack(target_unit)
else:
# 移動して攻撃
var move_pos = calculate_movement_toward_target(enemy_unit, target_pos)
if await move_unit(enemy_unit, move_pos):
attack_cells = attack_range.calculate_attack_range(enemy_unit)
for attack_pos in attack_cells:
target_unit = get_unit_at(attack_pos)
if target_unit and target_unit.team == TurnManager.Team.PLAYER:
enemy_unit.perform_attack(target_unit)
break
func find_closest_player_unit_position(enemy_unit: Unit) -> Vector2i:
var closest_distance = 999
var closest_pos = Vector2i(-1, -1)
for unit in turn_manager.active_units[TurnManager.Team.PLAYER]:
var distance = calculate_grid_distance(enemy_unit.grid_position, unit.grid_position)
if distance < closest_distance:
closest_distance = distance
closest_pos = unit.grid_position
print("Found player unit at: ", closest_pos, " distance: ", closest_distance)
return closest_pos
#==================================================
# Utility系(計算系)
#==================================================
func calculate_grid_distance(from: Vector2i, to: Vector2i) -> int:
return abs(from.x - to.x) + abs(from.y - to.y)
func calculate_movement_toward_target(unit: Unit, target_pos: Vector2i) -> Vector2i:
var possible_moves = movement_range.calculate_movement_range(unit)
var best_move = unit.grid_position
var best_distance = 999
print("Calculating movement toward: ", target_pos)
print("Possible moves from movement range: ", possible_moves)
for move in possible_moves:
var distance = calculate_grid_distance(move, target_pos)
if distance < best_distance:
best_distance = distance
best_move = move
print("Found better move: ", best_move, " distance: ", best_distance)
return best_move
func calculate_attack_position(attacker: Unit, target_pos: Vector2i) -> Vector2i:
var target_unit = get_unit_at(target_pos)
if not target_unit:
return attacker.grid_position
var possible_positions = []
var directions = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
for dir in directions:
var pos = target_pos + dir
if is_valid_position(pos) and pos in movement_range._current_range:
possible_positions.append(pos)
var best_pos = attacker.grid_position
var best_distance = 999
for pos in possible_positions:
var distance = calculate_grid_distance(attacker.grid_position, pos)
if distance < best_distance:
best_distance = distance
best_pos = pos
return best_pos
#==================================================
# グリッド・ユニット管理系
#==================================================
func is_valid_position(pos: Vector2i) -> bool:
return pos.x >= 0 and pos.x < grid_size.x and pos.y >= 0 and pos.y < grid_size.y
func get_cell_data(pos: Vector2i) -> CellData:
return grid_data.get(pos)
func world_to_grid(world_pos: Vector3) -> Vector2i:
return Vector2i(int(world_pos.x / cell_size), int(world_pos.z / cell_size))
func grid_to_world(grid_pos: Vector2i) -> Vector3:
return Vector3(grid_pos.x * cell_size, 0, grid_pos.y * cell_size)
func place_unit(unit: Unit, pos: Vector2i) -> bool:
if not is_valid_position(pos) or has_unit_at(pos):
return false
_remove_unit_from_old_pos_if_needed(unit)
units[pos] = unit
unit.grid_position = pos
unit.position = grid_to_world(pos)
return true
func _remove_unit_from_old_pos_if_needed(unit: Unit):
if units.has(unit):
var old_pos = units.find_key(unit)
units.erase(old_pos)
func get_unit_at(pos: Vector2i) -> Unit:
return units.get(pos)
func has_unit_at(pos: Vector2i) -> bool:
return units.has(pos)
func move_unit(unit: Unit, new_pos: Vector2i) -> bool:
if not is_valid_position(new_pos) or has_unit_at(new_pos):
return false
var old_pos = unit.grid_position
units.erase(old_pos)
await unit.move_to_grid(new_pos)
if place_unit(unit, new_pos):
unit.unit_moved.emit(old_pos, new_pos)
return true
return false
#==================================================
# セル選択・行動処理
#==================================================
func _select_cell(grid_pos: Vector2i):
if not is_valid_position(grid_pos) or not turn_manager.is_player_turn():
battle_ui.hide_unit_info()
return
var target_unit = get_unit_at(grid_pos)
_update_ui_for_target_unit(target_unit)
if selected_unit:
if await _attempt_attack_if_possible(target_unit, grid_pos):
# 攻撃実行後の状態を基準点として再保存
save_state()
return
if _attempt_move_if_in_range(grid_pos):
# 移動後の状態を基準点として再保存はexecute_movement内で行う
return
if target_unit and target_unit.team == Team.PLAYER and not target_unit.has_acted:
_select_new_unit(target_unit)
# ユニット選択後の状態を再保存
save_state()
selected_cell_indicator.visible = true
selected_cell_indicator.position = grid_to_world(grid_pos)
cell_selected.emit(grid_pos)
func _update_ui_for_target_unit(target_unit: Unit):
if target_unit:
battle_ui.show_unit_info(target_unit)
else:
battle_ui.hide_unit_info()
func _attempt_attack_if_possible(target_unit: Unit, grid_pos: Vector2i) -> bool:
if selected_unit and target_unit and target_unit.team != selected_unit.team and attack_range.is_in_attack_range(grid_pos):
# 近接攻撃用に移動
if grid_pos in movement_range._current_range:
var attack_pos = calculate_attack_position(selected_unit, grid_pos)
if attack_pos != selected_unit.grid_position:
await execute_movement(selected_unit, attack_pos)
if selected_action == ActionType.ATTACK:
_execute_attack(target_unit)
return true
return false
func _execute_attack(target_unit: Unit):
is_in_action = false
selected_unit.perform_attack(target_unit)
selected_unit.has_attacked = true
_clear_ranges()
selected_unit.end_action()
selected_unit = null
battle_ui.hide_unit_info()
waiting_for_turn_end = true
battle_ui.show_turn_end_button()
battle_ui.hide_action_buttons()
# 攻撃終了後、この状態を基準点として再保存
save_state()
func _attempt_move_if_in_range(grid_pos: Vector2i) -> bool:
if selected_unit and movement_range.is_cell_in_range(grid_pos):
is_in_action = true
save_state()
print("State saved before executing movement. is_in_action: ", is_in_action)
execute_movement(selected_unit, grid_pos)
# execute_movement内で移動完了後save_state()を行うのでここは不要
return true
return false
func _select_new_unit(target_unit: Unit):
selected_unit = target_unit
is_in_action = false
if not target_unit.has_moved:
var movement_cells = movement_range.calculate_movement_range(target_unit)
movement_range.show_movement_range(target_unit)
# ATTACKアクション中のみ攻撃範囲を表示
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(target_unit, movement_cells)
elif not target_unit.has_attacked:
# ATTACKアクション中のみ攻撃範囲表示
if selected_action == ActionType.ATTACK:
attack_range.show_attack_range(target_unit)
#==================================================
# 状態保存・復元系
#==================================================
func save_state():
print("Saving state...")
previous_state = {
"selected_unit": selected_unit,
"selected_unit_position": selected_unit.grid_position if selected_unit else null,
"has_moved": selected_unit.has_moved if selected_unit else false,
"has_attacked": selected_unit.has_attacked if selected_unit else false,
"has_acted": selected_unit.has_acted if selected_unit else false,
"waiting_for_direction": waiting_for_direction,
"waiting_for_turn_end": waiting_for_turn_end,
"selected_action": selected_action,
"action_buttons_visible": battle_ui.are_action_buttons_visible()
}
print("State saved. Current state: ", previous_state)
func restore_state():
print("Restoring state...")
if previous_state.is_empty():
print("No previous state to restore.")
return
if previous_state.selected_unit:
_restore_selected_unit_state()
waiting_for_direction = previous_state.waiting_for_direction
waiting_for_turn_end = previous_state.waiting_for_turn_end
selected_action = previous_state.selected_action
if previous_state.action_buttons_visible:
battle_ui.show_action_buttons()
else:
battle_ui.hide_action_buttons()
previous_state.clear()
print("State restored. previous_state cleared.")
_re_show_ranges_based_on_state()
# ★復元直後のsave_state()は削除
# 状態を戻した後に即再保存せず、「もう一段戻りたい」ときに必要以上にZキーを押す必要がないようにする。
func _restore_selected_unit_state():
selected_unit = previous_state.selected_unit
selected_unit.has_moved = previous_state.has_moved
selected_unit.has_attacked = previous_state.has_attacked
selected_unit.has_acted = previous_state.has_acted
if previous_state.selected_unit_position:
units.erase(selected_unit.grid_position)
selected_unit.position = grid_to_world(previous_state.selected_unit_position)
selected_unit.grid_position = previous_state.selected_unit_position
units[selected_unit.grid_position] = selected_unit
print("Restored selected unit state.")
func _re_show_ranges_based_on_state():
if selected_unit:
# 攻撃アクション以外では攻撃範囲を表示しない
var show_attack = (selected_action == ActionType.ATTACK)
var movement_cells = []
if not selected_unit.has_moved:
movement_cells = movement_range.calculate_movement_range(selected_unit)
movement_range.show_movement_range(selected_unit)
if show_attack:
attack_range.show_attack_range(selected_unit, movement_cells)
elif selected_unit.has_moved and not selected_unit.has_attacked:
if show_attack:
attack_range.show_attack_range(selected_unit)
print("Re-showing ranges based on restored state.")
#==================================================
# キャンセル系
#==================================================
func cancel_movement():
print("Cancelling movement...")
if selected_unit and selected_unit_previous_position != Vector2i(-1, -1):
units.erase(selected_unit.grid_position)
selected_unit.position = grid_to_world(selected_unit_previous_position)
selected_unit.grid_position = selected_unit_previous_position
units[selected_unit.grid_position] = selected_unit
selected_unit.has_moved = has_moved_previous_state
selected_unit.has_attacked = has_attacked_previous_state
selected_unit.has_acted = has_acted_previous_state
selected_unit_previous_position = Vector2i(-1, -1)
_clear_ranges()
_re_show_ranges_after_cancel()
battle_ui.hide_action_buttons()
battle_ui.hide_unit_info()
print("Movement cancelled.")
func _re_show_ranges_after_cancel():
if selected_unit:
var show_attack = (selected_action == ActionType.ATTACK)
if not selected_unit.has_moved:
var movement_cells = movement_range.calculate_movement_range(selected_unit)
movement_range.show_movement_range(selected_unit)
if show_attack:
attack_range.show_attack_range(selected_unit, movement_cells)
elif selected_unit.has_moved and not selected_unit.has_attacked:
if show_attack:
attack_range.show_attack_range(selected_unit)
print("Re-showing ranges after movement cancellation.")
func cancel_attack():
print("Cancelling attack...")
attack_range.clear_range_display()
battle_ui.show_action_buttons()
# 攻撃キャンセル直後もsave_state()はしない
# 次の行動開始時にsave_state()する
print("Attack cancelled.")
func remove_unit(unit: Unit):
if unit.team in active_units:
active_units[unit.team].erase(unit)
if check_game_end():
print("Game has ended!")
func check_game_end() -> bool:
if active_units[Team.PLAYER].is_empty():
return true
if active_units[Team.ENEMY].is_empty():
return true
return false
func register_unit(unit: Unit):
if unit.team in active_units:
active_units[unit.team].append(unit)
func start_game():
print("================")
print("Turn 1 - Player's turn START")
print("Active units for current team: ", active_units[current_team].size())
_start_turn()
func _start_turn():
for unit in active_units[current_team]:
unit.reset_actions()
turn_changed.emit(current_team)
# ターン開始時点で状態を保存
save_state()
func end_turn():
print("Current turn ending check...")
for unit in active_units[current_team]:
if not unit.has_acted:
print("Turn cannot end - ", active_units[current_team].size(), " units haven't acted yet")
return
print(get_team_name(current_team), "'s turn END")
print("================")
current_team = Team.ENEMY if current_team == Team.PLAYER else Team.PLAYER
print("================")
print("Turn 1 - ", get_team_name(current_team), "'s turn START")
print("Active units for current team: ", active_units[current_team].size())
_start_turn()
# ターン終了後、_start_turn()で再度save_state()されるため、ここでは不要
func get_team_name(team: int) -> String:
return "Player" if team == Team.PLAYER else "Enemy"
func is_player_turn() -> bool:すげえGemini(笑)
しかし、うまくはいかなかったのでo1,o1 pro同様にデバックログを共有します。
提供されたデバッグログとコードを詳細に分析した結果、問題の核心は `restore_state()` 関数が `previous_state` をクリアするタイミングにあることがわかりました。
**問題点の詳細**
現在、`restore_state()` は状態を復元した**直後**に `previous_state.clear()` を呼び出して `previous_state` をクリアしています。これにより、以下の問題が発生しています。
1. **待機方向選択中にZキーを押す**: `_handle_waiting_direction_input` 内で `waiting_for_direction = false` となり、アクションボタンが表示されます。この時点では `previous_state` は保持されています(意図通り)。
2. **移動完了状態でZキーを押す (1回目)**: `_handle_key_z_input` で `is_in_action` が `true` のため、`restore_state()` が呼び出されます。`restore_state()` は状態を復元し、`previous_state.clear()` で `previous_state` をクリアします。
3. **移動完了状態でZキーを押す (2回目)**: `_handle_key_z_input` で `is_in_action` が `true` ですが、`previous_state` は既にクリアされているため、`restore_state()` は何もせずに終了します。結果として、画面は変化しません。
4. **移動完了状態でZキーを押す (3回目)**: `_handle_key_z_input` で `is_in_action` が `false` となり、`elif selected_unit:` の部分が実行され、`selected_unit.has_moved` が `true` なので `cancel_movement()` が実行され、初期状態に戻ります。
**根本原因**
`restore_state()` が `previous_state` をクリアするタイミングが早すぎるため、2回目のZキー押下時に復元すべき状態が失われています。
**解決策**
`previous_state` をクリアするタイミングを、`restore_state()` の直後から、次の新しい状態が保存される直前 (`save_state()` の直前) に変更します。
**修正コード**
```gdscript
# grid_manager.gd
# ... (他のコードは変更なし)
#==================================================
# 状態保存・復元系
#==================================================
func save_state():
print("Saving state...")
# 新しい状態を保存する直前に、古い previous_state をクリアする
previous_state.clear()
previous_state = {
"selected_unit": selected_unit,
"selected_unit_position": selected_unit.grid_position if selected_unit else null,
"has_moved": selected_unit.has_moved if selected_unit else false,
"has_attacked": selected_unit.has_attacked if selected_unit else false,
"has_acted": selected_unit.has_acted if selected_unit else false,
"waiting_for_direction": waiting_for_direction,
"waiting_for_turn_end": waiting_for_turn_end,
"selected_action": selected_action,
"action_buttons_visible": battle_ui.are_action_buttons_visible()
}
print("State saved. Current state: ", previous_state)
func restore_state():
print("Restoring state...")
if previous_state.is_empty():
print("No previous state to restore.")
return
if previous_state.selected_unit:
_restore_selected_unit_state()
waiting_for_direction = previous_state.waiting_for_direction
waiting_for_turn_end = previous_state.waiting_for_turn_end
selected_action = previous_state.selected_action
if previous_state.action_buttons_visible:
battle_ui.show_action_buttons()
else:
battle_ui.hide_action_buttons()
# previous_state.clear() をここから削除
print("State restored. previous_state remains for potential further restoration.")
_re_show_ranges_based_on_state()
# ★復元直後のsave_state()は削除
# 状態を戻した後に即再保存せず、「もう一段戻りたい」ときに必要以上にZキーを押す必要がないようにする。
# ... (他のコードは変更なし)
```
**変更点の詳細**
1. `save_state()` の冒頭で `previous_state.clear()` を呼び出し、新しい状態を保存する直前に古い状態をクリアするようにしました。
2. `restore_state()` から `previous_state.clear()` を削除しました。
**動作確認**
この修正により、以下の手順で理想的な動作になるはずです。
1. 初期状態
2. アクション1: 移動実施
3. 状態1: 移動完了
4. アクション2: 待機ボタン押下
5. 待機方向が選択できますよ状態
6. Zボタン押下
7. 状態1: 移動完了
8. 2回目のZボタン押下
9. 初期状態
**追加の提案**
* デバッグログを見やすくするために、`print()` 関数で出力するメッセージにインデントを追加することを検討してください。例えば、`save_state()` や `restore_state()` の中では、インデントを深くして出力すると、どの関数が呼ばれているのかがわかりやすくなります。
この修正で問題が解決することを期待しています。もし他に質問があれば、遠慮なく聞いてください。
「restore_state()` が `previous_state` をクリアするタイミングが早すぎるため、2回目のZキー押下時に復元すべき状態が失われています」
正直、この部分は非常にコンパクトで好印象でした。
そして、なぜかこれは勘なのですがめっちゃ合ってそうに見えたんです。
ただ、まだ駄目だったので引き続き調査してもらうと。。
問題の原因は、`restore_state()` 関数で `previous_state` をクリアしていないため、2回目のZボタン押下時に前回の状態ではなく、さらに前の状態が復元されてしまっていることにあります。そのため、画面上の変化が見られず、3回目のZボタン押下で初めて初期状態に戻っているように見えます。
修正するには、`restore_state()` 関数内で状態を復元した後に `previous_state` をクリアする必要があります。
具体的には、`restore_state()` 関数内の以下の部分を修正します。
**修正前:**
```gdscript
# previous_state.clear() をここから削除
print("State restored. previous_state remains for potential further restoration.")
_re_show_ranges_based_on_state()
# ★復元直後のsave_state()は削除
# 状態を戻した後に即再保存せず、「もう一段戻りたい」ときに必要以上にZキーを押す必要がないようにする。
```
**修正後:**
```gdscript
print("State restored. Clearing previous_state.")
_re_show_ranges_based_on_state()
# 状態復元後に previous_state をクリアする
previous_state.clear()
```
この修正により、`restore_state()` が呼ばれるたびに `previous_state` がクリアされるようになり、Zボタン押下で正しく一つ前の状態に戻るようになります。
以下は、上記の修正を反映した `restore_state()` 関数全体です。
```gdscript
func restore_state():
print("Restoring state...")
if previous_state.is_empty():
print("No previous state to restore.")
return
if previous_state.selected_unit:
_restore_selected_unit_state()
waiting_for_direction = previous_state.waiting_for_direction
waiting_for_turn_end = previous_state.waiting_for_turn_end
selected_action = previous_state.selected_action
if previous_state.action_buttons_visible:
battle_ui.show_action_buttons()
else:
battle_ui.hide_action_buttons()
print("State restored. Clearing previous_state.")
_re_show_ranges_based_on_state()
# 状態復元後に previous_state をクリアする
previous_state.clear()
```
この修正で、問題が解決するはずです。 デバッグログと照らし合わせて、動作を確認してみてください。
「この修正で、問題が解決するはずです。 デバッグログと照らし合わせて、動作を確認してみてください。」
何だこの安心感(笑)これはGPTにはない安心感です。
そしてこの時点でもどんどん解決に向かっている感覚がありました。
そしてさらに1回聞くと、何かをつかみ、次の1回で以下の回答を得られました。
前回ご提示した解決策に基づき、`_re_show_ranges_based_on_state()` 関数と `_handle_key_z_input`関数に修正を加えられたとのこと、素晴らしいです。それらの修正により、問題が解決する見込みが高まりました。
しかし、まだ完全に問題が解決していない可能性があるため、さらに詳細なデバッグと修正を行っていきましょう。
**追加のデバッグと修正**
**1. `restore_state()` の詳細なデバッグ**
`restore_state()` 関数内で、各変数が正しく復元されているかを確認するために、`print` 文を追加して変数の値を出力します。
```gdscript
func restore_state():
print("Restoring state...")
if previous_state.is_empty():
print("No previous state to restore.")
return
print(" previous_state.selected_unit:", previous_state.selected_unit)
print(" previous_state.selected_unit_position:", previous_state.selected_unit_position)
print(" previous_state.has_moved:", previous_state.has_moved)
print(" previous_state.has_attacked:", previous_state.has_attacked)
print(" previous_state.has_acted:", previous_state.has_acted)
print(" previous_state.waiting_for_direction:", previous_state.waiting_for_direction)
print(" previous_state.waiting_for_turn_end:", previous_state.waiting_for_turn_end)
print(" previous_state.selected_action:", previous_state.selected_action)
print(" previous_state.action_buttons_visible:", previous_state.action_buttons_visible)
if previous_state.selected_unit:
_restore_selected_unit_state()
waiting_for_direction = previous_state.waiting_for_direction
waiting_for_turn_end = previous_state.waiting_for_turn_end
selected_action = previous_state.selected_action
if previous_state.action_buttons_visible:
battle_ui.show_action_buttons()
else:
battle_ui.hide_action_buttons()
print("State restored. previous_state remains for potential further restoration.")
_re_show_ranges_based_on_state()
```
**2. `_re_show_ranges_based_on_state()` の修正の確認**
前回の修正で、`selected_unit` が `null` の場合の処理を追加しましたが、その部分が正しく動作しているかを確認します。以下の点に注目してデバッグしてください。
* `turn_manager.is_player_turn()` が `true` になっているか?
* `turn_manager.active_units[TurnManager.Team.PLAYER]` にアクティブなプレイヤーユニットが含まれているか?
* 各ユニットに対して `movement_range.calculate_movement_range(unit)` が呼び出され、移動範囲が計算されているか?
* `movement_range.show_movement_range(unit)` が呼び出され、移動範囲が表示されているか?
**3. `_handle_waiting_direction_input` の見直し**
`_handle_waiting_direction_input` 関数で、`KEY_Z` が押された場合の処理が、他の「Z」キーの処理と競合していないかを確認します。
```gdscript
func _handle_waiting_direction_input(event) -> bool:
if waiting_for_direction and selected_unit and event is InputEventKey and event.pressed:
match event.keycode:
# ... 他のキーの処理 ...
KEY_Z:
waiting_for_direction = false
battle_ui.show_action_buttons()
print("Z pressed during waiting_for_direction. Showing action buttons.")
print(" is_in_action:", is_in_action) # is_in_actionの状態を確認
return true
return false
```
ここで、`is_in_action` が `true` のままになっていると、`_handle_key_z_input` の `if is_in_action:` の部分が実行されてしまい、`restore_state()` が再度呼び出されてしまう可能性があります。
`_handle_waiting_direction_input`で`KEY_Z`が押されたときに`is_in_action = false`を追加することで、この問題を回避できます。
```gdscript
func _handle_waiting_direction_input(event) -> bool:
if waiting_for_direction and selected_unit and event is InputEventKey and event.pressed:
match event.keycode:
# ... 他のキーの処理 ...
KEY_Z:
waiting_for_direction = false
is_in_action = false # アクション中フラグをリセット
battle_ui.show_action_buttons()
print("Z pressed during waiting_for_direction. Showing action buttons.")
return true
return false
```
**4. `_handle_key_z_input` の追加デバッグ**
`_handle_key_z_input` 関数で、`restore_state()` が呼び出された後の `selected_unit` の状態を確認します。
```gdscript
func _handle_key_z_input(event) -> bool:
if event is InputEventKey and event.pressed and event.keycode == KEY_Z:
print("Z key pressed. is_in_action: ", is_in_action)
if is_in_action:
print("Restoring state due to Z key in action.")
# 状態復元
restore_state()
print(" selected_unit after restore_state():", selected_unit) # 復元後のselected_unitを確認
is_in_action = false # 状態復元後にアクション中フラグをリセット
# ... 後略 ...
```
**デバッグログの再確認**
これらの修正とデバッグを行った後、再度問題を再現させてデバッグログを確認してください。特に以下の点に注目してください。
* `restore_state()` 内の `print` 文で、各変数が正しく復元されているか?
* `_re_show_ranges_based_on_state()` 内の `print` 文で、範囲が正しく再表示されているか?
* `_handle_waiting_direction_input` 内の `print` 文で、`is_in_action` が `false` になっているか?
* `_handle_key_z_input` 内の `print` 文で、`selected_unit` が `restore_state()` 呼び出し後に `null` になっているか?
これらの確認を通じて、問題の原因をさらに絞り込むことができるはずです。
**それでも解決しない場合**
上記のデバッグと修正を行っても問題が解決しない場合は、以下の情報を添えて再度質問してください。
* **最新のコード全体**: `grid_manager.gd` の全文を添付してください。
* **詳細な操作手順**: 問題を再現するための手順を、できるだけ詳しく記述してください。
* **最新のデバッグログ**: 問題が発生した時点のデバッグログを添付してください。
* **その他の関連情報**: 問題に関連すると思われる情報があれば、それも提供してください。
これらの情報があれば、より効果的に問題の解決を支援できます。一緒に問題解決に向けて頑張りましょう!
そしてついに。。。。

できた( ;∀;)
めっちゃうれしかったです。
悔しいので
o1 Proは3万、Geminiは0円。。。。
あまりに悔しいのでせめてここまでの内容をo1 proにまとめてもらいました。



ふむふむ、、むずい(笑)
ただ、言っている内容はよく読むととても分かりやすいですし文章作成能力は非常に高いと予想しています。
なのでドキュメントを作ってもらう上でまだまだ役に立ちそうな気配はあります。
比較結果
最終的な結果は以下の通りとなりました。
1位:Gemini-exp-1206
2位:o1 pro
3位:o1
今回も「Gemini-exp-1206」が圧勝し、2連覇達成です。Godotでの開発課題に関しては、Gemini-exp-1206が突出した問題解決能力を示し、他を大きくリードしました。しかも無料という観点からすると、そのコストパフォーマンスは驚異的といえます。
※ただ、会話が長くなると返答してくれなくなったりするという弱点はあります。
前回時点では悩んでいましたが、結論Godot開発なら「Gemini-exp-1206」一択だと思います。
o1,o1 proともに20時間ほど使いましたが、Godot開発においての問題解決能力はGemini-exp-1206が頭一つ抜けています。
無料という観点も踏まえると、Gemini-exp-1206一択です。
ただ、文章生成能力はo1 proの方が高そうなのでコード生成以外ならGPTの課金も検討してもいいかもです。
ただし!毎回言っていますが引き続き使用していく中で変わる可能性もあります。
それはこの回答が奇跡的なもので以降は全然ダメダメになるとかは否定できないためですね。この点はご注意ください🙇♂️
引き続きガンガン使って調査します。
おわりに
今回は3モデルをゲーム開発を軸に調査しましたがいかがでしたでしょうか。
今回も朝9時から検証して、気づけば12時になっていました。(笑)
でも、非常に面白い知見が得られたと思います。
本日は以上になります!
ここまで読んでいただきありがとうございます。
もしよろしければコメントやフォロー、「いいね」を頂けますと幸いです。
では、また次回の記事でお会いしましょう!
※おまけ
筆者は現在、Vandal Heartsを彷彿とさせるターン制SRPGの制作に挑戦中。小中高と青春時代に夢中になったこのゲームを、自分自身の手で再現するべく日々奮闘しています。
ファイアーエムブレムにもどっぷりはまった時期もありましたが、結局VandalHeratsがNo1でした。
https://youtu.be/DUydclBZq_M?si=7bkOVtxcUO7dVa1V
また、今回は省きましたが、以下のようなこともしていました。
【0チャレンジ】【チャレンジ結果】3ヶ月でAIを駆使してポケモン風RPGは作れるのか with Claude3.5 | 記事編集 | note