Skip to content

Commit

Permalink
Resorted to complete WASM control
Browse files Browse the repository at this point in the history
  • Loading branch information
Vilayat-Ali committed Mar 3, 2024
1 parent 6ee45e7 commit 7c8daed
Show file tree
Hide file tree
Showing 15 changed files with 44 additions and 947 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ wasm-pack.log
yarn.lock
package-lock.json
node_modules
web/styles/dist.css
web/styles/dist.css
/examples
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"rust-analyzer.linkedProjects": [
"./Cargo.toml",
"./Cargo.toml",
"./Cargo.toml"
]
}
45 changes: 0 additions & 45 deletions src/food.rs
Original file line number Diff line number Diff line change
@@ -1,45 +0,0 @@
use wasm_bindgen::prelude::*;

use super::{Coord, generate_random_points};

#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct Food {
pub x: u32,
pub y: u32,
}

#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct FoodSpawner {
x_bounds: u32,
y_bounds: u32,
food_vec: Vec<Food>,
}

#[wasm_bindgen]
impl FoodSpawner {
#[wasm_bindgen(constructor)]
pub fn new(x_bounds: u32, y_bounds: u32) -> Self {
Self {
x_bounds,
y_bounds,
food_vec: Vec::with_capacity(10)
}
}

#[wasm_bindgen]
pub fn spawn(&mut self) {
let Coord{x, y} = generate_random_points(self.x_bounds, self.y_bounds);
self.food_vec.push(Food {
x,
y
});
}

#[wasm_bindgen]
pub fn eat_food(&mut self, x: u32, y: u32) {
let idx: usize = self.food_vec.iter().position(|food| food.x == x && food.y == y).expect("Invalid food coordinates");
self.food_vec.swap_remove(idx);
}
}
1 change: 1 addition & 0 deletions src/game.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use wasm_bindgen::prelude::*;
47 changes: 6 additions & 41 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,8 @@
mod utils;
mod snake;
mod food;
pub mod utils;
pub mod snake;
pub mod game;
pub mod food;

use wasm_bindgen::prelude::*;
use getrandom::getrandom;
pub static ROW_BOUND: u32 = 33;
pub static COL_BOUND: u32 = 56;

#[wasm_bindgen]
pub struct Coord {
pub x: u32,
pub y: u32
}

#[wasm_bindgen]
impl Coord {
#[wasm_bindgen(getter)]
pub fn get_x(&self) -> u32 {
self.x
}

#[wasm_bindgen(getter)]
pub fn get_y(&self) -> u32 {
self.y
}
}

#[wasm_bindgen]
pub fn generate_random_points(x_bound: u32, y_bound: u32) -> Coord {
Coord {
x: {
let mut buffer = [0u8; 4];
getrandom(&mut buffer).expect("Failed to generate random number");
let random_number = u32::from_ne_bytes(buffer) % (x_bound + 1);
random_number
},
y: {
let mut buffer = [0u8; 4];
getrandom(&mut buffer).expect("Failed to generate random number");
let random_number = u32::from_ne_bytes(buffer) % (y_bound + 1);
random_number
}
}
}
11 changes: 6 additions & 5 deletions src/snake.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use wasm_bindgen::prelude::*;
use super::generate_random_points;
use super::utils::generate_random_points;

#[wasm_bindgen]
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -35,7 +35,7 @@ impl Node {
}

#[wasm_bindgen]
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Snake {
pub size: usize,
body: Option<Box<Node>>
Expand All @@ -45,10 +45,10 @@ pub struct Snake {
impl Snake {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
let coord = generate_random_points(33, 56);
let (x, y) = generate_random_points();
Self {
size: 1,
body: Some(Box::new(Node::new(coord.x, coord.y, Direction::UP)))
body: Some(Box::new(Node::new(x, y, Direction::UP)))
}
}

Expand Down Expand Up @@ -104,4 +104,5 @@ impl Snake {
vec.push(*(body_ref.clone().unwrap()));
vec
}
}
}

18 changes: 18 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use getrandom::getrandom;
use crate::{ROW_BOUND, COL_BOUND};

pub fn set_panic_hook() {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function at least once during initialization, and then
Expand All @@ -8,3 +11,18 @@ pub fn set_panic_hook() {
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
}

pub fn generate_random_points() -> (u32, u32) {
({
let mut buffer = [0u8; 4];
getrandom(&mut buffer).expect("Failed to generate random number");
let random_number = u32::from_ne_bytes(buffer) % (ROW_BOUND + 1);
random_number
},
{
let mut buffer = [0u8; 4];
getrandom(&mut buffer).expect("Failed to generate random number");
let random_number = u32::from_ne_bytes(buffer) % (COL_BOUND + 1);
random_number
})
}
39 changes: 0 additions & 39 deletions web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -115,45 +115,6 @@ <h2 class="text-white text-lg font-semibold mb-2">Game Stats</h2>

<!-- Include FontAwesome icons -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"></script>

<!-- JavaScript for generating the grid -->
<script>
const grid = document.getElementById('game-area');
const rows = 33; // Number of rows
const cols = 56; // Number of columns

for (let row_no = 0; row_no < rows; row_no++) {
for (let col_no = 0; col_no < cols; col_no++) {
const cell = document.createElement('div');
cell.className = 'h-6 w-6 bg-gray-700 border border-gray-800 rounded-sm shadow';
cell.id = `cell-${row_no}-${col_no}`;
grid.appendChild(cell);
}
}
</script>

<script>
const starCountCard = document.querySelector('#github-stars');
fetch(`https://api.github.com/repos/vilayat-ali/wasmslither`)
.then(response => response.json())
.then(data => {
starCountCard.innerHTML = data.stargazers_count;
})
.catch(error => console.error(error));
</script>

<script type="module">
import init, { generate_random_points, Snake } from "./static/snake.js";

init()
.then((wasm) => {
const snake = new Snake();
})
.catch((err) => {
console.error(err);
alert('Failed to load Web Assembly!')
});
</script>
</body>

</html>
Empty file removed web/scripts/app.js
Empty file.
9 changes: 9 additions & 0 deletions web/scripts/data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function updateGithubStarCount() {
const starCountCard = document.querySelector("#github-stars");
fetch(`https://api.github.com/repos/vilayat-ali/wasmslither`)
.then((response) => response.json())
.then((data) => {
starCountCard.innerHTML = data.stargazers_count;
})
.catch((error) => console.error(error));
}
17 changes: 0 additions & 17 deletions web/static/package.json

This file was deleted.

Loading

0 comments on commit 7c8daed

Please sign in to comment.