Skip to content

Instantly share code, notes, and snippets.

@alidinc
Created August 27, 2025 12:53
Show Gist options
  • Select an option

  • Save alidinc/4f36d1b3814727850d2e637d1ebeb1fa to your computer and use it in GitHub Desktop.

Select an option

Save alidinc/4f36d1b3814727850d2e637d1ebeb1fa to your computer and use it in GitHub Desktop.
import Foundation
enum Slot: CaseIterable {
case black, green, white, yellow
static func random() -> Slot {
Slot.allCases.randomElement()!
}
var description: String {
switch self {
case .black:
return "⚫️"
case .green:
return "🟢"
case .white:
return "⚪️"
case .yellow:
return "🟡"
}
}
}
class FruitPlayer {
var money: Int
var freePlay = 0
init(money: Int) {
self.money = money
}
func canPlay(cost: Int) -> Bool {
money >= cost || freePlay > 0
}
func pay(cost: Int) {
if freePlay > 0 {
freePlay -= 1
} else {
money -= cost
}
}
// winning
func addWinning(amount: Int) {
money += amount
}
// freeplay
func addFreeplay(count: Int) {
freePlay += count
}
}
class FruitMachine {
var float: Int
var playCost: Int
init(float: Int, playCost: Int) {
self.float = float
self.playCost = playCost
}
func play(player: FruitPlayer) {
// check if we can play
guard player.canPlay(cost: playCost) else {
print("Not enough money!")
return
}
print("We can play!...")
player.pay(cost: playCost)
print("Player paid \(playCost)")
float += playCost
print("Machine has now \(float) float")
let slots = (0..<4).map { _ in Slot.random() }
print("Slots: \(slots.map { $0.description })")
if slots.allSatisfy({ $0 == slots.first }) {
handleFreePlays(prize: float, player: player)
player.addWinning(amount: float)
float = 0
print("Player won: \(float)")
} else if Set(slots).count == 4 {
let prize = float / 2
float -= prize
handleFreePlays(prize: prize, player: player)
player.addWinning(amount: prize)
print("Player won: \(prize)")
} else if hasAdjacent(for: slots) {
let prize = playCost * 5
float -= prize
handleFreePlays(prize: prize, player: player)
player.addWinning(amount: prize)
print("Player won: \(prize)")
print("")
}
print("The machine has now \(float) money")
}
private func handleFreePlays(prize: Int, player: FruitPlayer) {
if float < prize {
let shortfall = float - prize
let freeplays = shortfall / playCost
player.addFreeplay(count: freeplays)
print("We have got freeplay \(freeplays)")
}
}
private func hasAdjacent(for slots: [Slot]) -> Bool {
for i in 0..<(slots.count - 1) {
if slots[i] == slots[i+1] {
return true
}
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment