/// Our hero!
struct Hero has key, store {
id: UID,
/// Hit points. If they go to zero, the hero can't do anything
hp: u64,
/// Experience of the hero. Begins at zero
experience: u64,
/// The hero's minimal inventory
sword: Option<Sword>,
/// An ID of the game user is playing
game_id: ID,
}
/// The hero's trusty sword
struct Sword has key, store {
id: UID,
/// Constant set at creation. Acts as a multiplier on sword's strength.
/// Swords with high magic are rarer (because they cost more).
magic: u64,
/// Sword grows in strength as we use it
strength: u64,
/// An ID of the game
game_id: ID,
}
/// A creature that the hero can slay to level up
struct Boar has key {
id: UID,
/// Hit points before the boar is slain
hp: u64,
/// Strength of this particular boar
strength: u64,
/// An ID of the game
game_id: ID,
}
/// Slay the `boar` with the `hero`'s sword, get experience.
/// Aborts if the hero has 0 HP or is not strong enough to slay the boar
public entry fun slay(
game: &GameInfo, hero: &mut Hero, boar: Boar, ctx: &TxContext
) {
check_id(game, hero.game_id);
check_id(game, boar.game_id);
let Boar { id: boar_id, strength: boar_strength, hp, game_id: _ } = boar;
let hero_strength = hero_strength(hero);
let boar_hp = hp;
let hero_hp = hero.hp;
// attack the boar with the sword until its HP goes to zero
while (boar_hp > hero_strength) {
// first, the hero attacks
boar_hp = boar_hp - hero_strength;
// then, the boar gets a turn to attack. if the boar would kill
// the hero, abort--we can't let the boar win!
assert!(hero_hp >= boar_strength , EBOAR_WON);
hero_hp = hero_hp - boar_strength;
};
// hero takes their licks
hero.hp = hero_hp;
// hero gains experience proportional to the boar, sword grows in
// strength by one (if hero is using a sword)
hero.experience = hero.experience + hp;
if (option::is_some(&hero.sword)) {
level_up_sword(option::borrow_mut(&mut hero.sword), 1)
};
// let the world know about the hero's triumph by emitting an event!
event::emit(BoarSlainEvent {
slayer_address: tx_context::sender(ctx),
hero: object::uid_to_inner(&hero.id),
boar: object::uid_to_inner(&boar_id),
game_id: id(game)
});
object::delete(boar_id);
}
【免责声明】市场有风险,投资需谨慎。本文不构成投资建议,用户应考虑本文中的任何意见、观点或结论是否符合其特定状况。据此投资,责任自负。