Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
broody committed Sep 9, 2023
1 parent 90ec176 commit 5263c14
Show file tree
Hide file tree
Showing 40 changed files with 460 additions and 523 deletions.
4 changes: 3 additions & 1 deletion src/components/player.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ struct Player {
game_id: u32,
#[key]
player_id: ContractAddress,
status: PlayerStatus,
location_id: felt252,
cash: u128,
health: u8,
drug_count: usize,
bag_limit: usize,
turns_remaining: usize,
status: PlayerStatus,
}

#[generate_trait]
Expand Down
8 changes: 1 addition & 7 deletions src/components/risks.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@ use debug::PrintTrait;

use rollyourown::constants::SCALING_FACTOR;

#[derive(Drop, Copy)]
struct TravelResult {
arrested: bool,
mugged: bool,
health_loss: u8,
}

#[derive(Component, Copy, Drop, Serde)]
struct Risks {
#[key]
Expand All @@ -28,6 +21,7 @@ impl RisksImpl of RisksTrait {
occurs(seed, self.travel)
}

#[inline(always)]
fn run(ref self: Risks, seed: felt252) -> bool {
occurs(seed, self.run)
}
Expand Down
4 changes: 3 additions & 1 deletion src/constants.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,7 @@ const MIN_QUANITTY: usize = 20_000;
const MAX_CASH: u128 = 60_000_000_000; // $6Mil
const MIN_CASH: u128 = 1_000_000_000; // $100k

// cash players start with
// starting stats
const STARTING_CASH: u128 = 20_000_000; // $2000
const STARTING_BAG_LIMIT: usize = 100; // inventory size
const STARTING_HEALTH: u8 = 100;
6 changes: 4 additions & 2 deletions src/systems/create.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ mod create_game {
use rollyourown::components::location::{Location, LocationTrait};
use rollyourown::constants::{
SCALING_FACTOR, TRAVEL_RISK, RUN_CHANCE, MIN_CASH, MAX_CASH, MIN_QUANITTY, MAX_QUANTITY,
STARTING_CASH
STARTING_CASH, STARTING_HEALTH, STARTING_BAG_LIMIT
};
use rollyourown::utils::random;

Expand Down Expand Up @@ -77,7 +77,9 @@ mod create_game {
player_id: ctx.origin,
location_id,
cash: STARTING_CASH,
health: 100,
health: STARTING_HEALTH,
drug_count: 0,
bag_limit: STARTING_BAG_LIMIT,
turns_remaining: max_turns,
status: PlayerStatus::Normal(()),
},
Expand Down
22 changes: 18 additions & 4 deletions src/systems/decide.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ mod decide {
enum Event {
Decision: Decision,
Consequence: Consequence,
CashLoss: CashLoss,
DrugLoss: DrugLoss,
}

#[derive(Drop, starknet::Event)]
Expand All @@ -43,13 +45,25 @@ mod decide {
struct Consequence {
game_id: u32,
player_id: ContractAddress,
outcome: Outcome
outcome: Outcome,
}

fn execute(ctx: Context, game_id: u32, action: Action, next_location_id: felt252) {
let game = get !(ctx.world, game_id, Game);
assert(game.tick(), 'game cannot progress');
#[derive(Drop, starknet::Event)]
struct CashLoss {
game_id: u32,
player_id: ContractAddress,
amount: u128
}

#[derive(Drop, starknet::Event)]
struct DrugLoss {
game_id: u32,
player_id: ContractAddress,
drug_id: felt252,
quantity: usize
}

fn execute(ctx: Context, game_id: u32, action: Action, next_location_id: felt252) {
let player_id = ctx.origin;
let mut player = get !(ctx.world, (game_id, player_id).into(), Player);
assert(player.status != PlayerStatus::Normal(()), 'player response not needed');
Expand Down
8 changes: 6 additions & 2 deletions src/systems/join.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ mod join_game {
use rollyourown::components::game::Game;
use rollyourown::components::player::Player;
use rollyourown::components::location::{Location, LocationTrait};
use rollyourown::constants::{SCALING_FACTOR, STARTING_CASH};
use rollyourown::constants::{
SCALING_FACTOR, STARTING_CASH, STARTING_HEALTH, STARTING_BAG_LIMIT
};

#[event]
#[derive(Drop, starknet::Event)]
Expand Down Expand Up @@ -44,7 +46,9 @@ mod join_game {
player_id: ctx.origin,
location_id,
cash: STARTING_CASH,
health: 100,
health: STARTING_HEALTH,
drug_count: 0,
bag_limit: STARTING_BAG_LIMIT,
turns_remaining: game.max_turns,
status: PlayerStatus::Normal(()),
})
Expand Down
3 changes: 3 additions & 0 deletions src/systems/trade.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ mod buy {
let mut player = get !(ctx.world, (game_id, player_id).into(), Player);
assert(player.location_id == location_id, 'player is not at location');
assert(player.can_continue(), 'player cannot trade');
assert(player.drug_count + quantity <= player.bag_limit, 'not enough inventory');

let mut market = get !(ctx.world, (game_id, location_id, drug_id).into(), Market);

Expand All @@ -59,6 +60,7 @@ mod buy {

// update player
player.cash -= cost;
player.drug_count += quantity;
set !(ctx.world, (player));

let mut player_drug = get !(ctx.world, (game_id, player_id, drug_id).into(), Drug);
Expand Down Expand Up @@ -126,6 +128,7 @@ mod sell {

// update player
player.cash += payout;
player.drug_count -= quantity;
set !(ctx.world, (player));

drug.quantity -= quantity;
Expand Down
9 changes: 5 additions & 4 deletions src/systems/travel.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ mod travel {
use rollyourown::PlayerStatus;
use rollyourown::components::{game::{Game, GameTrait}, location::Location};
use rollyourown::components::player::{Player, PlayerTrait};
use rollyourown::components::risks::{Risks, RisksTrait, TravelResult};
use rollyourown::components::risks::{Risks, RisksTrait};

#[event]
#[derive(Drop, starknet::Event)]
enum Event {
Traveled: Traveled,
RandomEvent: RandomEvent,
AdverseEvent: AdverseEvent,
}

#[derive(Drop, starknet::Event)]
Expand All @@ -28,7 +28,7 @@ mod travel {
}

#[derive(Drop, starknet::Event)]
struct RandomEvent {
struct AdverseEvent {
game_id: u32,
player_id: ContractAddress,
player_status: PlayerStatus,
Expand All @@ -51,13 +51,14 @@ mod travel {
let mut risks = get !(ctx.world, (game_id, next_location_id).into(), Risks);
let seed = starknet::get_tx_info().unbox().transaction_hash;

// only mugging for now
if risks.travel(seed) {
player.status = PlayerStatus::BeingMugged(());
set !(ctx.world, (player));

emit !(
ctx.world,
RandomEvent { game_id, player_id, player_status: PlayerStatus::BeingMugged(()) }
AdverseEvent { game_id, player_id, player_status: PlayerStatus::BeingMugged(()) }
);

return true;
Expand Down
3 changes: 1 addition & 2 deletions src/tests.cairo
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod create;
mod travel;
mod player;
//mod trade;

mod trade;

133 changes: 31 additions & 102 deletions src/tests/trade.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -7,119 +7,48 @@ use debug::PrintTrait;

use starknet::{ContractAddress, syscalls::deploy_syscall};
use starknet::class_hash::{ClassHash, Felt252TryIntoClassHash};
use starknet::contract_address_const;
use dojo::database::query::{IntoPartitioned, IntoPartitionedQuery};
use dojo::world::{IWorldDispatcher, IWorldDispatcherTrait};
use dojo::world::Context;
use dojo::string::ShortStringTrait;
use dojo::integer::u250Trait;

use rollyourown::components::{
player::Cash, drug::Drug, location::Location, market::{Market, MarketTrait}
};
use rollyourown::tests::spawn::{spawn_game, spawn_location, spawn_player};
use dojo::test_utils::spawn_test_world;

use rollyourown::PlayerStatus;
use rollyourown::components::drug::Drug;
use rollyourown::components::player::Player;
use rollyourown::tests::create::{spawn_game, spawn_player};
use rollyourown::constants::SCALING_FACTOR;

const DRUG_ID: felt252 = 0;
const QUANTITY: usize = 50;
const DRUG_ID: felt252 = 0x57656564; // weed
const QUANTITY: usize = 3;

#[test]
#[available_gas(100000000)]
fn test_player_buy() {
let (world_address, game_id, player_id) = spawn_game();
let location_id = spawn_location(world_address, game_id);

fn test_trade() {
let (world_address, game_id, player_id) = spawn_game(); // creator auto joins
let world = IWorldDispatcher { contract_address: world_address };

// travel to location
let mut player_travel_calldata = array::ArrayTrait::<felt252>::new();
player_travel_calldata.append(game_id);
player_travel_calldata.append(location_id);
world.execute('Travel'.into(), player_travel_calldata.span());
let player = get !(world, (game_id, player_id).into(), (Player));

// buy from market
// market buy 3 weed
let mut buy_calldata = array::ArrayTrait::<felt252>::new();
buy_calldata.append(game_id);
buy_calldata.append(location_id);
buy_calldata.append(game_id.into());
buy_calldata.append(player.location_id);
buy_calldata.append(DRUG_ID);
buy_calldata.append(QUANTITY.into());
world.execute('Buy'.into(), buy_calldata.span());

// verify player has drug in inventory
let mut res = world
.entity('Drug'.into(), (game_id, (player_id, DRUG_ID)).into_partitioned(), 0, 0);
assert(res.len() > 0, 'no drug');
let drug = serde::Serde::<Drug>::deserialize(ref res).expect('deserialization failed');
assert(drug.quantity == QUANTITY, 'incorrect quantity');

// calc market cost
let market = Market { cash: 100 * SCALING_FACTOR, quantity: 1000 };
let cost = market.buy(QUANTITY);

// verify player has cash - cost
let mut res = world.entity('Cash'.into(), (game_id, (player_id)).into_partitioned(), 0, 0);
assert(res.len() > 0, 'no cash');
let cash = serde::Serde::<Cash>::deserialize(ref res).expect('deserialization failed');
assert(cash.amount == (100 * SCALING_FACTOR - cost), 'incorrect cash');
world.execute('buy'.into(), buy_calldata);

let player = get !(world, (game_id, player_id).into(), (Player));
let player_drug = get !(world, (game_id, player_id, DRUG_ID).into(), (Drug));
assert(player.drug_count == QUANTITY, 'wrong drug count');
assert(player_drug.quantity == QUANTITY, 'wrong purchase amount');

// market sell 1 weed
let mut sell_calldata = array::ArrayTrait::<felt252>::new();
sell_calldata.append(game_id.into());
sell_calldata.append(player.location_id);
sell_calldata.append(DRUG_ID);
sell_calldata.append(1);
world.execute('sell'.into(), sell_calldata);

let player = get !(world, (game_id, player_id).into(), (Player));
assert(player.drug_count == QUANTITY - 1, 'wrong sell amount');
}
// FIXME
// #[test]
// #[available_gas(100000000)]
// fn test_player_sell() {
// let (world_address, game_id, player_id) = spawn_game();
// let location_id = spawn_location(world_address, game_id);

// let world = IWorldDispatcher { contract_address: world_address };

// let ctx = Context {
// world,
// caller_account: world.contract_address,
// caller_system: 'Sell'.into(),
// execution_role: AuthRole {
// id: 'DrugWriter'.into()
// },
// };
// // give player drug
// let mut calldata = array::ArrayTrait::new();
// serde::Serde::serialize(@Drug { id: 0.into(), quantity: QUANTITY }, ref calldata);
// World::set_entity(
// ctx,
// 'Drug'.into(),
// (game_id, (player_id, DRUG_ID)).into_partitioned(),
// 0,
// ArrayTrait::span(@calldata)
// );

// // travel to location
// let mut player_travel_calldata = array::ArrayTrait::<felt252>::new();
// player_travel_calldata.append(game_id);
// player_travel_calldata.append(location_id);
// world.execute('Travel'.into(), player_travel_calldata.span());

// // sell to market
// let mut sell_calldata = array::ArrayTrait::<felt252>::new();
// sell_calldata.append(game_id);
// sell_calldata.append(location_id);
// sell_calldata.append(DRUG_ID);
// sell_calldata.append(QUANTITY.into());
// world.execute('Sell'.into(), sell_calldata.span());

// // verify player has no drug
// let mut res = world
// .entity('Drug'.into(), (game_id, (player_id, DRUG_ID)).into_partitioned(), 0, 0);
// assert(res.len() > 0, 'no drug');
// let drug = serde::Serde::<Drug>::deserialize(ref res).expect('deserialization failed');
// assert(drug.quantity == 0, 'incorrect quantity');
// // FIXME: keep getting gas withdraw errors
// // // calc market cost
// // let market = Market { cash: 100 * SCALING_FACTOR, quantity: 1000};
// // let payout = market.sell(QUANTITY);

// // // verify player has cash + payout
// // let mut res = world.entity('Cash'.into(), (game_id, (player_id)).into_partitioned(), 0, 0);
// // assert(res.len() > 0, 'no cash');
// // let cash = serde::Serde::<Cash>::deserialize(ref res).expect('deserialization failed');
// // assert(cash.amount == (100 * SCALING_FACTOR + payout), 'incorrect cash');
// }


14 changes: 5 additions & 9 deletions web/src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,15 @@ import {
stopSound,
initSoundStore,
} from "@/hooks/sound";
import { useUiStore, setIsConnected } from "@/hooks/ui";
import HeaderButton from "@/components/HeaderButton";
import MediaPlayer from "@/components/MediaPlayer";
import MobileMenu from "@/components/MobileMenu";
import { play } from "@/hooks/media";
import { usePlayerEntityQuery, Entity } from "@/generated/graphql";
import { usePlayerEntity } from "@/hooks/dojo/entities/usePlayerEntity";
import { useGameEntity } from "@/hooks/dojo/entities/useGameEntity";
import { usePlayerEntity } from "@/dojo/entities/usePlayerEntity";
import { useGameEntity } from "@/dojo/entities/useGameEntity";
import { formatCash } from "@/utils/ui";
import { useDojo } from "@/hooks/dojo";
import { useDojo } from "@/dojo";

// TODO: constrain this on contract side
const MAX_INVENTORY = 100;
Expand All @@ -35,18 +34,15 @@ const Header = ({ back }: HeaderProps) => {
const [inventory, setInventory] = useState(0);
const { account } = useDojo();

const { player: playerEntity, isFetched: isFetchedPlayer } = usePlayerEntity({
const { player: playerEntity } = usePlayerEntity({
gameId,
address: account?.address,
});
const { game: gameEntity, isFetched: isFetchedGame } = useGameEntity({
const { game: gameEntity } = useGameEntity({
gameId,
});

const isMobile = IsMobile();
const isMuted = useSoundStore((state) => state.isMuted);
const isConnected = useUiStore((state) => state.isConnected);
const hasNewMessages = true;

useEffect(() => {
const init = async () => {
Expand Down
Loading

0 comments on commit 5263c14

Please sign in to comment.