UPDATE: The Importance of Classes in Object Oriented Programming
One issue I had when coding my various enemies was the MESS that sprite data made. At first, it wasn’t so bad, but as stuff compounded, it got harder and harder to read. Lines got soooo long, and most of the time stuff got cluttered.
Making classes really optimized my workflow! As an example, lets walk through some stuff I made
First, I realized the Enemy AND Player both used hitboxes and costumes. Therefore, I could conjoin them into one class that would have all essential variables and functions that I could pull from
class Creature {
costume : Sprite;
hitbox : Sprite;
anim_count: number = 0;
constructor (hitbox: Image, costume: Image, kind: number){
this.costume = sprites.create(costume, kind)
this.costume.setFlag(SpriteFlag.GhostThroughWalls, true)
this.hitbox = sprites.create(hitbox, SpriteKind.Hitbox)
this.hitbox.setFlag(SpriteFlag.Invisible, true)
}
add_animation(anim_arr: Array<Image>) {
adv_anim.attachAnim(this.costume, anim_arr, WALK_ANIM_TIME, this.anim_count)
this.anim_count += 1
}
}
It then makes making new classes easier! Sometimes, the player and enemy will have class specific variables that influence how it works, like an array that would display the enemies present in the program
Heres the enemy class, as an example
class Enemy extends Creature
{
static enemies : Enemy[] = [];
attacking : boolean = false;
direction : number = 0;
creature : number;
exhaustion : number = 0;
used_ability : number;
ability_cooldown : number = 200;
constructor(hitbox_img: Image, costume_img: Image, creature: Enemy.EnemyType)
{
super(hitbox_img, costume_img, SpriteKind.Enemy)
// Sets the appropriate AI
this.creature = creature
//
this.used_ability = this.ability_cooldown + game.runtime()
// Adds the new enemy to the enemies array
Enemy.enemies.push(this)
}
destroy()
{
for (let i = Enemy.enemies.length - 1; i >=0; i--)
{
if (Enemy.enemies[i] == this) Enemy.enemies.splice(i, i)
break;
}
sprites.destroy(this.costume)
sprites.destroy(this.hitbox)
}
/**
* TODO: Increases the Enemy
*/
increaseExhaustion(amt: number, double: boolean)
{
this.exhaustion += amt * (1 + Math.BoolToInt(double))
if (this.exhaustion > 100) this.exhaustion = 100
}
placeOnTile(loc: tiles.Location)
{
tiles.placeOnTile(this.hitbox, loc)
this.costume.setPosition(this.hitbox.x, this.hitbox.y)
}
}
Not only do classes help with programming, it also helps with readability! I’ll provide even more updates at some point :3