export class Character {
name: string = "";
health: number = 100;
constructor(name: string, health: number = 100) {
this.name = name;
this.health = health;
}
getName() : string {
return this.name;
}
getHealth() : number {
return this.health;
}
receiveDamage(damage: number) {
this.health = this.health - damage;
}
}
import { Character } from "./character";
export class Warrior extends Character {
weapon: string = "";
constructor(name: string, weapon: string, health: number = 100) {
super(name, health);
this.weapon = weapon;
}
getWeapon(): string {
return this.weapon;
}
receiveDamage(damage: number) {
const now = this.health;
this.health = now - (damage - damage * 0.1);
}
}
import { Character } from "./character";
import { Warrior } from "./warrior";
const character = new Character("NPC");
console.log(character.getName());
// NPC
console.log(character.getHealth());
// 100
// NOTE: Character has no armor can't reduce damage
character.receiveDamage(10);
console.log(character.getHealth());
// 90
const warrior = new Warrior("King Arthur", "Excalibur", 200);
console.log(warrior.getName());
// King Arthur
console.log(warrior.getHealth());
// 200
// NOTE: King Arthur has great weapon can reduce 10% of damage
warrior.receiveDamage(45);
console.log(warrior.getHealth());
// 159.5
console.log(warrior.getWeapon());
// Excalibur
# TypeScript Quiz — ข้อ 3 (1 คะแนน)
## 🎯 คำสั่ง
ให้นักเรียนสร้าง 2 class ได้แก่
- `Character` ในไฟล์ `character.ts` (parent class)
- `Warrior` ในไฟล์ `warrior.ts` (child class ที่ `extends Character`)
โดยต้องทำให้ไฟล์ `index.ts` ที่กำหนดให้ สามารถทำงานได้ถูกต้อง และได้ผลลัพธ์ตามที่คาดหวัง
ห้ามแก้ไขไฟล์ `index.ts`
## 📌 หมายเหตุสำคัญ
**ในไฟล์ `index.ts` มี comment (`//`) ที่แสดงตัวอย่างผลลัพธ์ที่คาดหวัง**
ให้นักเรียนอ่านผลลัพธ์จาก comment เหล่านั้น แล้วเขียน method logic ใน class ต่างๆ ให้สอดคล้องกับผลลัพธ์ที่แสดงไว้ ยกเว้น comment ที่เป็น NOTE
**ตัวอย่าง:**
```typescript
console.log(character.getName());
// NPC
จาก comment ด้านบน แสดงว่าผลลัพธ์ที่คาดหวังคือ "NPC" ดังนั้น method getName() ใน class Character ต้อง return ค่าในรูปแบบนี้
📁 โครงสร้างไฟล์ที่ต้องมี
p03/
├── character.ts
├── warrior.ts
└── index.ts
export class Character และ export class Warrior extends CharacterCharacter ต้องมี attribute name และ health
health มีค่าเริ่มต้นเป็น 100Character ต้องมี method:
getName()getHealth()receiveDamage(damage: number): ลดเลือดตาม damage ที่ได้รับWarrior ต้องมี constructor รับค่า name, weapon และ health (optional ใน parent แต่ warrior รับมา)Warrior ต้องมี attribute weapon และ method getWeapon()Warrior ต้อง override method receiveDamage(damage: number)
anyconsole.log ภายใน class