-refactor: apply rider suggested changes to codebase

This commit is contained in:
rsxri 2025-04-19 23:33:53 +01:00
parent 4c561f7e02
commit 15ed109daf
5 changed files with 117 additions and 122 deletions

View file

@ -8,7 +8,7 @@ public partial class Laser : Area2D
public ship Shooter; public ship Shooter;
public Vector2 MovementVector { get; set; } = new Vector2(0, -1); private Vector2 MovementVector { get; set; } = new Vector2(0, -1);
private void _on_visible_on_screen_notifier_2d_screen_exited() private void _on_visible_on_screen_notifier_2d_screen_exited()
@ -26,10 +26,9 @@ public partial class Laser : Area2D
} }
private void OnAreaEntered(Area2D area) private void OnAreaEntered(Area2D area)
{ {
if (area is asteroid) if (area is asteroid asteroid)
{ {
asteroid a = (asteroid)area; asteroid.Explode();
a.Explode();
QueueFree(); QueueFree();
} }
} }
@ -56,7 +55,6 @@ public partial class Laser : Area2D
{ {
GD.Print("friendly fire"); GD.Print("friendly fire");
QueueFree(); QueueFree();
return; // prevent friendly fire
} }
else else
{ {

View file

@ -11,24 +11,24 @@ public partial class ai_fighter : ship
[Export] [Export]
public float EngageDistance = 300f; public float EngageDistance = 300f;
private Label HealthLabel; private Label _healthLabel;
private Label HPLabel; private Label _hpLabel;
//retreat logic //retreat logic
private float previousDistance = 0f; private float _previousDistance;
private float stuckTime = 0f; private float _stuckTime;
private const float stuckThreshold = 0.5f; private const float StuckThreshold = 0.5f;
private const float distanceTolerance = 5f; private const float DistanceTolerance = 5f;
private Node2D currentTarget; private Node2D _currentTarget;
public override void _Ready() public override void _Ready()
{ {
SetShipStats(); SetShipStats();
SetupVisual(); SetupVisual();
Sprite.Texture = GD.Load<Texture2D>(spritePath); Sprite.Texture = GD.Load<Texture2D>(SpritePath);
HealthLabel = GetNode<Label>("HealthDisplay/HealthLabel"); _healthLabel = GetNode<Label>("HealthDisplay/HealthLabel");
UpdateHealthLabel(Health); UpdateHealthLabel(Health);
LaserSpawn = GetNode<Node2D>("LaserSpawn"); LaserSpawn = GetNode<Node2D>("LaserSpawn");
@ -37,7 +37,7 @@ public partial class ai_fighter : ship
public override void _Process(double delta) public override void _Process(double delta)
{ {
base._Process(delta); base._Process(delta);
HealthLabel.GetParent<Node2D>().GlobalRotation = 0f; _healthLabel.GetParent<Node2D>().GlobalRotation = 0f;
} }
public override void _PhysicsProcess(double delta) public override void _PhysicsProcess(double delta)
@ -55,10 +55,10 @@ public partial class ai_fighter : ship
private void UpdateHealthLabel(int health) private void UpdateHealthLabel(int health)
{ {
HealthLabel.Text = health.ToString(); _healthLabel.Text = health.ToString();
float percentage = (float)Health / MaxHealth; float percentage = (float)Health / MaxHealth;
HealthLabel.Modulate = percentage switch _healthLabel.Modulate = percentage switch
{ {
<= 0.25f => new Color(1f, 0f, 0f), <= 0.25f => new Color(1f, 0f, 0f),
<= 0.5f => new Color(1f, 0.5f, 0f), <= 0.5f => new Color(1f, 0.5f, 0f),
@ -81,16 +81,16 @@ public partial class ai_fighter : ship
fireTimer -= (float)delta; // countdown to next shot available FireTimer -= (float)delta; // countdown to next shot available
if (fireTimer > 0f) return; // if countdown not finished then no shoot if (FireTimer > 0f) return; // if countdown not finished then no shoot
if (currentTarget == null || !IsInstanceValid(currentTarget)) return; // checks for valid target, returns if not if (_currentTarget == null || !IsInstanceValid(_currentTarget)) return; // checks for valid target, returns if not
// determining direction and distance to target // determining direction and distance to target
Vector2 toTarget = (currentTarget.GlobalPosition - GlobalPosition).Normalized(); Vector2 toTarget = (_currentTarget.GlobalPosition - GlobalPosition).Normalized();
float angleToTarget = toTarget.Angle() + Mathf.Pi / 2; float angleToTarget = toTarget.Angle() + Mathf.Pi / 2;
float angleDiff = Mathf.Abs(Mathf.AngleDifference(Rotation, angleToTarget)); float angleDiff = Mathf.Abs(Mathf.AngleDifference(Rotation, angleToTarget));
float distance = GlobalPosition.DistanceTo(currentTarget.GlobalPosition); float distance = GlobalPosition.DistanceTo(_currentTarget.GlobalPosition);
//GD.Print(Name, ": angleDiff = ", Mathf.RadToDeg(angleDiff)); //GD.Print(Name, ": angleDiff = ", Mathf.RadToDeg(angleDiff));
@ -99,7 +99,7 @@ public partial class ai_fighter : ship
//GD.Print(Name, ": angleDiff = ", angleDiff, ", distance = ", distance); //GD.Print(Name, ": angleDiff = ", angleDiff, ", distance = ", distance);
ShootLaser(); ShootLaser();
fireTimer = FireCooldown; // resets cooldown FireTimer = FireCooldown; // resets cooldown
} }
} }
@ -126,7 +126,7 @@ public partial class ai_fighter : ship
foreach (Node node in shipParent.GetChildren()) foreach (Node node in shipParent.GetChildren())
{ {
if (node is ship target && target.Health > 0) if (node is ship { Health: > 0 } target)
{ {
float dist = GlobalPosition.DistanceTo(target.GlobalPosition); float dist = GlobalPosition.DistanceTo(target.GlobalPosition);
if (dist < closestDistance) if (dist < closestDistance)
@ -141,9 +141,9 @@ public partial class ai_fighter : ship
private bool EnsureTarget() // finds a new target if no current or if invalid (dead) private bool EnsureTarget() // finds a new target if no current or if invalid (dead)
{ {
if (currentTarget == null || !IsInstanceValid(currentTarget)) if (_currentTarget == null || !IsInstanceValid(_currentTarget))
{ {
currentTarget = FindClosestTarget(); _currentTarget = FindClosestTarget();
return false; return false;
} }
return true; return true;
@ -151,15 +151,15 @@ public partial class ai_fighter : ship
private void UpdateDistanceTracking(float distance) // tracks how long AI has been stuck in same spot private void UpdateDistanceTracking(float distance) // tracks how long AI has been stuck in same spot
{ {
if (MathF.Abs(distance - previousDistance) < distanceTolerance) if (MathF.Abs(distance - _previousDistance) < DistanceTolerance)
{ {
stuckTime += (float)GetProcessDeltaTime(); _stuckTime += (float)GetProcessDeltaTime();
} }
else else
{ {
stuckTime = 0f; _stuckTime = 0f;
} }
previousDistance = distance; _previousDistance = distance;
} }
private void HandleThrust(float angleDiff, float distance) private void HandleThrust(float angleDiff, float distance)
@ -177,10 +177,10 @@ public partial class ai_fighter : ship
} }
else if (distance < retreatThreshold) else if (distance < retreatThreshold)
{ {
if (stuckTime > stuckThreshold) if (_stuckTime > StuckThreshold)
{ {
// reposition if stuck // reposition if stuck
Vector2 away = (GlobalPosition - currentTarget.GlobalPosition).Normalized(); Vector2 away = (GlobalPosition - _currentTarget.GlobalPosition).Normalized();
Velocity += away * MainSpeed; Velocity += away * MainSpeed;
} }
else else
@ -207,10 +207,10 @@ public partial class ai_fighter : ship
if (!EnsureTarget()) return; // skip if no valid target if (!EnsureTarget()) return; // skip if no valid target
// math for direction, distance and rotation // math for direction, distance and rotation
Vector2 direction = (currentTarget.GlobalPosition - GlobalPosition).Normalized(); Vector2 direction = (_currentTarget.GlobalPosition - GlobalPosition).Normalized();
float angleToTarget = direction.Angle() + MathF.PI / 2; float angleToTarget = direction.Angle() + MathF.PI / 2;
float angleDiff = Mathf.AngleDifference(Rotation, angleToTarget); float angleDiff = Mathf.AngleDifference(Rotation, angleToTarget);
float distance = GlobalPosition.DistanceTo(currentTarget.GlobalPosition); float distance = GlobalPosition.DistanceTo(_currentTarget.GlobalPosition);
UpdateDistanceTracking(distance); UpdateDistanceTracking(distance);
HandleThrust(angleDiff, distance); HandleThrust(angleDiff, distance);

View file

@ -3,48 +3,48 @@ using System;
public partial class game : Node2D public partial class game : Node2D
{ {
public Node Lasers; private Node _lasers;
public CharacterBody2D Player; private CharacterBody2D _player;
public Node Asteroids; private Node _asteroids;
public Node Friendlies; private Node _friendlies;
public Node Enemies; private Node _enemies;
public Node Ships; private Node _ships;
public Control HUD; private Control _hud;
public Label ScoreLabel; private Label _scoreLabel;
public Label HealthLabel; private Label _healthLabel;
public Label FlightAssistLabel; private Label _flightAssistLabel;
public hud H; private hud _h;
private readonly PackedScene _asteroidScene = GD.Load<PackedScene>("res://scenes/asteroid.tscn"); private readonly PackedScene _asteroidScene = GD.Load<PackedScene>("res://scenes/asteroid.tscn");
public int Score = 0; private int _score;
public override void _Ready() public override void _Ready()
{ {
HUD = GetNode<Control>("UI/HUD"); _hud = GetNode<Control>("UI/HUD");
ScoreLabel = GetNode<Label>("UI/HUD/Score"); _scoreLabel = GetNode<Label>("UI/HUD/Score");
FlightAssistLabel = GetNode<Label>("UI/HUD/FlightAssist"); _flightAssistLabel = GetNode<Label>("UI/HUD/FlightAssist");
//HealthLabel = GetNode<Label>("UI/HUD/Health"); //HealthLabel = GetNode<Label>("UI/HUD/Health");
Asteroids = GetNode<Node>("Asteroids"); _asteroids = GetNode<Node>("Asteroids");
Lasers = GetNode<Node>("Lasers"); _lasers = GetNode<Node>("Lasers");
Ships = GetNode<Node>("Ships"); _ships = GetNode<Node>("Ships");
Enemies = GetNode<Node>("Ships/Enemy"); _enemies = GetNode<Node>("Ships/Enemy");
Friendlies = GetNode<Node>("Ships/Friendly"); _friendlies = GetNode<Node>("Ships/Friendly");
Player = GetNode<CharacterBody2D>("Ships/Friendly/Player"); _player = GetNode<CharacterBody2D>("Ships/Friendly/Player");
//AI fighter signals //AI fighter signals
foreach (Node node in Enemies.GetChildren()) foreach (Node node in _enemies.GetChildren())
{ {
if (node is ai_fighter ai) if (node is ai_fighter ai)
{ {
@ -54,7 +54,7 @@ public partial class game : Node2D
} }
} }
foreach (Node node in Friendlies.GetChildren()) foreach (Node node in _friendlies.GetChildren())
{ {
if (node is player) continue; if (node is player) continue;
@ -83,7 +83,7 @@ public partial class game : Node2D
} }
//AUTO SPAWN AFTER CLEAR //AUTO SPAWN AFTER CLEAR
if (Asteroids.GetChildCount() == 0) if (_asteroids.GetChildCount() == 0)
{ {
Random rand = new Random(); Random rand = new Random();
for (int i = 0; i < rand.Next(1, 5); i++) for (int i = 0; i < rand.Next(1, 5); i++)
@ -93,61 +93,58 @@ public partial class game : Node2D
} }
} }
public void SpawnAsteroid(Vector2 position, int size) private void SpawnAsteroid(Vector2 position, int size)
{ {
var a = new asteroid(); var a = new asteroid();
a = _asteroidScene.Instantiate<asteroid>(); a = _asteroidScene.Instantiate<asteroid>();
a.GlobalPosition = position; a.GlobalPosition = position;
a.Size = (asteroid.AsteroidSize)size; a.Size = (asteroid.AsteroidSize)size;
a.Exploded += OnAsteroidExploded; a.Exploded += OnAsteroidExploded;
Asteroids.CallDeferred("add_child", a); _asteroids.CallDeferred("add_child", a);
} }
public void UpdateScoreLabel(int score) private void UpdateScoreLabel(int score)
{ {
/*var h = new hud(); /*var h = new hud();
GD.Print(h.Score); GD.Print(h.Score);
h.Score.Text = "SCORE: " + score.ToString(); h.Score.Text = "SCORE: " + score.ToString();
GD.Print(h.Score.Text);*/ GD.Print(h.Score.Text);*/
ScoreLabel.Text = "SCORE: " + score.ToString(); _scoreLabel.Text = "SCORE: " + score.ToString();
} }
public void UpdateHealthLabel(int health) private void UpdateHealthLabel(int health)
{ {
if (HealthLabel == null) _healthLabel ??= GetNode<Label>("UI/HUD/Health");
{ _healthLabel.Text = "HEALTH: " + health.ToString();
HealthLabel = GetNode<Label>("UI/HUD/Health");
}
HealthLabel.Text = "HEALTH: " + health.ToString();
} }
public void UpdateFALabel() private void UpdateFALabel()
{ {
// Bit of a hacky implementation I think, but it works. // Bit of a hacky implementation I think, but it works.
if (FlightAssistLabel.Text == "FA: OFF"){FlightAssistLabel.Text = "FA: ON";} if (_flightAssistLabel.Text == "FA: OFF"){_flightAssistLabel.Text = "FA: ON";}
else if (FlightAssistLabel.Text == "FA: ON"){FlightAssistLabel.Text = "FA: OFF";} else if (_flightAssistLabel.Text == "FA: ON"){_flightAssistLabel.Text = "FA: OFF";}
} }
//Signals and Connections //Signals and Connections
public void OnAILaserShot(Area2D Laser) private void OnAILaserShot(Area2D laser)
{ {
Lasers.AddChild(Laser); _lasers.AddChild(laser);
} }
public void OnPlayerLaserShot(Area2D laser) private void OnPlayerLaserShot(Area2D laser)
{ {
Lasers.AddChild(laser); _lasers.AddChild(laser);
GD.Print(laser.Position); GD.Print(laser.Position);
GD.Print(Player.Position); GD.Print(_player.Position);
} }
public void OnPlayerHealthUpdate(int health) private void OnPlayerHealthUpdate(int health)
{ {
UpdateHealthLabel(health); UpdateHealthLabel(health);
} }
public void OnPlayerDeath() private void OnPlayerDeath()
{ {
CallDeferred(nameof(SafeReloadScene)); //Reload scene to act as restart CallDeferred(nameof(SafeReloadScene)); //Reload scene to act as restart
} }
@ -158,7 +155,7 @@ public partial class game : Node2D
GetTree().ReloadCurrentScene(); GetTree().ReloadCurrentScene();
} }
public void OnAsteroidExploded(Vector2 pos, int size) private void OnAsteroidExploded(Vector2 pos, int size)
{ {
// DEBUG PRINT // DEBUG PRINT
GD.Print($"DEBUG: Asteroid exploded at {pos}, size: {size}"); GD.Print($"DEBUG: Asteroid exploded at {pos}, size: {size}");
@ -167,21 +164,21 @@ public partial class game : Node2D
for (int i = 0; i < 2; i++){ for (int i = 0; i < 2; i++){
SpawnAsteroid(pos, (int)asteroid.AsteroidSize.MEDIUM); SpawnAsteroid(pos, (int)asteroid.AsteroidSize.MEDIUM);
} }
Score += 60; _score += 60;
} }
else if (size == 1) else if (size == 1)
{ {
for (int i = 0; i < 2; i++){ for (int i = 0; i < 2; i++){
SpawnAsteroid(pos, (int)asteroid.AsteroidSize.SMALL); SpawnAsteroid(pos, (int)asteroid.AsteroidSize.SMALL);
} }
Score += 40; _score += 40;
} }
else if (size == 2) else if (size == 2)
{ {
Score += 20; _score += 20;
} }
GD.Print(Score); GD.Print(_score);
UpdateScoreLabel(Score); UpdateScoreLabel(_score);
} }
} }

View file

@ -66,15 +66,15 @@ public partial class player : ship // Inherits from base ship class
SetupVisual(); SetupVisual();
GD.Print(Faction); GD.Print(Faction);
this.spritePath = Color switch this.SpritePath = Color switch
{ {
ShipColor.RED => this.spritePath + "ShipRed.png", ShipColor.RED => this.SpritePath + "ShipRed.png",
ShipColor.GREEN => this.spritePath + "ShipGreen.png", ShipColor.GREEN => this.SpritePath + "ShipGreen.png",
ShipColor.BLUE => this.spritePath + "ShipBlue.png", ShipColor.BLUE => this.SpritePath + "ShipBlue.png",
_ => this.spritePath _ => this.SpritePath
}; };
GD.Print(spritePath); GD.Print(SpritePath);
Sprite.Texture = GD.Load<Texture2D>(spritePath); Sprite.Texture = GD.Load<Texture2D>(SpritePath);
LaserSpawn = GetNode<Node2D>("LaserSpawn"); LaserSpawn = GetNode<Node2D>("LaserSpawn");
@ -86,13 +86,13 @@ public partial class player : ship // Inherits from base ship class
public override void _Process(double delta) public override void _Process(double delta)
{ {
fireTimer -= (float)delta; FireTimer -= (float)delta;
if(Input.IsActionPressed("shoot")) if(Input.IsActionPressed("shoot"))
{ {
if (fireTimer > 0f) return; if (FireTimer > 0f) return;
ShootLaser(); ShootLaser();
fireTimer = FireCooldown; FireTimer = FireCooldown;
} }
} }

View file

@ -7,7 +7,7 @@ public partial class ship : CharacterBody2D
public enum ShipFaction {PLAYER, FRIENDLY, ENEMY, ACE} public enum ShipFaction {PLAYER, FRIENDLY, ENEMY, ACE}
[Signal] [Signal]
public delegate void LaserShotEventHandler(Area2D Laser); public delegate void LaserShotEventHandler(Area2D laser);
//[Export] //[Export]
//public Vector2 ScreenSize; //public Vector2 ScreenSize;
@ -28,23 +28,23 @@ public partial class ship : CharacterBody2D
[Export] [Export]
public float FireCooldown { get; set; } public float FireCooldown { get; set; }
[Export] [Export]
public ShipType type; public ShipType Type;
[Export] [Export]
public ShipFaction Faction; public ShipFaction Faction;
public Sprite2D Sprite = new Sprite2D(); protected Sprite2D Sprite = new Sprite2D();
public Node2D LaserSpawn = null; protected Node2D LaserSpawn;
protected float fireTimer = 0f; protected float FireTimer = 0f;
public string spritePath = ""; protected string SpritePath;
protected int RotationDirection; protected int RotationDirection;
protected readonly PackedScene LaserScene = GD.Load<PackedScene>("res://scenes/laser.tscn"); protected readonly PackedScene LaserScene = GD.Load<PackedScene>("res://scenes/laser.tscn");
public virtual void ShootLaser() protected virtual void ShootLaser()
{ {
//GD.Print(Name, ": firing laser"); //GD.Print(Name, ": firing laser");
@ -58,74 +58,74 @@ public partial class ship : CharacterBody2D
protected virtual void SetupVisual() protected virtual void SetupVisual()
{ {
Sprite = GetNode<Sprite2D>("ShipSprite"); Sprite = GetNode<Sprite2D>("ShipSprite");
spritePath = ""; // Have to initialise as "" because of switch statements SpritePath = ""; // Have to initialise as "" because of switch statements
if (Faction == ShipFaction.PLAYER) if (Faction == ShipFaction.PLAYER)
{ {
switch (type) switch (Type)
{ {
case ShipType.FIGHTER: case ShipType.FIGHTER:
spritePath = "res://assets/Ships/Fighters/Player/Fighter/"; SpritePath = "res://assets/Ships/Fighters/Player/Fighter/";
break; break;
case ShipType.INTERCEPTOR: case ShipType.INTERCEPTOR:
spritePath = "res://assets/Ships/Fighters/Player/Interceptor/"; SpritePath = "res://assets/Ships/Fighters/Player/Interceptor/";
break; break;
case ShipType.GUARDIAN: case ShipType.GUARDIAN:
spritePath = "res://assets/Ships/Fighters/Player/Guardian/"; SpritePath = "res://assets/Ships/Fighters/Player/Guardian/";
break; break;
} }
} }
else if (Faction == ShipFaction.FRIENDLY) else if (Faction == ShipFaction.FRIENDLY)
{ {
switch (type) switch (Type)
{ {
case ShipType.FIGHTER: case ShipType.FIGHTER:
spritePath = "res://assets/Ships/Fighters/Friendly/friendlyFighter.png/"; SpritePath = "res://assets/Ships/Fighters/Friendly/friendlyFighter.png/";
break; break;
case ShipType.INTERCEPTOR: case ShipType.INTERCEPTOR:
spritePath = "res://assets/Ships/Fighters/Friendly/friendlyInterceptor.png/"; SpritePath = "res://assets/Ships/Fighters/Friendly/friendlyInterceptor.png/";
break; break;
case ShipType.GUARDIAN: case ShipType.GUARDIAN:
spritePath = "res://assets/Ships/Fighters/Friendly/friendlyGuardian.png/"; SpritePath = "res://assets/Ships/Fighters/Friendly/friendlyGuardian.png/";
break; break;
} }
} }
else if (Faction == ShipFaction.ENEMY) else if (Faction == ShipFaction.ENEMY)
{ {
switch (type) switch (Type)
{ {
case ShipType.FIGHTER: case ShipType.FIGHTER:
spritePath = "res://assets/Ships/Fighters/Enemy/enemyFighter.png/"; SpritePath = "res://assets/Ships/Fighters/Enemy/enemyFighter.png/";
break; break;
case ShipType.INTERCEPTOR: case ShipType.INTERCEPTOR:
spritePath = "res://assets/Ships/Fighters/Enemy/enemyInterceptor.png/"; SpritePath = "res://assets/Ships/Fighters/Enemy/enemyInterceptor.png/";
break; break;
case ShipType.GUARDIAN: case ShipType.GUARDIAN:
spritePath = "res://assets/Ships/Fighters/Enemy/enemyGuardian.png/"; SpritePath = "res://assets/Ships/Fighters/Enemy/enemyGuardian.png/";
break; break;
} }
} }
else if (Faction == ShipFaction.ACE) else if (Faction == ShipFaction.ACE)
{ {
switch (type) switch (Type)
{ {
case ShipType.FIGHTER: case ShipType.FIGHTER:
spritePath = "res://assets/Ships/Fighters/Ace/aceFighter.png/"; SpritePath = "res://assets/Ships/Fighters/Ace/aceFighter.png/";
break; break;
case ShipType.INTERCEPTOR: case ShipType.INTERCEPTOR:
spritePath = "res://assets/Ships/Fighters/Ace/aceInterceptor.png/"; SpritePath = "res://assets/Ships/Fighters/Ace/aceInterceptor.png/";
break; break;
case ShipType.GUARDIAN: case ShipType.GUARDIAN:
spritePath = "res://assets/Ships/Fighters/Ace/aceGuardian.png/"; SpritePath = "res://assets/Ships/Fighters/Ace/aceGuardian.png/";
break; break;
} }
} }
@ -138,10 +138,10 @@ public partial class ship : CharacterBody2D
Sprite.RotationDegrees = 0; Sprite.RotationDegrees = 0;
} }
} }
public void SetShipStats() protected void SetShipStats()
{ {
switch (type) switch (Type)
{ {
case ShipType.FIGHTER: case ShipType.FIGHTER:
Health = 100; Health = 100;
@ -188,7 +188,7 @@ public partial class ship : CharacterBody2D
GD.Print(Name, " health: ", Health); GD.Print(Name, " health: ", Health);
} }
public virtual void Explode() protected virtual void Explode()
{ {
GD.Print(Name, " exploded"); GD.Print(Name, " exploded");
QueueFree(); QueueFree();