Skip to content

Instantly share code, notes, and snippets.

@webuniverseio
Last active July 21, 2022 16:45
Show Gist options
  • Save webuniverseio/083b6cdfab4f6f698eb83236950a57b8 to your computer and use it in GitHub Desktop.
Save webuniverseio/083b6cdfab4f6f698eb83236950a57b8 to your computer and use it in GitHub Desktop.
Swift class based fighting game
import Foundation
class Dragon: Enemy {
let wings = 2
override var type: String {
"Dragon"
}
override init(strength: Int) {
super.init(strength: strength * 2)
}
override func move() {
print("\(type) flies forward.")
}
}
import Foundation
class Enemy {
var type: String {
get {
"Enemy"
}
}
private(set) var health: Int = 100
private let strength: Int
init(strength: Int) {
self.strength = strength
print("A \(type) was born.")
}
init(strength: Int, healthBoost: Int) {
health += healthBoost
self.strength = strength
print("A \(type) was born.")
}
func attack(_ x : Enemy) {
if (Bool.random()) {
print("\(type) hits \(x.type).")
x.setDamage(strength)
} else {
print( Bool.random() ? "\(type) missed." : "\(x.type) dodged.")
}
}
private func setDamage(_ x: Int) {
health -= x
if (health <= 0) {
health = 0
print("\(type) is dead.")
} else {
print("\(type) takes \(x) damage.")
}
}
func move() {
print("\(type) walks forward.")
}
}
let e1 = Skeleton(strength: Int.random(in: 5..<50))
let e2 = Dragon(strength: Int.random(in: 7..<50))
e1.move()
e2.move()
while e1.health != 0 && e2.health != 0 {
e1.attack(e2)
if (e2.health != 0) {
e2.attack(e1)
}
print()
}
import Foundation
class Skeleton: Enemy {
override var type: String {
"Skeleton"
}
override init(strength: Int) {
super.init(strength: strength, healthBoost: 100)
}
override func move() {
print("\(type) crawls forward.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment