Skip to content

Commit

Permalink
Improved gameplay
Browse files Browse the repository at this point in the history
  • Loading branch information
gdsc0301 committed Jun 30, 2023
1 parent 349c85c commit 8275fc4
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 125 deletions.
34 changes: 7 additions & 27 deletions .github/workflows/page.yml
Original file line number Diff line number Diff line change
@@ -1,31 +1,18 @@
# This is a basic workflow to help you get started with Actions

name: CI
name: Build and Deploy

# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the "main" branch
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

permissions:
contents: read
pages: write
id-token: write
branches:
- main

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

# The type of runner that the job will run on
runs-on: ubuntu-latest

Expand All @@ -44,15 +31,8 @@ jobs:
- name: Build the project
run: npm install && npm run build

- name: Setup Pages
uses: actions/configure-pages@v3

- name: Upload artifact
uses: actions/upload-pages-artifact@v1
- name: Deploy to GH Pages 🚀
uses: peaceiris/actions-gh-pages@v3
with:
# Upload entire repository
path: '.dist'

- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v2
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: public
11 changes: 5 additions & 6 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ const rooms = {};

/**
* @param {Player} player
* @returns {String} The room ID
* @returns {Room} The room with the player
*/
const get_free_room_for = player => {
const assign_room_for = player => {
if(Object.keys(rooms).length === 0) { // If ther's no room, create a new one;
const new_room = new Room(createHash('sha256').update(Date.now().toString()).digest('hex'));
player.setRoomID(new_room.ID);
Expand Down Expand Up @@ -102,7 +102,6 @@ const get_headers = (content_type) => {
}

const server = createServer(async (req, res) => {
console.log(req.headers);
const req_url = new URL(`http://${req.headers.host}${req.url}`);

const player_email = req_url.searchParams.get('player_email');
Expand Down Expand Up @@ -140,7 +139,7 @@ const server = createServer(async (req, res) => {

route('/login', () => {
const new_player = new Player(player_email);
const new_player_room = get_free_room_for(new_player);
const new_player_room = assign_room_for(new_player);

res.writeHead(OK, BasicHeaders);
res.end((new Response(new_player_room)).toString);
Expand All @@ -163,13 +162,13 @@ const server = createServer(async (req, res) => {
return;
}, req);

route('/move', (params, body) => {
route('/player_update', (params, body) => {
if(!body) return;
let response = undefined;

const targetPlayer = rooms[room_id].get_player(player_email);
if(targetPlayer)
targetPlayer.move(body.params.x, body.params.y);
targetPlayer.setPosition(body.params.x, body.params.y);
else
response = (new Response({}, BAD_REQUEST, 'Invalid player email')).toString;

Expand Down
7 changes: 0 additions & 7 deletions src/Command.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,6 @@ class Command {
this.action = action;
this.key = key;
}

get obj() {
return {
action: this.action,
key: this.key
};
}
}

export default Command;
61 changes: 42 additions & 19 deletions src/Player.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,53 @@ export class Player {
speed = 10;

direction = 0;
inputAxis = {

#inputAxis = {
x: 0,
y: 0
}

commandsBuffer = [];

constructor(username) {
this.username = username;
}

/**
* @param {Player} serverUpdatedPlayer
* @param {string} key The key to check
* @param {boolean} pressing Is pressing or releasing that key?
*/
update(serverUpdatedPlayer) {
this.username = serverUpdatedPlayer.username;
this.currentRoomID = serverUpdatedPlayer.currentRoomID;
this.x = serverUpdatedPlayer.x;
this.y = serverUpdatedPlayer.y;

this.width = serverUpdatedPlayer.width;
this.height = serverUpdatedPlayer.height;
#defineAxis(key, pressing) {
switch (key) {
case 'ArrowUp':
this.#inputAxis.y = pressing ? -1 : 0;
break;

case 'ArrowDown':
this.#inputAxis.y = pressing ? 1 : 0;
break;

case 'ArrowLeft':
this.#inputAxis.x = pressing ? -1 : 0;
break;

case 'ArrowRight':
this.#inputAxis.x = pressing ? 1 : 0;
break;

default:
break;
}
}

this.speed = serverUpdatedPlayer.speed;
initInputEvents() {
document.addEventListener('keydown', e => {
this.#defineAxis(e.key, true);
}
);

this.direction = serverUpdatedPlayer.direction;
document.addEventListener('keyup', e => {
this.#defineAxis(e.key, false);
}
);
}

setRoomID(roomID) {
Expand All @@ -50,16 +71,16 @@ export class Player {
return false;
}

move(axis_x,axis_y) {
this.x += axis_x * this.speed;
this.y += axis_y * this.speed;
move() {
this.x += this.#inputAxis.x * this.speed;
this.y += this.#inputAxis.y * this.speed;
}

setPosition(x,y) {
this.x = x;
this.y = y;
}

/**
* @param {CanvasRenderingContext2D} ctx
* @param {number} canvasWidth
Expand All @@ -84,14 +105,16 @@ export class Player {
PlayerD2D.lineTo(thisPos.x + this.width/2, thisPos.y + this.height/2);
PlayerD2D.closePath();

ctx.stroke(PlayerD2D);

ctx.fillStyle = this.usernameStyle;
ctx.fillText(this.username, thisPos.x, thisPos.y - this.height - 12);

return PlayerD2D;
}

setInputAxis(x,y) {
this.inputAxis = {x:x,y:y};
this.#inputAxis = {x:x,y:y};
}

get currentRoomID() {
Expand Down
103 changes: 37 additions & 66 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,50 +32,40 @@ function init() {
fetch(`${serverURL}/login?player_email=${encodeURIComponent(username)}`).then(res => {
res.json().then(body => {
if(body?.status === 200) {
welcomeMessage.innerHTML = 'Welcome, '+username;
currentRoom = body.data;
currentRoom = Object.assign((new Room(body.data.ID)), structuredClone(body.data));
LocalPlayer = Object.assign((new Player(username)), structuredClone(currentRoom.players[username]));
parseRoomPlayers();
LocalPlayer = currentRoom.players[username];

gameplayLoop = setInterval(update, 1000/60);

document.addEventListener('keydown', e => {
LocalPlayer.commandsBuffer.push((new Command('down', e.key)).obj);
}
);

document.addEventListener('keyup', e => {
LocalPlayer.commandsBuffer.push(
(new Command('up', e.key)).obj
);
if(e.key === 'Escape') { // On press esc, stop game
clearInterval(gameplayLoop);
return;
}
}
);

document.addEventListener('keydown', e => {
return e.key === 'Escape' ? clearInterval(gameplayLoop) : undefined;
});
LocalPlayer.initInputEvents();

window.addEventListener('beforeunload', () => {
clearInterval(gameplayLoop);
return fetch(getReqURL('logout')).then(() => {return true;});
if(gameplayLoop){
fetch(getReqURL('logout'));
clearInterval(gameplayLoop);
}
return;
});

welcomeMessage.innerHTML = 'Welcome, ' + username;
gameplayLoop = setInterval(update, 1000/60);
}else {
welcomeMessage.innerHTML = 'Login failed, try again later';
clearInterval(gameplayLoop);
console.error(body);
}
})
});
});
}

function parseRoomPlayers() {
for(const player_id in currentRoom.players) {
const playerInst = new Player(player_id);

currentRoom.players[player_id] = Object.assign(playerInst, currentRoom.players[player_id]);
}
}

function getReqURL(path) {
return `${serverURL}/${path}?player_email=${LocalPlayer.username}&room_id=${LocalPlayer.currentRoomID}`;
}
Expand All @@ -84,10 +74,8 @@ function getRoomData() {
fetch(getReqURL('room')).then(res => {
res.json().then(body => {
if(body?.status === 200) {
const updated_room = body.data;
currentRoom = Object.assign(currentRoom, updated_room);
currentRoom = Object.assign(currentRoom, body.data);
parseRoomPlayers();
LocalPlayer.update(currentRoom.players[LocalPlayer.username]);
}else {
emailErrorField.classList.add('active');
emailErrorField.innerHTML = body.error;
Expand All @@ -97,15 +85,20 @@ function getRoomData() {
});
}

function movePlayer(x,y) {
const req = new Request(getReqURL('move'), {
function parseRoomPlayers() {
for(const player_id in currentRoom.players) {
const playerInst = new Player(player_id);

currentRoom.players[player_id] = Object.assign(playerInst, currentRoom.players[player_id]);
}
}

function sendPlayerToServer() {
const req = new Request(getReqURL('player_update'), {
method: 'POST',
body: JSON.stringify({
action: 'move',
params: {
x: x,
y: y
}
action: 'player_update',
params: LocalPlayer
})
});

Expand All @@ -115,44 +108,22 @@ function movePlayer(x,y) {
function update() {
getRoomData();

// Get keys
for(let i=0;i < LocalPlayer.commandsBuffer.length; i++){
const movement = LocalPlayer.commandsBuffer.pop();
const pressing = movement.action === 'down';

switch (movement.key) {
case 'ArrowUp':
LocalPlayer.inputAxis.y = pressing ? -1 : 0;
break;

case 'ArrowDown':
LocalPlayer.inputAxis.y = pressing ? 1 : 0;
break;

case 'ArrowLeft':
LocalPlayer.inputAxis.x = pressing ? -1 : 0;
break;

case 'ArrowRight':
LocalPlayer.inputAxis.x = pressing ? 1 : 0;
break;
default:
break;
}
}

if(LocalPlayer.inputAxis.x !== 0 || LocalPlayer.inputAxis.y !== 0)
movePlayer(LocalPlayer.inputAxis.x, LocalPlayer.inputAxis.y);
LocalPlayer.move();

sendPlayerToServer();
draw();
}

function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeStyle = 'orange';

LocalPlayer.draw(ctx, canvas.width, canvas.height, LocalPlayer);
for(const player_id in currentRoom.players) {
ctx.stroke(currentRoom.players[player_id].draw(ctx, canvas.width, canvas.height, LocalPlayer));
if(player_id === LocalPlayer.username) continue;

currentRoom.players[player_id].draw(
ctx, canvas.width, canvas.height, LocalPlayer
)
}

ctx.strokeStyle = 'white';
Expand Down

0 comments on commit 8275fc4

Please sign in to comment.