extends SceneTree # Exercise the public scenes, inventory, pointer picking and physical finish. # Only the verifier reads the separately stored walkthroughs. const REPORT := "res://playtest/artifacts/element_puzzles/acceptance.json" var app var cases: Array = [] var current: Dictionary var pointer_inside := false func _initialize() -> void: root.mouse_entered.connect(func(): pointer_inside = true) root.mouse_exited.connect(func(): pointer_inside = false) call_deferred("run") func frames(count: int) -> void: for tick in range(count): await physics_frame func click(point: Vector2, shift := false) -> void: if not pointer_inside: root.notify_mouse_entered() pointer_inside = true var motion := InputEventMouseMotion.new() motion.position = point motion.shift_pressed = shift root.push_input(motion, true) for pressed in [true, false]: var event := InputEventMouseButton.new() event.position = point event.button_index = MOUSE_BUTTON_LEFT event.button_mask = MOUSE_BUTTON_MASK_LEFT if pressed else 0 event.pressed = pressed event.shift_pressed = shift root.push_input(event, true) await frames(2) func check(ok: bool, problem: String) -> bool: if not ok: current.errors.append(problem) print("FAIL ", current.scene, " ", problem) return ok func is_target(pick: Dictionary, step: Dictionary, position: Vector3) -> bool: return not pick.is_empty() and pick.id == "" and pick.kind == step.kind and pick.quarter == step.quarter and pick.position.distance_to(position) < .002 func click_empty_cell(step: Dictionary) -> bool: var position: Vector3 = app.lib.vector(step.position) if app.kind != step.kind: await click(app.palette_buttons[step.kind].get_global_rect().get_center()) for quarter_turn in range(posmod(int(step.quarter) - app.quarter, 4)): await click(app.palette_buttons[step.kind].get_global_rect().get_center()) if not check(app.kind == step.kind and app.quarter == step.quarter, "Palette could not select " + str(step)): return false # Try the starting camera first, then orbit around the target if another # structure obscures its cell, exactly as a player can orbit and pan. var initial_yaw: float = app.yaw for view in range(9): if view > 0: app.target = position app.yaw = initial_yaw + (view - 1) * PI / 2 app.pitch = 1.25 if view <= 4 else .45 app.camera_size = 8 app.update_camera() for offset in [Vector3.ZERO, Vector3(.3,0,.3), Vector3(-.3,0,.3), Vector3(.3,0,-.3), Vector3(-.3,0,-.3)]: var point: Vector2 = app.camera.unproject_position(position + offset + Vector3.UP * app.CELL_OVERLAY_Y) var pick: Dictionary = app.pick_candidate(point) if not is_target(pick, step, position): continue var count: int = app.records.size() await click(point) if app.records.size() == count + 1: var placed: Dictionary = app.records.back() return check(placed.kind == step.kind and placed.quarter == step.quarter and placed.position.distance_to(position) < .002, "Preview and placement disagree " + str(step)) # A click over a UI control may change the selection. Recentering # subsequent views places the intended point in the play area. if app.kind != step.kind or app.quarter != step.quarter: return check(false, "HUD overlapped build click " + str(step)) return check(false, "No legal pointer placement for " + str(step)) func simulate() -> Dictionary: var stats := {} var prev := {} var water_trial: bool = current.scene in ["res://playtest/water/scenes/04.tscn","res://playtest/water/scenes/05.tscn"] var placed_tiles := {} var actual_ice := {} var broken := {} for piece in app.pieces: if water_trial and str(piece.get_meta("record_id")).begins_with("built_"): placed_tiles[piece.get_meta("record_id")] = piece.position if piece.get_meta("piece_type") == "ice": actual_ice[str(piece.get_meta("record_id"))] = piece for i in range(app.balls.size()): var ball = app.balls[i] var id := str(ball.name) prev[id] = ball.position stats[id] = {"type":app.spawn_specs[i].ballTypeId, "max_immersion":0.0, "surface_flow_m":0.0, "ice_contacts":[], "cleared_ice":{}} if water_trial: stats[id].tiles={} stats[id].flow_m={"east":0.0,"south":0.0} await click(app.run_button.get_global_rect().get_center()) check(app.started, "Release control did not start the run") check(not app.release_ticks.is_empty() and app.release_ticks.all(func(t): return t == app.release_ticks[0]), "Balls were not released together") for tick in range(4000): await physics_frame for id in actual_ice: var ice = actual_ice[id] if ice.broken and not broken.has(id): var impacts: Array = ice.events.filter(func(e): return e.breaks) if not impacts.is_empty(): broken[id]={"time":app.elapsed, "ball":impacts[0].ballId, "impulse_Ns":impacts[0].normalImpulseNs} for i in range(app.balls.size()): var ball = app.balls[i] var id := str(ball.name) var observation: Dictionary = stats[id] var delta:Vector3 = ball.position - prev[id] prev[id] = ball.position observation.max_immersion = maxf(observation.max_immersion, ball.submerged_fraction) if ball.submerged_fraction > .04 and ball.submerged_fraction < .96: observation.surface_flow_m += delta.dot(ball.water_velocity.normalized()) if water_trial: if ball.water_velocity.x > 1:observation.flow_m.east += delta.x if ball.water_velocity.z > 1:observation.flow_m.south += delta.z for collider in ball.get_colliding_bodies(): var node: Node = collider while node != null and not node.has_meta("record_id"):node=node.get_parent() if not node:continue var tile_id = node.get_meta("record_id") if placed_tiles.has(tile_id): var key := str(placed_tiles[tile_id]) if not observation.tiles.has(key): observation.tiles[key]={"first":app.elapsed,"at":app.codec.array_from(ball.position)} observation.tiles[key].last=app.elapsed if collider.get_meta("piece_type","") == "ice" and tile_id not in observation.ice_contacts: observation.ice_contacts.append(node.get_meta("record_id")) for ice_id in broken: if observation.cleared_ice.has(ice_id):continue var record:Dictionary = app.records[app.index_for(ice_id)] if app.lib.record_bounds(record).has_point(ball.position): observation.cleared_ice[ice_id] = app.elapsed if app.solved or app.attempt_done or app.failed:break var ice_peaks := {} for block_id in actual_ice: for event in actual_ice[block_id].events: ice_peaks[event.ballId] = maxf(ice_peaks.get(event.ballId,0.0),event.normalImpulseNs) return {"won":app.solved, "goals":app.events.duplicate(true), "balls":stats, "breaks":broken, "ice_impact_peak_Ns":ice_peaks} func verify_mechanic(group: String, number: int) -> void: var observed: Dictionary = current.solved var wood: Dictionary = {} var iron: Dictionary = {} var wood_id := "" var iron_id := "" for id in observed.balls: var ball: Dictionary = observed.balls[id] if ball.type == "wood_ball": wood = ball wood_id = id if ball.type == "iron_ball": iron = ball iron_id = id if group == "water": if number != 2: check(not wood.is_empty() and wood.surface_flow_m > 1.0, "Wood did not travel along the current while partially immersed") if number >= 2: check(not iron.is_empty() and iron.max_immersion < .1, "Iron was not routed clear of water") check(not iron_id.is_empty() and current.blank.balls[iron_id].max_immersion > .95, "Missing contrast: iron should sink on the unbridged route") return if number != 2: check(not wood.is_empty() and not wood.ice_contacts.is_empty(), "Wood did not travel on intact ice") if number == 1 or number == 3: check(observed.breaks.is_empty(), "Wood broke the intended ice bridge") if number == 1: check(observed.ice_impact_peak_Ns.get(wood_id,0.0) > 0, "Opening lesson lacks a real wood impact") if number == 2 or number >= 4: var iron_opened_gate := false for gate_id in observed.breaks: var event: Dictionary = observed.breaks[gate_id] if event.ball != iron_id:continue if number == 2 or wood.get("cleared_ice",{}).get(gate_id,-1.0) > event.time: iron_opened_gate = true check(iron_opened_gate, "Missing iron break or later passage of wood through that gate") func check_dependency(group: String, number: int, layout: Dictionary) -> void: # Control runs keep the player's assembled track and the real ball profiles. # Change just the component whose role the level is intended to teach. var control := layout.duplicate(true) var label: String if group=="water" and number!=2: label="without_water" control.entities=control.entities.filter(func(r):return r.kind!="water") elif group=="ice" and number==2: label="wood_at_iron_start" control.balls[0].ballTypeId="wood_ball" elif group=="ice" and number>=4: label="without_iron" control.balls=control.balls.filter(func(b):return b.ballTypeId!="iron_ball") elif group=="ice" and number==3: label="without_ice_bridge" control.entities=control.entities.filter(func(r):return r.kind!="ice") else: return app.started=false app.open_lesson(number-1) app.apply_data(control) await frames(3) var result:Dictionary=await simulate() var woods:Array=control.balls.filter(func(b):return b.ballTypeId=="wood_ball").map(func(b):return b.id) current[label]={"goals":result.goals,"won":result.won} if label=="wood_at_iron_start": current[label].peak_Ns=result.ice_impact_peak_Ns.get(control.balls[0].id,0.0) check(current[label].peak_Ns>0.0 and result.breaks.is_empty(), "Wood did not hit and leave the same ice cap intact") check(not woods.is_empty() and not result.goals.any(func(e):return e.ballId in woods), "Wood still reached the goal " + label) func verify_low_bridge(run_result:Dictionary) -> Dictionary: var wood:Dictionary=run_result.balls.wood.tiles var iron:Dictionary=run_result.balls.iron.tiles var first_tile := "" for tile in wood: if first_tile=="" or wood[tile].first=wood[tile].first:continue if first_tile==tile:landing_found=true shared+=1 check(run_result.won and run_result.goals.size()==2 and run_result.goals[0].ballId=="iron", "Both balls must finish, iron first") check(run_result.balls.wood.surface_flow_m>1 and run_result.balls.iron.max_immersion<.1, "Wood must ride the current and iron must stay on its dry route") check(landing_found and shared>=2, "Wood must land directly on a tile cleared by iron, then roll on the same bridge") return {"first_wood_contact":wood.get(first_tile,{}), "first_tile":first_tile, "shared_tiles_in_order":shared, "iron_last_on_landing_tile_s":iron.get(first_tile,{}).get("last",-1), "won":run_result.won} func check_water_routes(number:int, solution:Array) -> void: if number==4: var flow:Dictionary=current.solved.balls.wood.flow_m check(flow.east>1 and flow.south>1,"Wood must ride both perpendicular currents") else: current.bridge_runs=[verify_low_bridge(current.solved)] for trial in range(19): app.started=false app.open_lesson(4) await frames(3 + trial % 7) for step in solution: if not await click_empty_cell(step):return var result:Dictionary=await simulate() current.bridge_runs.append(verify_low_bridge(result)) if not current.errors.is_empty():return app.started=false app.open_lesson(number-1) await frames(3) var fixture:Dictionary=JSON.parse_string(FileAccess.get_file_as_string("res://playtest/checks/water_alternate_routes.json")) for step in fixture[str(number)]: if not await click_empty_cell(step):return current.upper_route=await simulate() var alternate:Dictionary=current.upper_route check(not alternate.won and alternate.goals.size()==1 and alternate.goals[0].ballId=="wood" and alternate.balls.iron.max_immersion>.95, "Upper route should save wood alone and leave iron submerged") func validate_scene(group: String, number: int) -> void: var base := "res://playtest/%s/" % group var path := base+"scenes/%02d.tscn" % number current={"scene":path,"errors":[]} cases.append(current) var scene := load(path) as PackedScene if not check(scene != null, "Scene failed to load"):return app = scene.instantiate() root.add_child(app) await frames(4) check(app.series == group and app.lesson_index == number - 1, "Direct scene opened wrong level") check(app.validate_level(app.lesson.initial).is_empty(), "Invalid starting layout: "+app.validate_level(app.lesson.initial)) check(app.lesson.initial.pieces.is_empty() and app.records.all(func(r):return r.kind not in app.IDS), "Has a preplaced chute") var solution = JSON.parse_string(FileAccess.get_file_as_string(base+"solutions/%02d.json"%number)) if not check(solution is Array, "Missing solution"):return current.title = app.lesson.title current.blank = await simulate() check(not current.blank.won, "Empty layout already wins") app.started=false app.open_lesson(number-1) await frames(3) for step in solution: if not await click_empty_cell(step):return check(app.validate_level(app.encode()).is_empty(), "Illegal assembled layout") var layout:Dictionary=app.encode() current.placed=solution.size() current.solved=await simulate() check(current.solved.won and current.solved.goals.size()==app.balls.size(), "Answer did not get every ball into a hole") verify_mechanic(group,number) if current.errors.is_empty() and group=="ice" and number==5: # The two corners and shared hole exposed marginal rolling speeds in an # early version. Rebuild via the player UI on additional trial starts. current.repeat_goal_times=[] for trial in range(3): app.started=false app.open_lesson(number-1) await frames(3+trial) for step in solution: if not await click_empty_cell(step):return var again:Dictionary=await simulate() current.repeat_goal_times.append(again.goals.map(func(g):return g.time)) if not check(again.won and again.goals.size()==app.balls.size(), "Final ice puzzle stalled on repeat "+str(trial+1)):break if current.errors.is_empty() and group=="water" and number>=4:await check_water_routes(number,solution) if current.errors.is_empty():await check_dependency(group,number,layout) print("RESULT ",group,number," ",current.title," ",JSON.stringify(current.errors)) func run() -> void: var only:=OS.get_cmdline_user_args() for group in ["water","ice"]: for number in range(1,6): if not only.is_empty() and "%s%02d"%[group,number] not in only:continue await validate_scene(group,number) if is_instance_valid(app): root.remove_child(app) app.queue_free() await frames(3) var passed:=cases.filter(func(c):return c.errors.is_empty() and c.has("solved")).size() var report:={"engine":Engine.get_version_info().string,"physics_hz":Engine.physics_ticks_per_second,"passed":passed,"levels":cases} var path:=REPORT if only.is_empty() else "user://element_%s_report.json"%"_".join(only) DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(path.get_base_dir())) var file:=FileAccess.open(path,FileAccess.WRITE) file.store_string(JSON.stringify(report," ")) file.close() print("Element puzzle acceptance ",passed,"/",cases.size()) quit(0 if not cases.is_empty() and passed==cases.size() else 1)