Skip to content

Commit

Permalink
Added WASM code and fixed lifetime fuckery
Browse files Browse the repository at this point in the history
  • Loading branch information
Vilayat-Ali committed Mar 17, 2024
1 parent 25c9cb1 commit 4974080
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 67 deletions.
56 changes: 35 additions & 21 deletions src/game.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
use std::borrow::BorrowMut;
use std::cell::RefCell;
use std::rc::Rc;

use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{console, HtmlElement};

use crate::Coord;
use crate::{snake::Snake, food::Food, ROW_BOUND, COL_BOUND};

use crate::{food::Food, snake::Snake, COL_BOUND, ROW_BOUND};
use web_sys::{console, HtmlElement};
const TICK_RATE: i32 = 500;

#[wasm_bindgen]
#[derive(Debug)]
pub struct Game {
pub is_running: bool,
pub score: u32,
is_running: bool,
score: u32,
bounds: (u32, u32),
snake: Snake,
food_vec: Vec<Food>
snake: Rc<RefCell<Snake>>,
food_vec: Vec<Food>,
}

#[wasm_bindgen]
Expand All @@ -38,29 +43,38 @@ impl Game {
is_running: true,
score: 0,
bounds: (ROW_BOUND, COL_BOUND),
snake: Snake::new(),
snake: Rc::new(RefCell::new(Snake::new())),
food_vec: Vec::with_capacity(5)
}
}


#[wasm_bindgen]
pub fn play(&mut self) {
let window = web_sys::window().expect("Wndow not found");
let snake = self.snake.clone();
let window = web_sys::window().expect("Failed to load WINDOW");
let document = window.document().expect("Failed to fetch Document");

let game_loop = Closure::wrap(Box::new(|| {
console::log_1(&"Snake moving...".into());
// let window = web_sys::window().expect("Wndow not found");
// let document = window.document().unwrap();
// let snake_node_vec = self.snake.get_snake_body().clone();
// for node in snake_node_vec {
// let cell_element = document.get_element_by_id(&format!("cell-{}-{}", node.coord.x, node.coord.y)).unwrap().dyn_into::<HtmlElement>().unwrap();
// cell_element.set_class_name("bg-white");
// }
let game_loop = Closure::wrap(Box::new(move || {
let snake_instance = snake.borrow();
let snake_vec = snake_instance.clone().get_snake_body().clone();

for node in snake_vec {
let Coord {x, y} = node.coord;
console::log_1(&format!("{:#?}", node.coord).into());
let body_cell = document.clone().get_element_by_id(&format!("cell-{}-{}", x, y)).unwrap().dyn_into::<HtmlElement>().unwrap();
body_cell.set_class_name("bg-green-700");
}
}) as Box<dyn FnMut()>);

// running game loop
window.set_interval_with_callback_and_timeout_and_arguments_0(game_loop.as_ref().unchecked_ref(), 500).unwrap();
// Run game loop
let window = web_sys::window().expect("Window Object not found!");
window
.set_interval_with_callback_and_timeout_and_arguments_0(
game_loop.as_ref().unchecked_ref(),
TICK_RATE,
)
.expect("Failed to set gameloop");
game_loop.forget();
}

}
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,36 @@ impl Coord {
}
}
}

use std::rc::Rc;
use std::cell::RefCell;

struct MyType {
value: i32,
}

impl MyType {
fn new(value: i32) -> Self {
MyType { value }
}

fn update(&mut self, new_value: i32) {
self.value = new_value;
}
}

fn main() {
let my_type = Rc::new(RefCell::new(MyType::new(5)));

// Clone the Rc to create a new reference
let my_type_clone = my_type.clone();

// Borrow the RefCell mutably
let mut my_type_instance = my_type.borrow_mut();

// Call a method on the struct
my_type_instance.update(10);

// Access the value inside the RefCell using dereference
println!("{}", my_type_clone.borrow().value); // Output: 10
}
2 changes: 2 additions & 0 deletions src/snake.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use wasm_bindgen::prelude::*;
use web_sys::console;
use crate::{COL_BOUND, ROW_BOUND};

use super::Coord;
Expand Down Expand Up @@ -97,6 +98,7 @@ impl Snake {
}
};
let new_node = Node::new(new_x, new_y, node.direction);
console::log_1(&format!("New Node Appended:\n {:#?}", &new_node.coord).into());
node.next = Some(Box::new(new_node));
self.size += 1;
break;
Expand Down
1 change: 1 addition & 0 deletions web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ <h2 class="text-white text-lg font-semibold mb-2">Game Stats</h2>
async function run() {
await init();

// initiating game
const game = new Game();
game.play();
}
Expand Down
10 changes: 0 additions & 10 deletions web/static/snake.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,6 @@ export class Game {
/**
*/
play(): void;
/**
*/
is_running: boolean;
/**
*/
score: number;
}
/**
*/
Expand Down Expand Up @@ -96,8 +90,6 @@ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembl
export interface InitOutput {
readonly memory: WebAssembly.Memory;
readonly __wbg_game_free: (a: number) => void;
readonly __wbg_get_game_is_running: (a: number) => number;
readonly __wbg_set_game_is_running: (a: number, b: number) => void;
readonly game_new: () => number;
readonly game_play: (a: number) => void;
readonly __wbg_food_free: (a: number) => void;
Expand All @@ -106,8 +98,6 @@ export interface InitOutput {
readonly __wbg_get_food_y: (a: number) => number;
readonly __wbg_set_food_y: (a: number, b: number) => void;
readonly food_get_color: (a: number, b: number) => void;
readonly __wbg_set_game_score: (a: number, b: number) => void;
readonly __wbg_get_game_score: (a: number) => number;
readonly __wbg_coord_free: (a: number) => void;
readonly __wbg_get_coord_x: (a: number) => number;
readonly __wbg_set_coord_x: (a: number, b: number) => void;
Expand Down
38 changes: 6 additions & 32 deletions web/static/snake.js
Original file line number Diff line number Diff line change
Expand Up @@ -391,32 +391,6 @@ export class Game {
wasm.__wbg_game_free(ptr);
}
/**
* @returns {boolean}
*/
get is_running() {
const ret = wasm.__wbg_get_game_is_running(this.__wbg_ptr);
return ret !== 0;
}
/**
* @param {boolean} arg0
*/
set is_running(arg0) {
wasm.__wbg_set_game_is_running(this.__wbg_ptr, arg0);
}
/**
* @returns {number}
*/
get score() {
const ret = wasm.__wbg_get_food_x(this.__wbg_ptr);
return ret >>> 0;
}
/**
* @param {number} arg0
*/
set score(arg0) {
wasm.__wbg_set_food_x(this.__wbg_ptr, arg0);
}
/**
*/
constructor() {
const ret = wasm.game_new();
Expand Down Expand Up @@ -610,6 +584,10 @@ function __wbg_get_imports() {
const ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbg_instanceof_Window_cee7a886d55e7df5 = function(arg0) {
let result;
try {
Expand Down Expand Up @@ -760,10 +738,6 @@ function __wbg_get_imports() {
const ret = getObject(arg0).subarray(arg1 >>> 0, arg2 >>> 0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {
const ret = debugString(getObject(arg1));
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
Expand All @@ -778,8 +752,8 @@ function __wbg_get_imports() {
const ret = wasm.memory;
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper59 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 3, __wbg_adapter_22);
imports.wbg.__wbindgen_closure_wrapper146 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 22, __wbg_adapter_22);
return addHeapObject(ret);
};

Expand Down
Binary file modified web/static/snake_bg.wasm
Binary file not shown.
4 changes: 0 additions & 4 deletions web/static/snake_bg.wasm.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
/* eslint-disable */
export const memory: WebAssembly.Memory;
export function __wbg_game_free(a: number): void;
export function __wbg_get_game_is_running(a: number): number;
export function __wbg_set_game_is_running(a: number, b: number): void;
export function game_new(): number;
export function game_play(a: number): void;
export function __wbg_food_free(a: number): void;
Expand All @@ -12,8 +10,6 @@ export function __wbg_set_food_x(a: number, b: number): void;
export function __wbg_get_food_y(a: number): number;
export function __wbg_set_food_y(a: number, b: number): void;
export function food_get_color(a: number, b: number): void;
export function __wbg_set_game_score(a: number, b: number): void;
export function __wbg_get_game_score(a: number): number;
export function __wbg_coord_free(a: number): void;
export function __wbg_get_coord_x(a: number): number;
export function __wbg_set_coord_x(a: number, b: number): void;
Expand Down

0 comments on commit 4974080

Please sign in to comment.