Assignment 4 Exam

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/31

encourage image

There's no tags or description

Looks like no tags are added yet.

32 Terms

1
New cards

Draw the inheritance structure of the classes your team created, starting from UObject.

UObject

├── UGameInstance ── URPGGameInstance

├── UVisual → UWidget → UUserWidget

│ ├── UBattleWidget (→ WBP_BattleHUD)

│ ├── UGameOverWidget (→ WBP_GameOver)

│ └── UPlayerStatsWidget (→ WBP_PlayerStats)

└── AActor

├── ABattleManager

├── APotionDelivered (win trigger)

├── APawn → ACharacter

│ ├── ARPGCharacter (player)

│ └── ARPGEnemy

└── AController → APlayerController

├── ABattlePlayerController (→ BP_BattlePlayerController)

└── AWorldPlayerController

Non-UObject types: FCombatStats (struct), EBattleResult (enum), EStatsSource (enum)

Blueprint-only: GM_Battle (GameModeBase), BP_Enemy

2
New cards

What is the relationship between your Actors and Components, and what do the components provide?

  • ARPGCharacter: the Capsule (root) gives collision and the overlap shape. The SkeletalMesh gives the visual. CharacterMovementComponent gives walking and rotation. The SpringArm (CameraBoom) is attached to the root and follows the controller’s rotation. The Camera is attached to the boom’s socket.

  • ARPGEnemy: the same Capsule, Mesh and CharacterMovementComponent, plus a SphereComponent (DetectionSphere) with the Trigger collision profile. It doesn’t block anything, it only fires overlap events, which is what starts a battle.

  • ABattleManager: it has no components. It’s a logic-only Actor that holds turn state and timers, so ticking is off.


3
New cards

What parts did you contribute to? Circle the one you contributed to most.

I built the player character (WASD movement via Enhanced Input, camera boom and follow camera) and the battle level. I wrote ABattleManager, the combat logic: Attack, Defend, Escape, enemy turn, damage math and win/lose/escape outcomes. I also worked on the hand-off between the world and the battle: saving and restoring the return position and tracking defeated enemies through the GameInstance. Circled: the battle system (ABattleManager).

4
New cards

What functionality is implemented in each Pawn’s constructor?

Constructors only create components and set defaults. Gameplay logic goes in BeginPlay.

  • Player (ACharacter subclass):

    • Enable tick.

    • Create the CameraBoom, attach it to the root, set TargetArmLength = 400 and bUsePawnControlRotation = true.

    • Create the FollowCamera, attach it to the boom’s socket, and set bUsePawnControlRotation = false because the boom already rotates.

    • Set bOrientRotationToMovement = true and RotationRate = (0, 540, 0) on the CharacterMovementComponent so the character turns toward its movement direction.

    • Set bUseControllerRotationYaw = false so the character doesn’t snap to camera yaw.

  • Enemy: create the DetectionSphere, attach it to the root and set its collision profile to Trigger. The radius is set later in BeginPlay from an exposed property.


5
New cards

How did you handle input in the battle level?

The battle player controller shows the cursor, sets FInputModeGameAndUI, and calls SetIgnoreMoveInput(true) and SetIgnoreLookInput(true). That stops anyone from walking around the battle scene. Hotkeys are handled by the widget.

6
New cards

Why did you use a GameInstance?

Unreal destroys the GameMode, PlayerController, Pawn and every Actor on a level load. The GameInstance lives from game launch until the game closes, so it is the only reliable place for data that crosses a level change. Everything else keeps only temporary state and asks the GameInstance for the rest.

7
New cards

What data did you persist, and why?

  • Player stats: HP, level and the combat stats must not reset between fights.

  • Player XP: progress toward the next level.

  • Enemy stats: the HUD and combat code both read the current enemy HP.

  • Active enemy ID: which enemy we’re fighting.

  • Defeated enemy IDs: a TSet<FName> so the world knows who’s gone.

  • Return location and rotation: so the player reappears where the fight started.

  • State flags: bBattleActive, bEscapeCooldown, bGameOver, bBattleXPAwarded.


8
New cards

How do you keep defeated enemies from reappearing?

Each placed enemy has a unique ID property. On victory, EndBattle adds the active enemy ID to DefeatedEnemyIDs. When the world map reloads, each enemy’s BeginPlay asks GI->IsEnemyDefeated(EnemyID) and calls Destroy() if true. IDs must be unique, because if two enemies shared one, beating either would remove both. Escaping doesn’t add the ID, so that enemy stays.

9
New cards

How do you return the player to where they were?

StartBattle stores the player’s location and rotation and sets bHasReturnTransform = true. When the world map loads, the character’s BeginPlay checks that the current map is the world map, then calls ConsumeReturnTransform(). If it returns true, the character calls SetActorLocationAndRotation(..., TeleportPhysics). “Consume” clears the flag so the position isn’t reused later.

10
New cards

What happens if the player is already in a battle or just escaped, and touches another enemy?

StartBattle begins with if (!CanStartBattle()) return;. CanStartBattle is !bBattleActive && !bEscapeCooldown. After an escape or enemy flee, a 3-second cooldown timer runs on the GameInstance’s own TimerManager. It’s on the GameInstance because an Actor’s timer would be destroyed with the level. This stops the player from instantly re-triggering the same enemy.

11
New cards

What happens to progress if the game is closed and reopened?

It’s lost. The GameInstance is in memory only, and Init() calls ResetGame(). We don’t save to disk. Persisting it would use a USaveGame subclass with SaveGameToSlot and LoadGameFromSlot.

12
New cards

How does an encounter get triggered?

The enemy has a sphere component with the Trigger profile (overlap, no blocking). In BeginPlay it sets the radius and binds OnComponentBeginOverlap to a handler. The handler checks !bIsDefeated, casts OtherActor to the player class (so other overlaps are ignored), gets the GameInstance, and calls StartBattle(EnemyID, EnemyStats, PlayerLocation, PlayerRotation).

13
New cards

Step by step, what happens from encounter to battle screen?

  1. The player overlaps the sphere and the handler runs.

  2. StartBattle is guarded by CanStartBattle.

  3. It sets bBattleActive, clears the per-fight flags, and stores the enemy ID.

  4. It copies the enemy’s stats, falling back to default stats if MaxHP is 0, then sets HP to max and level to 1.

  5. It saves the return transform.

  6. It calls OpenLevel(BattleLevel), and every Actor in the world map is destroyed.

  7. In the battle level, GM_Battle spawns no pawn and uses ABattlePlayerController.

  8. The controller’s BeginPlay finds the camera actor, calls SetViewTargetWithBlend, creates the HUD and adds it to the viewport.

  9. The HUD reads stats from the GameInstance and draws the bars.

  10. ABattleManager::BeginPlay caches the GameInstance and starts the player’s turn.


14
New cards

How does the game return to the world, and what differs by outcome?
ABattleManager calls GI->EndBattle(Result).

Result

Enemy defeated?

Other effects

Next

Victory

Yes, ID added to the defeated set

XP awarded once

Open world map

Escaped

No

3s escape cooldown

Open world map

EnemyFled

No

3s escape cooldown

Open world map

Defeat

No

TriggerGameOver fires the event

Stay in the battle level, show Game Over

Afterward, EndBattle resets bBattleXPAwarded, sets the enemy HP back to max and clears bBattleActive. That reset is what fixed the “second battle starts with enemy at 0 HP” bug.

15
New cards

How did you implement turn-based combat?

ABattleManager is an Actor with a bPlayerTurn flag. SetTurn(bool) sets it and broadcasts OnTurnChanged. Every player action starts with a guard: if (!GI || bIsBattleOver || !bPlayerTurn) return;. The action then calls SetTurn(false), resolves, and calls QueueEnemyTurn(). That sets a timer (EnemyTurnDelay, 1s) to run EnemyTurn(), so the player can read the log. The enemy turn ends with SetTurn(true) unless the battle ended.

16
New cards

Explain each player action in detail.

  • Attack:

    • Roll dodge: FRand() < clamp(EnemyEvasion × 0.05, 0, 0.75). On a miss, log it and queue the enemy turn.

    • Otherwise, damage = max(1, PlayerStrength − EnemyDefense × (enemyDefending ? 2 : 1)).

    • Clear bEnemyIsDefending, apply damage through the GameInstance, check for battle end, then queue the enemy turn.

  • Defend: set bIsDefending = true, log, queue the enemy turn. The flag doubles the player’s Defense on the next enemy attack.

  • Escape: FRand() < clamp(PlayerEvasion × 0.05, 0, 0.75) leads to FinishBattle(Escaped). Otherwise log “couldn’t escape” and the enemy gets a turn.


17
New cards

How does the enemy decide what to do?

Roll RandRange(1,100): 1–60 attack (60%), 61–85 defend (25%), 86–100 flee (15%).

  • Attack: save wasDefending, then clear bIsDefending. Roll the player’s dodge from Evasion. If it hits, damage = max(1, EnemyStrength − PlayerDefense × (wasDefending ? 2 : 1)). Apply damage, check for battle end, hand the turn back.

  • Defend: set bEnemyIsDefending so the player’s next attack faces doubled Defense.

  • Flee: FinishBattle(EnemyFled).


18
New cards

How does the battle end?

After every damage application, CheckBattleEnd() runs. It checks enemy HP ≤ 0 first (award XP, FinishBattle(Victory)), then player HP ≤ 0 (FinishBattle(Defeat)). FinishBattle is guarded by bIsBattleOver, so it only runs once. It stores the pending result, clears the enemy-turn timer, disables the player’s buttons with SetTurn(false), and starts a BattleEndDelay (3s) timer that calls CompleteBattle, which calls GI->EndBattle. Without the delay, the level would change on the same frame and the player would never see the final message or the level-up. XP is paid at the moment the enemy hits 0 for the same reason, and bBattleXPAwarded makes EndBattle’s call a no-op.

19
New cards

How does the UI stay in sync with game state without Tick?

Event-driven delegates. The GameInstance declares DECLARE_DYNAMIC_MULTICAST_DELEGATE events (OnPlayerHPChanged, OnEnemyHPChanged, OnPlayerStatsChanged, OnPlayerLevelUp, OnGameOver). Whenever data changes through a setter such as DamagePlayer, the setter updates the value and calls Broadcast. Widgets bind with AddUniqueDynamic in NativeConstruct, and handlers just set the progress bar percent and text. The data owner never knows the UI exists, and the UI never holds its own copy of the numbers.

20
New cards

How does C++ connect to a Widget Blueprint layout?

The C++ class declares members with UPROPERTY(meta=(BindWidget)). The Widget Blueprint is reparented to that class, and Unreal matches by exact name and type. A missing or misspelled widget fails to compile instead of silently doing nothing. BindWidgetOptional is used for non-essential widgets. The screenshot shows the Designer’s Bind Widgets panel with every entry green, meaning all names matched.

21
New cards

How is the HUD created in a given level?

The Game Mode picks the PlayerController class per level. GM_Battle in the battle level’s World Settings selects BP_BattlePlayerController. Its BeginPlay runs CreateWidget<UBattleWidget>(this, WidgetClass) and AddToViewport(). WidgetClass is a TSubclassOf set in the Blueprint. The widget class is a UPROPERTY on the controller because the controller owns UI for its player.

22
New cards

How did you implement leveling?

  • XP cost: XPToNext(L) = Base × Growth^(L−1), rounded (20, 30, 45, 68…).

  • AddXP: add the amount, then loop while (level < max && XP >= cost): subtract the cost (the remainder carries over), increment the level, add the per-level stat gains, and accumulate a “gained” struct. The loop handles one big award paying for several levels.

  • After the loop: heal (full heal is a tunable), broadcast the HP event so bars see the new max, then the stats-changed event, then the level-up event with the gains.

  • Tuning: all values (base, growth, per-level gains, max level) are EditDefaultsOnly on the GameInstance Blueprint, so rebalancing needs no recompile.


23
New cards

What happens on Game Over?

When EndBattle(Defeat) runs, the GameInstance calls TriggerGameOver(), which fires OnGameOver once (guarded by bGameOver). The battle controller, subscribed in BeginPlay, creates the Game Over widget at a high Z-order and switches to UI-only input. On Restart, the widget first sets the input mode back to game-only and hides the cursor. That’s needed because input mode belongs to the viewport and survives level changes, so otherwise the world loads but ignores input. It then calls RestartGame(), which saves the current stats, runs ResetGame(), optionally restores them, and opens the world map. ResetGame also clears the saved return transform, or the player would respawn next to the enemy that killed them.

24
New cards

What if the enemy sphere overlaps multiple times, or two enemies overlap at once?

The bBattleActive guard in StartBattle makes the second call return immediately, so only one battle opens.

25
New cards

Data structure matching cheat sheet

Data

Structure

In-game text

String Table

Designer meta information, UI dynamic data

Data Table

File management info, soft refs to binary data

Data Asset

Leveling function

Curve Table


26
New cards

The whole game loop

  1. Launch → GameInstance Init → ResetGame (default stats)

  2. World map loads → character BeginPlay (consume return transform, add input context)

  3. Player walks → enemy patrols

  4. Overlap enemy sphere → StartBattle

  5. Battle level loads → battle controller builds HUD, fixes camera, ignores movement

  6. Turn loop until a result

  7. EndBattle(Result) → branch (victory/escape/flee → world; defeat → Game Over)

  8. World reloads → defeated enemies self-destroy, player teleported back

  9. Reach goal → win screen


27
New cards

One round of combat flow

  1. Player acts (button or hotkey)

  2. SetTurn(false) → buttons disable (event)

  3. Resolve action (dodge roll → damage → apply through GameInstance)

  4. GameInstance clamps HP and broadcasts → bars update

  5. CheckBattleEnd → if over, FinishBattle

  6. Otherwise, timer → EnemyTurn → roll action → resolve → CheckBattleEnd

  7. SetTurn(true) → buttons re-enable


28
New cards

Level transition (persistence) flow

write needed data to GameInstance → OpenLevel → old world destroyed → new world’s BeginPlays read from GameInstance

29
New cards

Turn flow pseudocode

Action():

if !GI or battleOver or !playerTurn: return

SetTurn(false)

resolve...

if CheckBattleEnd(): return

SetTimer(EnemyTurn, delay)

SetTurn(b): bPlayerTurn = b; OnTurnChanged.Broadcast(b)

FinishBattle(R):

if battleOver: return

battleOver = true; Pending = R

ClearTimer(EnemyTurn); SetTurn(false)

SetTimer(Complete, EndDelay) // Complete → GI.EndBattle(Pending)

30
New cards

Damage and dodge pseudocode

Dodge = FRand() < Clamp(Evasion * 0.05, 0, 0.75)

Damage = Max(1, AttackerStrength - DefenderDefense * (defending ? 2 : 1))

31
New cards

Enemy AI pseudocode

roll = RandRange(1,100)

if roll <= 60: Attack

elif roll <= 85: Defend

else: Flee

32
New cards

Game over/restart pseudocode

TriggerGameOver(): if bGameOver return; bGameOver = true; OnGameOver.Broadcast()

OnRestartClicked(): GI.RestartGame()

RestartGame(): ResetGame(); OpenLevel(World)