Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement functions #1

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions gameplay/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ wasm-bindgen = "0.2.83"
num = "0.4"
num-traits = "0.2"
num-derive = "0.3"
lazy_static = "1.4.0"

#[package.metadata.wasm-pack.profile.release]
#wasm-opt = false
Expand Down
68 changes: 36 additions & 32 deletions gameplay/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ use zkwasm_rust_sdk::{
require,
wasm_dbg,
};
use std::sync::Mutex;
extern crate num;
#[macro_use]
extern crate num_derive;
#[macro_use]
extern crate lazy_static;

pub fn get_account(account: u32) -> [u64; 4] {
Merkle::get(account as u64)
Expand Down Expand Up @@ -69,7 +72,7 @@ impl Consequence {
}
}

#[derive(Clone)]
#[derive(Copy, Clone)]
struct Choice {
consequence: Consequence,
description_id: u32,
Expand All @@ -91,6 +94,11 @@ impl RuleEngine {
}
}

// calculate status after applying consequence
fn cal_cons(status: u32, consq: i32) -> u32 {
u32::try_from(i32::try_from(status).unwrap() + consq).unwrap()
}

impl Status {
pub fn new() -> Self {
Status {
Expand All @@ -113,29 +121,32 @@ impl Status {
}

pub fn choose(&mut self, choice_index: usize) -> Choice {
let choice = self.context.as_ref().unwrap()[choice_index].clone();
let choice = self.context.as_ref().unwrap()[choice_index];
self.apply_consequence(choice.consequence);
choice
}

// calculate new status value
fn apply_consequence(&mut self, consq: Consequence) {
self.wisdom += 1;
self.wisdom = cal_cons(self.wisdom, consq.wisdom);
self.attack = cal_cons(self.attack, consq.attack);
self.luck = cal_cons(self.luck, consq.luck);
self.charm = cal_cons(self.charm, consq.charm);
self.family = cal_cons(self.family, consq.family);
self.speed = cal_cons(self.speed, consq.speed);
self.defence = cal_cons(self.defence, consq.defence);
self.age = cal_cons(self.age, consq.age);
self.currency = cal_cons(self.currency, consq.currency);
}
}

//static STATUS: Status = Status::new();
static mut STATUS: Status = Status {
wisdom: 10,
attack: 10,
luck: 10,
charm: 10,
family: 10,
speed: 10,
defence: 10,
age: 10,
currency: 10,
context: None,
};
lazy_static! {
static ref STATUS: Mutex<Status> = {
let status = Status::new();
Mutex::new(status)
};
}

#[derive(Copy, Clone, FromPrimitive)]
enum ActionType {
Expand All @@ -154,38 +165,31 @@ pub fn get_status() -> Status {

#[wasm_bindgen]
pub fn get_wisdom() -> u32 {
unsafe {
STATUS.wisdom
}
STATUS.lock().unwrap().wisdom
}


#[wasm_bindgen]
pub fn get_choices() -> Vec<u32> {
unsafe {
let choices = STATUS.context.as_ref();
choices.map_or(vec![], |x| {
x.iter().map(|x| {
x.description_id
}).collect::<Vec<u32>>()
})
}
let binding = STATUS.lock().unwrap();
let choices = binding.context.as_ref();
choices.map_or(vec![], |x| {
x.iter().map(|x| {
x.description_id
}).collect::<Vec<u32>>()
})
}

#[wasm_bindgen]
pub fn action(at: u32) {
let action_type = num::FromPrimitive::from_u32(at).unwrap();
let rule_engine = RuleEngine {};
unsafe {
let _choices = STATUS.act(action_type, &rule_engine);
}
let _choices = STATUS.lock().unwrap().act(action_type, &rule_engine);
}

#[wasm_bindgen]
pub fn choose(at: usize) {
unsafe {
STATUS.choose(at);
}
STATUS.lock().unwrap().choose(at);
}

#[wasm_bindgen]
Expand Down
31 changes: 31 additions & 0 deletions src/components/Status.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
interface IProps {
tag?: string;
wisdom: number;
attack: number;
luck: number;
charm: number;
family: number;
speed: number;
defence: number;
age: number;
className?: string;
}

export default function StatusDisplay(props: IProps) {
const { tag = "Status", wisdom, attack, luck, charm, family, speed, defence, age } = props;
return (
<>
<div className={`status-display ${props.className}`}>
<span className="tag">{tag}</span>
<span className="value ms-2">{wisdom}</span>
<span className="value ms-2">{attack}</span>
<span className="value ms-2">{luck}</span>
<span className="value ms-2">{charm}</span>
<span className="value ms-2">{family}</span>
<span className="value ms-2">{speed}</span>
<span className="value ms-2">{defence}</span>
<span className="value ms-2">{age}</span>
</div>
</>
);
}
36 changes: 36 additions & 0 deletions src/components/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,39 @@
font-size: 14px;
}
}

.statusBar {
background-color: var(--button-main);
padding: 5px 10px;
border-radius: 5px;
font-family: "Be Vietnam";
font-style: normal;
font-weight: 600;
font-size: 16px;

width: 500px;
margin: 0 auto;
margin-top: 20px;
display: flex;
align-items: center;
justify-content: space-between;

.tag {
font-family: "Be Vietnam";
font-style: normal;
font-weight: 600;
font-size: 20px;

color: var(--blue-text-color);
position: relative;
top: -5px;
}
.value {
font-family: "Be Vietnam";
font-style: normal;
font-weight: 600;
font-size: 16px;
text-align: end;
color: var(--blue-text-color);
}
}
37 changes: 37 additions & 0 deletions src/js/game.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import makeWasm from './game.wasm';
const {
Module,
instantiate,
Memory,
Table
} = WebAssembly;

var instance = null;

export default async function () {
if (instance != null) {
return instance.exports;
} else {
module = await makeWasm({
'global': {},
'env': {
'memory': new Memory({ initial: 10, limit: 100 }),
'table': new Table({ initial: 0, element: 'anyfunc' }),
'abort': () => {console.error("abort in wasm!"); throw new Error("Unsupported wasm api: abort");},
'require': (b) => {if(!b){console.error("require failed"); throw new Error("Require failed");}},
'wasm_input': () => {
console.error("wasm_input should not been called in non-zkwasm mode");
throw new Error("Unsupported wasm api: wasm_input");
}
}
});
console.log("module loaded", module); // "3
/*
WebAssembly.instantiateStreaming(makeWasm, importObject).then(
(obj) => console.log(obj.instance.exports)
);
*/
instance = module.instance;
return instance.exports;
}
}
30 changes: 27 additions & 3 deletions src/layout/Main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,33 @@ import "bootstrap-icons/font/bootstrap-icons.css";
import "./style.scss";
import "bootswatch/dist/slate/bootstrap.min.css";
import CurrencyDisplay from "../components/Currency";
import StatusDisplay from "../components/Status";
import { Container } from "react-bootstrap";
import { MainNavBar } from "../components/Nav";
import Title from "../images/2048_title.png";

export function Main() {
const dispatch = useAppDispatch();
const [currency, setCurrency] = useState(20);
const [submitURI, setSubmitURI] = useState("");
const [wisdom, setWisdom] = useState(0);
const [attack, setAttack] = useState(0);
const [luck, setLuck] = useState(0);
const [charm, setCharm] = useState(0);
const [family, setFamily] = useState(0);
const [speed, setSpeed] = useState(0);
const [defence, setDefence] = useState(0);
const [age, setAge] = useState(0);
const [currency, setCurrency] = useState(0);

let ready = useAppSelector(tasksLoaded);

useEffect(() => {
initGameInstance().then((ins: any) => {
console.log("current wisdom", ins.get_wisdom());
ins.step();
ins.action(0);
ins.choose(0);
ins.get_choices();
setWisdom(ins.get_wisdom());
console.log("post wisdom", ins.get_wisdom());

});
Expand All @@ -53,11 +65,23 @@ export function Main() {
<img src={Title} height="40px" alt="title" className="me-4" />
<CurrencyDisplay
tag="Best"
value={12}
value={currency}
className="high-score mx-2"
></CurrencyDisplay>
</Col>
</Row>
<StatusDisplay
tag="Status"
wisdom={wisdom}
attack={attack}
luck={luck}
charm={charm}
family={family}
speed={speed}
defence={defence}
age={age}
className="statusBar"
></StatusDisplay>
<Row className="mt-3">
<Col>
<div className="content">
Expand Down