Commit 5161cb87 authored by Vũ Gia Vương's avatar Vũ Gia Vương

add network ctrl

parent f8296233
......@@ -27,8 +27,7 @@ const CONFIG = {
SPAWN_TOWER: '205',
CLOSE_QR_VIEW: '206',
PASS_TOWER: '207',
HISTORY: '208',
GAME_MESSAGE: '300',
......
const URL = 'https://dev.gamee.vn/api/web';
const URL_START_GAME = `${URL}/game/start`;
const URL_END_GAME = `${URL}/game/end`;
const GAME_CODE = 'flip-jump';
let token = 'eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MTI1LCJ1c2VybmFtZSI6IlFIU18wMUpEVkZHOE5DUEdBNEtFRUhLWDA4RUJWOCIsImRpc3BsYXlOYW1lIjoiVFJBTiBEVUMgS0hBTkgiLCJlbmFibGVkM'
+ 'kZBIjpmYWxzZSwibGFzdExvZ2luVGltZSI6IjIwMjUtMDgtMDhUMTQ6MTc6MDcuNzczMTEyMjUzIiwicmVmZXJlbmNlQ29kZSI6IklRVEtUQzRkbGk4NiIsImdlbmRlciI6Ik1BTEUiLCJ2dG1BY2NvdW50'
+ 'SWQiOiIwMUpEVkZHOE5DUEdBNEtFRUhLWDA4RUJWOCIsImRvYiI6IjE5OTktMDItMTciLCJjb2RlIjoiMTIzNDU2NzYiLCJzdWIiOiIxMjUiLCJpYXQiOjE3NTQ2Mzc0MjcsImV4cCI6MTc2MzI3NzQyN30.'
+ 'Wf7PDX2rgqRPajkTL8oHHeYFwZrLpTKmuBO8Va9OGMs';
let timeStart = 0;
let userId = 0;
let matchId = '';
let eventId: string | null = null;
export async function startGameApi(data: any) {
timeStart = new Date().getTime();
userId = (Math.random() * 100 >> 0) + 10;
matchId = `${userId}-${GAME_CODE}-${timeStart}`;
data = {
matchId,
gameCode: GAME_CODE,
};
const result = await callApi(URL_START_GAME, 'POST', data);
return result;
}
export async function endGameApi(score: number) {
console.log('score', score)
const playedSeconds = (new Date().getTime() - timeStart) / 1e3;
const params = {
matchId,
gameCode: GAME_CODE,
eventId,
playedSeconds,
score,
}
const res = await callApi(URL_END_GAME, 'POST', params);
}
async function callApi(url: string, method: string, data: any) {
try {
let res = await fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify(data),
});
const result = await res.json();
console.log(url, result.code, result.message);
return result?.code == 'success';
} catch (error) {
console.log('error call api: ', error);
}
}
......@@ -14,8 +14,8 @@ class User {
public nextBlock: v2 = v2.zero;
public screenPos: v2 = v2.zero;
public isEndGame: boolean = false;
public history: v2[] = [];
public isEndGame: boolean = true;
public history: History[] = [];
constructor(token: string) {
this.token = token;
......@@ -24,7 +24,7 @@ class User {
class History{
public time: number = 0;
public score: number = 0;
public totalScore: number = 0;
public tower: number = 0;
}
......
......@@ -8,7 +8,6 @@ class v2 {
this.y = y || 0;
}
public distanceTo(other: v2): number {
return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
}
......
export class Global {
public static rooms: { [room: string]: Room };
public static users: { [uuid: string]: User };
}
export class Room {
public name: string = '';
public users: string[] = [];
public key: string = '';
constructor(name: string, key: string) {
this.name = name;
this.users = [];
this.key = key;
}
}
export class User {
public uuid: string = '';
public room: string = '';
constructor(room: string, id: string) {
this.room = room;
this.uuid = id;
}
}
......@@ -2,11 +2,13 @@ import { Server, Socket } from "socket.io";
import CONFIG from "./Config/config";
import User from "./Model/User";
import v2 from "./Model/v2";
import { endGameApi, startGameApi } from "./Controller/networkCtrl";
const users: { [key: string]: User } = {};
const yRadio: number = 0.5560472;
const distanceBlock: number = 56.43580423808985;
export function setupSocket(io: Server) {
io.use((socket: Socket, next) => {
const token = socket.handshake.query.token;
......@@ -20,12 +22,33 @@ export function setupSocket(io: Server) {
console.log(`🟢 Client connected: ${socket.id}`);
socket.on(CONFIG.EVT.JOIN_ROOM, (data: string) => joinRoom(socket, data));
socket.on(CONFIG.EVT.START_GAME, (data: string) => startGame(socket, data));
socket.on(CONFIG.EVT.PASS_TOWER, async (data: { nextPos: v2, time: number, distance: number }) => await passTower(socket, data));
socket.on(CONFIG.EVT.SPAWN_TOWER, async () => addBlock(socket));
// socket.on(CONFIG.EVT.SPAWN_TOWER, async () => addBlock(socket));
socket.on(CONFIG.EVT.HISTORY, async () => getHistory(socket));
socket.on("disconnect", () => console.log(`🔴 Client disconnected: ${socket.id}`));
});
}
async function getHistory(socket: Socket) {
const user = getUserBySocketId(socket.id);
const response = await socket.emitWithAck('requestHistory', user.history);
}
async function startGame(socket: Socket, data: any) {
const user = getUserBySocketId(socket.id);
const result = await startGameApi(data);
if (result) {
user.isEndGame = false;
addBlock(socket);
} else {
console.log('start game fail');
const response = await socket.emitWithAck('requestStartGame', { code: 9999 });
}
}
async function passTower(socket: Socket, data: { nextPos: v2, time: number, distance: number }) {
const user = getUserBySocketId(socket.id);
// console.log('data', data);
......@@ -51,19 +74,23 @@ async function passTower(socket: Socket, data: { nextPos: v2, time: number, dist
} else {
user.combo = 0;
}
user.totalScore += score;
const dataSend = {
totalScore: user.totalScore,
tower: user.towerNumber,
score,
time: data.time,
};
const response = await socket.emitWithAck('requestPassTower', dataSend);
if (!user.isEndGame) {
addBlock(socket);
} else {
endGameApi(user.totalScore);
user.history.unshift(dataSend);
user.totalScore = 0;
}
const response = await socket.emitWithAck('requestPassTower', dataSend);
}
async function addBlock(socket: Socket) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment