module hero::example {
use sui::balance::{Self, Balance};
use sui::coin::{Self, Coin};
use sui::sui::SUI;
/// Game character with attributes and inventory
public struct Hero has key, store {
id: UID,
game_id: ID,
health: u64,
experience: u64,
sword: Option<Sword>,
}
/// Weapon with magic and strength
public struct Sword has key, store {
id: UID,
game_id: ID,
magic: u64,
strength: u64,
}
/// Consumable healing item
public struct Potion has key, store {
id: UID,
game_id: ID,
potency: u64,
}
/// Enemy to fight
public struct Boar has key, store {
id: UID,
game_id: ID,
health: u64,
strength: u64,
}
/// Game state (shared object)
public struct Game has key {
id: UID,
payments: Balance<SUI>,
}
const MAX_HP: u64 = 1000;
const MAX_MAGIC: u64 = 10;
const MIN_SWORD_COST: u64 = 100;
/// Create a sword - payment determines magic level
public fun new_sword(
game: &mut Game,
payment: Coin<SUI>,
ctx: &mut TxContext
): Sword {
let value = payment.value();
assert!(value >= MIN_SWORD_COST, EInsufficientFunds);
coin::put(&mut game.payments, payment);
let magic = (value - MIN_SWORD_COST) / MIN_SWORD_COST;
Sword {
id: object::new(ctx),
magic: magic.min(MAX_MAGIC),
strength: 1,
game_id: object::id(game),
}
}
/// Create a hero with a sword
public fun new_hero(sword: Sword, ctx: &mut TxContext): Hero {
Hero {
id: object::new(ctx),
game_id: sword.game_id,
health: 100,
experience: 0,
sword: option::some(sword),
}
}
/// Heal hero with potion
public fun heal(hero: &mut Hero, potion: Potion) {
let Potion { id, potency, game_id } = potion;
id.delete();
assert!(hero.game_id == game_id, EWrongGame);
hero.health = (hero.health + potency).min(MAX_HP);
}
/// Equip sword to hero
public fun equip(hero: &mut Hero, sword: Sword) {
assert!(hero.sword.is_none(), EAlreadyEquipped);
hero.sword.fill(sword);
}
/// Remove sword from hero
public fun unequip(hero: &mut Hero): Sword {
assert!(hero.sword.is_some(), ENotEquipped);
option::extract(&mut hero.sword)
}
}