1
0
mirror of https://github.com/lexogrine/cs2-react-hud.git synced 2026-05-04 12:13:11 +02:00

Updated setup to vite and moved to hooks instead of class

This commit is contained in:
Hubert Walczak
2023-11-02 12:11:03 +01:00
parent 44f173f23c
commit f88baa5fc9
90 changed files with 7411 additions and 2706 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from "react";
import { mediaStreams } from "./mediaStream";
import { v4 as uuidv4 } from 'uuid';
import { mediaStreams } from "../../API/HUD/camera";
type Props = {
steamid: string,
visible: boolean;
+2 -2
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from "react";
import { useEffect, useState } from "react";
import PlayerCamera from "./Camera";
import api from "../../api/api";
import api from "../../API";
import "./index.scss";
-153
View File
@@ -1,153 +0,0 @@
import { Instance, SignalData } from 'simple-peer';
import api from '../../api/api';
import { socket as Socket } from "../../App";
const Peer = require('simple-peer');
const wait = (ms: number) => new Promise(r => setTimeout(r, ms));
type OfferData = {
offer: SignalData,
}
type PeerInstance = Instance & { _remoteStreams: MediaStream[] }
type MediaStreamPlayer = {
peerConnection: PeerInstance | null;
steamid: string;
}
type ListenerType = ({ listener: (stream: MediaStream) => void, event: 'create', steamid: string } | ({ listener: () => void, event: 'destroy', steamid: string }));
type MediaStreamManager = {
blocked: string[];
blockedListeners: ((blocked: string[]) => void)[],
players: MediaStreamPlayer[];
onStreamCreate: (listener: (stream: MediaStream) => void, steamid: string) => void;
onStreamDestroy: (listener: () => void, steamid: string) => void;
onBlockedUpdate: (listener: (steamids: string[]) => void) => void;
removeListener: (listener: any) => void;
listeners: ListenerType[];
}
const mediaStreams: MediaStreamManager = {
blocked: [],
blockedListeners: [],
players: [],
listeners: [],
onStreamCreate: (listener: (stream: MediaStream) => void, steamid: string) => {
mediaStreams.listeners.push({ listener, event: "create", steamid });
},
onBlockedUpdate: (listener: (blocked: string[]) => void) => {
mediaStreams.blockedListeners.push(listener);
},
onStreamDestroy: (listener: () => void, steamid: string) => {
mediaStreams.listeners.push({ listener, event: "destroy", steamid });
},
removeListener: (listenerToRemove: any) => {
mediaStreams.listeners = mediaStreams.listeners.filter(listener => listener !== listenerToRemove);
mediaStreams.blockedListeners = mediaStreams.blockedListeners.filter(listener => listener !== listenerToRemove);
}
};
const getConnectionInfo = (steamid: string) => mediaStreams.players.find(player => player.steamid === steamid) || null;
const closeConnection = (steamid: string) => {
const connectionInfo = getConnectionInfo(steamid);
try {
if (connectionInfo) {
if (connectionInfo.peerConnection) {
connectionInfo.peerConnection.removeAllListeners();
connectionInfo.peerConnection.destroy();
}
connectionInfo.peerConnection = null;
}
} catch {
}
for (const listener of mediaStreams.listeners.filter(listener => listener.steamid === steamid)) {
if (listener.event === "destroy") listener.listener();
}
mediaStreams.players = mediaStreams.players.filter(player => player.steamid !== steamid);
console.log(mediaStreams.players)
}
const initiateConnection = async () => {
const socket = Socket as SocketIOClient.Socket;
const camera = await api.camera.get();
await wait(1000);
socket.emit("registerAsHUD", camera.uuid);
socket.on('playersCameraStatus', (players: { steamid: string, label: string, allow: boolean, active: boolean }[]) => {
const blockedSteamids = players.filter(player => !player.allow).map(player => player.steamid);
mediaStreams.blocked = blockedSteamids;
for (const listener of mediaStreams.blockedListeners) {
listener(blockedSteamids);
}
});
socket.on('offerFromPlayer', async (roomId: string, offerData: OfferData, steamid: string) => {
// It's not from available player, ignore incoming request
/*if(!camera.availablePlayers.find(player => player.steamid === steamid)){
console.log("Wrong player");
return;
}*/
const currentConnection = getConnectionInfo(steamid);
// Connection already made, ignore incoming request
if (currentConnection) {
console.log("Connection has been made already");
return;
}
if (camera.uuid !== roomId) return;
const peerConnection: PeerInstance = new Peer({ initiator: false, trickle: false });
const mediaStreamPlayer: MediaStreamPlayer = { peerConnection, steamid };
mediaStreams.players.push(mediaStreamPlayer);
peerConnection.on('signal', answer => {
console.log("SIGNAL COMING IN");
const offer = JSON.parse(JSON.stringify(answer)) as RTCSessionDescriptionInit;
socket.emit("offerFromHUD", roomId, { offer }, steamid);
});
peerConnection.on('error', (err) => {
console.log(err)
closeConnection(steamid);
});
peerConnection.on('stream', () => {
console.log("STREAM COMING IN");
const currentConnection = getConnectionInfo(steamid);
if (!currentConnection) {
console.log("Connection not established");
closeConnection(steamid);
return;
}
if (peerConnection._remoteStreams.length === 0) {
console.log('no stream?');
return;
}
for (const listener of mediaStreams.listeners.filter(listener => listener.steamid === steamid)) {
if (listener.event === "create") listener.listener(peerConnection._remoteStreams[0]);
}
});
peerConnection.on('close', () => {
console.log("CLOSE COMING IN");
const currentConnection = getConnectionInfo(steamid);
if (!currentConnection) return;
closeConnection(steamid);
});
console.log("Sending offer");
peerConnection.signal(offerData.offer);
});
}
export { mediaStreams, initiateConnection };
+12 -14
View File
@@ -1,15 +1,13 @@
import React from 'react';
import { Player } from 'csgogsi-socket';
import {ArmorHelmet, ArmorFull} from './../../assets/Icons';
export default class Armor extends React.Component<{ player: Player }> {
render() {
const { player } = this.props;
if(!player.state.health || !player.state.armor) return '';
return (
<div className={`armor_indicator`}>
{player.state.helmet ? <ArmorHelmet /> : <ArmorFull/>}
</div>
);
}
import React from "react";
import { ArmorFull, ArmorHelmet } from "./../../assets/Icons";
}
const Armor = ({ health, armor, helmet }: { health: number, armor: number, helmet: boolean }) => {
if (!health || !armor) return null;
return (
<div className={`armor_indicator`}>
{helmet ? <ArmorHelmet /> : <ArmorFull />}
</div>
);
};
export default React.memo(Armor);
+13 -15
View File
@@ -1,15 +1,13 @@
import React from 'react';
import { Player } from 'csgogsi-socket';
import {Bomb as BombIcon} from './../../assets/Icons';
export default class Bomb extends React.Component<{ player: Player }> {
render() {
const { player } = this.props;
if(Object.values(player.weapons).every(weapon => weapon.type !== "C4")) return '';
return (
<div className={`armor_indicator`}>
<BombIcon />
</div>
);
}
}
import { Player } from "csgogsi";
import { Bomb as BombIcon } from "./../../assets/Icons";
const Bomb = ({ player }: { player: Player }) => {
if (Object.values(player.weapons).every((weapon) => weapon.type !== "C4")) {
return null;
}
return (
<div className={`armor_indicator`}>
<BombIcon />
</div>
);
};
export default Bomb;
+3 -7
View File
@@ -1,15 +1,11 @@
import React from 'react';
import { Player } from 'csgogsi-socket';
import { Player } from 'csgogsi';
import {Defuse as DefuseIcon} from './../../assets/Icons';
export default class Defuse extends React.Component<{ player: Player }> {
render() {
const { player } = this.props;
const Defuse = ({ player }: { player: Player }) => {
if(!player.state.health || !player.state.defusekit) return '';
return (
<div className={`defuse_indicator`}>
<DefuseIcon />
</div>
);
}
}
export default Defuse;
+4 -6
View File
@@ -1,13 +1,11 @@
import React from 'react';
import Weapon from './../Weapon/Weapon';
import flash_assist from './../../assets/flash_assist.png';
import { C4, Defuse, FlashedKill, Headshot, NoScope, SmokeKill, Suicide, Wallbang } from "./../../assets/Icons"
import { ExtendedKillEvent, BombEvent } from "./Killfeed"
export default class Kill extends React.Component<{ event: ExtendedKillEvent | BombEvent }> {
render() {
const { event } = this.props;
const Kill = ({event}: { event: ExtendedKillEvent | BombEvent }) => {
if (event.type !== "kill") {
return (
<div className={`single_kill`}>
@@ -50,6 +48,6 @@ export default class Kill extends React.Component<{ event: ExtendedKillEvent | B
</div>
</div>
);
}
}
export default Kill;
+22 -60
View File
@@ -1,8 +1,9 @@
import React from 'react';
import { GSI } from './../../App';
import { KillEvent, Player } from 'csgogsi-socket';
import React, { useState } from 'react';
import { KillEvent, Player } from 'csgogsi';
import Kill from './Kill';
import './killfeed.scss';
import { onGSI } from '../../API/contexts/actions';
export interface ExtendedKillEvent extends KillEvent {
@@ -14,63 +15,24 @@ export interface BombEvent {
type: 'plant' | 'defuse'
}
export default class Killfeed extends React.Component<any, { events: (BombEvent | ExtendedKillEvent)[] }> {
constructor(props: any){
super(props);
this.state = {
events: []
}
}
addKill = (kill: KillEvent) => {
this.setState(state => {
state.events.push({...kill, type: 'kill'});
return state;
})
}
addBombEvent = (player: Player, type: 'plant' | 'defuse') => {
if(!player) return;
const event: BombEvent = {
player: player,
type: type
}
this.setState(state => {
state.events.push(event);
return state;
})
}
async componentDidMount() {
GSI.on("kill", kill => {
this.addKill(kill);
});
GSI.on("data", data => {
if(data.round && data.round.phase === "freezetime"){
if(Number(data.phase_countdowns.phase_ends_in) < 10 && this.state.events.length > 0){
this.setState({events:[]})
}
const Killfeed = () => {
const [ events, setEvents ] = useState<(BombEvent | ExtendedKillEvent)[]>([]);
onGSI("kill", kill => {
setEvents(ev => [...ev, {...kill, type: 'kill'}]);
}, []);
onGSI("data", data => {
if(data.round && data.round.phase === "freezetime"){
if(Number(data.phase_countdowns.phase_ends_in) < 10 && events.length > 0){
setEvents([]);
}
});
/*
GSI.on("bombPlant", player => {
this.addBombEvent(player, 'plant');
})
GSI.on("bombDefuse", player => {
this.addBombEvent(player, 'defuse');
})
*/
}
render() {
return (
<div className="killfeed">
{this.state.events.map(event => <Kill event={event}/>)}
</div>
);
}
}
}, []);
return (
<div className="killfeed">
{events.map(event => <Kill event={event}/>)}
</div>
);
}
export default React.memo(Killfeed);
+74 -104
View File
@@ -1,14 +1,11 @@
import React from "react";
import { useState } from "react";
import TeamBox from "./../Players/TeamBox";
import MatchBar from "../MatchBar/MatchBar";
import SeriesBox from "../MatchBar/SeriesBox";
import Observed from "./../Players/Observed";
import { CSGO, Team } from "csgogsi-socket";
import { Match } from "../../api/interfaces";
import RadarMaps from "./../Radar/RadarMaps";
import Trivia from "../Trivia/Trivia";
import SideBox from '../SideBoxes/SideBox';
import { GSI, actions } from "./../../App";
import MoneyBox from '../SideBoxes/Money';
import UtilityLevel from '../SideBoxes/UtilityLevel';
import Killfeed from "../Killfeed/Killfeed";
@@ -17,119 +14,92 @@ import Overview from "../Overview/Overview";
import Tournament from "../Tournament/Tournament";
import Pause from "../PauseTimeout/Pause";
import Timeout from "../PauseTimeout/Timeout";
import PlayerCamera from "../Camera/Camera";
import { CSGO } from "csgogsi";
import { Match } from "../../API/types";
import { useAction } from "../../API/contexts/actions";
interface Props {
game: CSGO,
match: Match | null
}
/*
interface State {
winner: Team | null,
showWin: boolean,
forceHide: boolean
}
}*/
export default class Layout extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
winner: null,
showWin: false,
forceHide: false
const Layout = ({game,match}: Props) => {
const [ forceHide, setForceHide ] = useState(false);
useAction('boxesState', (state) => {
console.log("UPDATE STATE UMC", state);
if (state === "show") {
setForceHide(false);
} else if (state === "hide") {
setForceHide(true);
}
}
});
componentDidMount() {
GSI.on('roundEnd', score => {
this.setState({ winner: score.winner, showWin: true }, () => {
setTimeout(() => {
this.setState({ showWin: false })
}, 4000)
});
});
actions.on("boxesState", (state: string) => {
if (state === "show") {
this.setState({ forceHide: false });
} else if (state === "hide") {
this.setState({ forceHide: true });
}
});
}
const left = game.map.team_ct.orientation === "left" ? game.map.team_ct : game.map.team_t;
const right = game.map.team_ct.orientation === "left" ? game.map.team_t : game.map.team_ct;
getVeto = () => {
const { game, match } = this.props;
const { map } = game;
if (!match) return null;
const mapName = map.name.substring(map.name.lastIndexOf('/') + 1);
const veto = match.vetos.find(veto => veto.mapName === mapName);
if (!veto) return null;
return veto;
}
render() {
const { game, match } = this.props;
const left = game.map.team_ct.orientation === "left" ? game.map.team_ct : game.map.team_t;
const right = game.map.team_ct.orientation === "left" ? game.map.team_t : game.map.team_ct;
const leftPlayers = game.players.filter(player => player.team.side === left.side);
const rightPlayers = game.players.filter(player => player.team.side === right.side);
const isFreezetime = (game.round && game.round.phase === "freezetime") || game.phase_countdowns.phase === "freezetime";
const { forceHide } = this.state;
return (
<div className="layout">
<div className={`players_alive`}>
<div className="title_container">Players alive</div>
<div className="counter_container">
<div className={`team_counter ${left.side}`}>{leftPlayers.filter(player => player.state.health > 0).length}</div>
<div className={`vs_counter`}>VS</div>
<div className={`team_counter ${right.side}`}>{rightPlayers.filter(player => player.state.health > 0).length}</div>
</div>
</div>
<Killfeed />
<Overview match={match} map={game.map} players={game.players || []} />
<RadarMaps match={match} map={game.map} game={game} />
<MatchBar map={game.map} phase={game.phase_countdowns} bomb={game.bomb} match={match} />
<Pause phase={game.phase_countdowns}/>
<Timeout map={game.map} phase={game.phase_countdowns} />
<SeriesBox map={game.map} phase={game.phase_countdowns} match={match} />
<Tournament />
<Observed player={game.player} veto={this.getVeto()} round={game.map.round+1}/>
<TeamBox team={left} players={leftPlayers} side="left" current={game.player} />
<TeamBox team={right} players={rightPlayers} side="right" current={game.player} />
<Trivia />
<MapSeries teams={[left, right]} match={match} isFreezetime={isFreezetime} map={game.map} />
<div className={"boxes left"}>
<UtilityLevel side={left.side} players={game.players} show={isFreezetime && !forceHide} />
<SideBox side="left" hide={forceHide} />
<MoneyBox
team={left.side}
side="left"
loss={Math.min(left.consecutive_round_losses * 500 + 1400, 3400)}
equipment={leftPlayers.map(player => player.state.equip_value).reduce((pre, now) => pre + now, 0)}
money={leftPlayers.map(player => player.state.money).reduce((pre, now) => pre + now, 0)}
show={isFreezetime && !forceHide}
/>
</div>
<div className={"boxes right"}>
<UtilityLevel side={right.side} players={game.players} show={isFreezetime && !forceHide} />
<SideBox side="right" hide={forceHide} />
<MoneyBox
team={right.side}
side="right"
loss={Math.min(right.consecutive_round_losses * 500 + 1400, 3400)}
equipment={rightPlayers.map(player => player.state.equip_value).reduce((pre, now) => pre + now, 0)}
money={rightPlayers.map(player => player.state.money).reduce((pre, now) => pre + now, 0)}
show={isFreezetime && !forceHide}
/>
const leftPlayers = game.players.filter(player => player.team.side === left.side);
const rightPlayers = game.players.filter(player => player.team.side === right.side);
const isFreezetime = (game.round && game.round.phase === "freezetime") || game.phase_countdowns.phase === "freezetime";
return (
<div className="layout">
<div className={`players_alive`}>
<div className="title_container">Players alive</div>
<div className="counter_container">
<div className={`team_counter ${left.side}`}>{leftPlayers.filter(player => player.state.health > 0).length}</div>
<div className={`vs_counter`}>VS</div>
<div className={`team_counter ${right.side}`}>{rightPlayers.filter(player => player.state.health > 0).length}</div>
</div>
</div>
);
}
<Killfeed />
<Overview match={match} map={game.map} players={game.players || []} />
<RadarMaps match={match} map={game.map} game={game} />
<MatchBar map={game.map} phase={game.phase_countdowns} bomb={game.bomb} match={match} />
<Pause phase={game.phase_countdowns}/>
<Timeout map={game.map} phase={game.phase_countdowns} />
<SeriesBox map={game.map} match={match} />
<Tournament />
<Observed player={game.player} />
<TeamBox team={left} players={leftPlayers} side="left" current={game.player} />
<TeamBox team={right} players={rightPlayers} side="right" current={game.player} />
<Trivia />
<MapSeries teams={[left, right]} match={match} isFreezetime={isFreezetime} map={game.map} />
<div className={"boxes left"}>
<UtilityLevel side={left.side} players={game.players} show={isFreezetime && !forceHide} />
<SideBox side="left" hide={forceHide} />
<MoneyBox
team={left.side}
side="left"
loss={Math.min(left.consecutive_round_losses * 500 + 1400, 3400)}
equipment={leftPlayers.map(player => player.state.equip_value).reduce((pre, now) => pre + now, 0)}
money={leftPlayers.map(player => player.state.money).reduce((pre, now) => pre + now, 0)}
show={isFreezetime && !forceHide}
/>
</div>
<div className={"boxes right"}>
<UtilityLevel side={right.side} players={game.players} show={isFreezetime && !forceHide} />
<SideBox side="right" hide={forceHide} />
<MoneyBox
team={right.side}
side="right"
loss={Math.min(right.consecutive_round_losses * 500 + 1400, 3400)}
equipment={rightPlayers.map(player => player.state.equip_value).reduce((pre, now) => pre + now, 0)}
money={rightPlayers.map(player => player.state.money).reduce((pre, now) => pre + now, 0)}
show={isFreezetime && !forceHide}
/>
</div>
</div>
);
}
export default Layout;
+54 -50
View File
@@ -1,62 +1,66 @@
import React from "react";
import * as I from "csgogsi-socket";
import { Match, Veto } from '../../api/interfaces';
import * as I from "csgogsi";
import TeamLogo from "../MatchBar/TeamLogo";
import "./mapseries.scss";
import { Match, Veto } from "../../API/types";
interface IProps {
match: Match | null;
teams: I.Team[];
isFreezetime: boolean;
map: I.Map
match: Match | null;
teams: I.Team[];
isFreezetime: boolean;
map: I.Map;
}
interface IVetoProps {
veto: Veto;
teams: I.Team[];
active: boolean;
veto: Veto;
teams: I.Team[];
active: boolean;
}
class VetoEntry extends React.Component<IVetoProps> {
render(){
const { veto, teams, active } = this.props;
return <div className={`veto_container ${active ? 'active' : ''}`}>
<div className="veto_map_name">
{veto.mapName}
</div>
<div className="veto_picker">
<TeamLogo team={teams.filter(team => team.id === veto.teamId)[0]} />
</div>
<div className="veto_winner">
<TeamLogo team={teams.filter(team => team.id === veto.winner)[0]} />
</div>
<div className="veto_score">
{Object.values((veto.score || ['-','-'])).sort().join(":")}
</div>
<div className='active_container'>
<div className='active'>Currently playing</div>
</div>
</div>
}
}
const VetoEntry = ({ veto, teams, active }: IVetoProps) => {
return (
<div className={`veto_container ${active ? "active" : ""}`}>
<div className="veto_map_name">
{veto.mapName}
</div>
<div className="veto_picker">
<TeamLogo team={teams.filter((team) => team.id === veto.teamId)[0]} />
</div>
<div className="veto_winner">
<TeamLogo team={teams.filter((team) => team.id === veto.winner)[0]} />
</div>
<div className="veto_score">
{Object.values(veto.score || ["-", "-"]).sort().join(":")}
</div>
<div className="active_container">
<div className="active">Currently playing</div>
</div>
</div>
);
};
export default class MapSeries extends React.Component<IProps> {
render() {
const { match, teams, isFreezetime, map } = this.props;
if (!match || !match.vetos.length) return null;
const MapSeries = ({ match, teams, isFreezetime, map }: IProps) => {
if (!match || !match.vetos.length) return null;
return (
<div className={`map_series_container ${isFreezetime ? "show" : "hide"}`}>
<div className="title_bar">
<div className="picked">Picked</div>
<div className="winner">Winner</div>
<div className="score">Score</div>
</div>
{match.vetos.filter((veto) =>
veto.type !== "ban"
).map((veto) => {
if (!veto.mapName) return null;
return (
<div className={`map_series_container ${isFreezetime ? 'show': 'hide'}`}>
<div className="title_bar">
<div className="picked">Picked</div>
<div className="winner">Winner</div>
<div className="score">Score</div>
</div>
{match.vetos.filter(veto => veto.type !== "ban").map(veto => {
if(!veto.mapName) return null;
return <VetoEntry key={`${match.id}${veto.mapName}${veto.teamId}${veto.side}`} veto={veto} teams={teams} active={map.name.includes(veto.mapName)}/>
})}
</div>
<VetoEntry
key={`${match.id}${veto.mapName}${veto.teamId}${veto.side}`}
veto={veto}
teams={teams}
active={map.name.includes(veto.mapName)}
/>
);
}
}
})}
</div>
);
};
export default MapSeries;
+24 -152
View File
@@ -1,11 +1,10 @@
import React from "react";
import * as I from "csgogsi-socket";
import * as I from "csgogsi";
import "./matchbar.scss";
import TeamScore from "./TeamScore";
import Bomb from "./../Timers/BombTimer";
import Countdown from "./../Timers/Countdown";
import { GSI } from "../../App";
import { Match } from "../../api/interfaces";
import { useBombTimer } from "./../Timers/Countdown";
import { Match } from './../../API/types';
function stringToClock(time: string | number, pad = true) {
if (typeof time === "string") {
@@ -28,176 +27,49 @@ interface IProps {
}
export interface Timer {
width: number;
time: number;
active: boolean;
countdown: number;
side: "left"|"right";
type: "defusing" | "planting";
player: I.Player | null;
}
interface IState {
defusing: Timer,
planting: Timer,
winState: {
side: "left"|"right",
show: boolean
const getRoundLabel = (mapRound: number) => {
const round = mapRound + 1;
if (round <= 30) {
return `Round ${round}/30`;
}
const additionalRounds = round - 30;
const OT = Math.ceil(additionalRounds/6);
return `OT ${OT} (${additionalRounds - (OT - 1)*6}/6)`;
}
export default class TeamBox extends React.Component<IProps, IState> {
constructor(props: IProps){
super(props);
this.state = {
defusing: {
width: 0,
active: false,
countdown: 10,
side: "left",
type: "defusing",
player: null
},
planting: {
width: 0,
active: false,
countdown: 10, // Fake
side: "right",
type: "planting",
player: null
},
winState: {
side: 'left',
show: false
}
}
}
plantStop = () => this.setState(state => {
state.planting.active = false;
return state;
});
setWidth = (type: 'defusing' | 'planting', width: number) => {
this.setState(state => {
state[type].width = width;
return state;
})
}
initPlantTimer = () => {
const bomb = new Countdown(time => {
let width = time * 100;
this.setWidth("planting", width/3);
});
GSI.on("bombPlantStart", player => {
if(!player || !player.team) return;
this.setState(state => {
state.planting.active = true;
state.planting.side = player.team.orientation;
state.planting.player = player;
})
})
GSI.on("data", data => {
if(!data.bomb || !data.bomb.countdown || data.bomb.state !== "planting") return this.plantStop();
this.setState(state => {
state.planting.active = true;
})
return bomb.go(data.bomb.countdown);
});
}
defuseStop = () => this.setState(state => {
state.defusing.active = false;
state.defusing.countdown = 10;
return state;
});
initDefuseTimer = () => {
const bomb = new Countdown(time => {
let width = time > this.state.defusing.countdown ? this.state.defusing.countdown*100 : time * 100;
this.setWidth("defusing", width/this.state.defusing.countdown);
});
GSI.on("defuseStart", player => {
if(!player || !player.team) return;
this.setState(state => {
state.defusing.active = true;
state.defusing.countdown = !Boolean(player.state.defusekit) ? 10 : 5;
state.defusing.side = player.team.orientation;
state.defusing.player = player;
return state;
})
})
GSI.on("data", data => {
if(!data.bomb || !data.bomb.countdown || data.bomb.state !== "defusing") return this.defuseStop();
this.setState(state => {
state.defusing.active = true;
return state;
})
return bomb.go(data.bomb.countdown);
});
}
resetWin = () => {
setTimeout(() => {
this.setState(state => {
state.winState.show = false;
return state;
})
}, 6000);
}
componentDidMount(){
this.initDefuseTimer();
this.initPlantTimer();
GSI.on("roundEnd", score => {
this.setState(state => {
state.winState.show = true;
state.winState.side = score.winner.orientation;
return state;
}, this.resetWin);
});
}
getRoundLabel = () => {
const { map } = this.props;
const round = map.round + 1;
if (round <= 24) {
return `Round ${round}/24`;
}
const additionalRounds = round - 24;
const OT = Math.ceil(additionalRounds/6);
return `OT ${OT} (${additionalRounds - (OT - 1)*6}/6)`;
}
render() {
const { defusing, planting, winState } = this.state;
const { bomb, match, map, phase } = this.props;
const Matchbar = (props: IProps) => {
const { bomb, match, map, phase } = props;
const time = stringToClock(phase.phase_ends_in);
const left = map.team_ct.orientation === "left" ? map.team_ct : map.team_t;
const right = map.team_ct.orientation === "left" ? map.team_t : map.team_ct;
const isPlanted = bomb && (bomb.state === "defusing" || bomb.state === "planted");
const bo = (match && Number(match.matchType.substr(-1))) || 0;
let leftTimer: Timer | null = null, rightTimer: Timer | null = null;
if(defusing.active || planting.active){
if(defusing.active){
if(defusing.side === "left") leftTimer = defusing;
else rightTimer = defusing;
} else {
if(planting.side === "left") leftTimer = planting;
else rightTimer = planting;
}
}
const bombData = useBombTimer();
const plantTimer: Timer | null = bombData.state === "planting" ? { time:bombData.plantTime, active: true, side: bombData.player?.team.orientation || "right", player: bombData.player, type: "planting"} : null;
const defuseTimer: Timer | null = bombData.state === "defusing" ? { time:bombData.defuseTime, active: true, side: bombData.player?.team.orientation || "left", player: bombData.player, type: "defusing"} : null;
return (
<>
<div id={`matchbar`}>
<TeamScore team={left} orientation={"left"} timer={leftTimer} showWin={winState.show && winState.side === "left"} />
<TeamScore team={left} orientation={"left"} timer={left.side === "CT" ? defuseTimer : plantTimer}/>
<div className={`score left ${left.side}`}>{left.score}</div>
<div id="timer" className={bo === 0 ? 'no-bo' : ''}>
<div id={`round_timer_text`} className={isPlanted ? "hide":""}>{time}</div>
<div id="round_now" className={isPlanted ? "hide":""}>{this.getRoundLabel()}</div>
<div id="round_now" className={isPlanted ? "hide":""}>{getRoundLabel(map.round)}</div>
<Bomb />
</div>
<div className={`score right ${right.side}`}>{right.score}</div>
<TeamScore team={right} orientation={"right"} timer={rightTimer} showWin={winState.show && winState.side === "right"} />
<TeamScore team={right} orientation={"right"} timer={right.side === "CT" ? defuseTimer : plantTimer} />
</div>
</>
);
}
}
export default Matchbar;
+5 -8
View File
@@ -1,16 +1,12 @@
import React from "react";
import * as I from "csgogsi-socket";
import { Match } from "../../api/interfaces";
import * as I from "csgogsi";
import { Match } from "../../API/types";
interface Props {
map: I.Map;
phase: I.PhaseRaw;
match: Match | null;
}
export default class SeriesBox extends React.Component<Props> {
render() {
const { match, map } = this.props;
const SeriesBox = ({ map, match }: Props) => {
const amountOfMaps = (match && Math.floor(Number(match.matchType.substr(-1)) / 2) + 1) || 0;
const bo = (match && Number(match.matchType.substr(-1))) || 0;
const left = map.team_ct.orientation === "left" ? map.team_ct : map.team_t;
@@ -40,5 +36,6 @@ export default class SeriesBox extends React.Component<Props> {
</div>
</div>
);
}
}
export default SeriesBox;
+7 -9
View File
@@ -1,11 +1,8 @@
import React from 'react';
import { Team } from 'csgogsi-socket';
import * as I from '../../api/interfaces';
import { apiUrl } from './../../api/api';
import { Team } from 'csgogsi';
import * as I from '../../API/types';
import { apiUrl } from './../../API';
export default class TeamLogo extends React.Component<{ team?: Team | I.Team | null, height?: number, width?: number}> {
render(){
const { team } = this.props;
const TeamLogo = ({team, height, width }: { team?: Team | I.Team | null, height?: number, width?: number}) => {
if(!team) return null;
let id = '';
const { logo } = team;
@@ -16,9 +13,10 @@ export default class TeamLogo extends React.Component<{ team?: Team | I.Team | n
}
return (
<div className={`logo`}>
{ logo && id ? <img src={`${apiUrl}api/teams/logo/${id}`} width={this.props.width} height={this.props.height} alt={'Team logo'} /> : ''}
{ logo && id ? <img src={`${apiUrl}api/teams/logo/${id}`} width={width} height={height} alt={'Team logo'} /> : ''}
</div>
);
}
}
export default TeamLogo;
+22 -12
View File
@@ -1,30 +1,40 @@
import React from "react";
import * as I from "csgogsi-socket";
import WinIndicator from "./WinIndicator";
import * as I from "csgogsi";
import { Timer } from "./MatchBar";
import TeamLogo from './TeamLogo';
import PlantDefuse from "../Timers/PlantDefuse"
import { onGSI } from "../../API/contexts/actions";
import WinAnnouncement from "./WinIndicator";
import { useState } from "react";
interface IProps {
team: I.Team;
orientation: "left" | "right";
timer: Timer | null;
showWin: boolean;
team: I.Team;
}
export default class TeamScore extends React.Component<IProps> {
render() {
const { orientation, timer, team, showWin } = this.props;
const TeamScore = ({orientation, timer, team }: IProps) => {
const [ show, setShow ] = useState(false);
onGSI("roundEnd", result => {
if(result.winner.orientation !== orientation) return;
setShow(true);
setTimeout(() => {
setShow(false);
}, 5000);
}, [orientation]);
return (
<>
<div className={`team ${orientation} ${team.side}`}>
<div className="team-name">{team.name}</div>
<div className={`team ${orientation} ${team.side || ''}`}>
<div className="team-name">{team?.name || null}</div>
<TeamLogo team={team} />
<div className="round-thingy"><div className="inner"></div></div>
</div>
<PlantDefuse timer={timer} side={orientation} />
<WinIndicator team={team} show={showWin}/>
<WinAnnouncement team={team} show={show} />
</>
);
}
}
export default TeamScore;
+5 -6
View File
@@ -1,12 +1,11 @@
import React from 'react';
import { Team } from 'csgogsi-socket';
import { Team } from 'csgogsi';
export default class WinAnnouncement extends React.Component<{ team: Team | null, show: boolean }> {
render() {
const { team, show } = this.props;
const WinAnnouncement = ({team, show }: { team: Team | null, show: boolean }) => {
if(!team) return null;
return <div className={`win_text ${show ? 'show' : ''} ${team.orientation} ${team.side}`}>
WINS THE ROUND!
</div>
}
}
export default WinAnnouncement;
+35 -37
View File
@@ -1,41 +1,39 @@
import React from 'react';
import * as I from '../../api/interfaces';
import TeamLogo from '../MatchBar/TeamLogo';
import * as I from "../../API/types";
import "./index.scss";
import TeamLogo from "../MatchBar/TeamLogo";
interface IProps {
match: I.Match,
show: boolean,
teams: I.Team[],
veto: I.Veto | null
match: I.Match;
show: boolean;
teams: I.Team[];
veto: I.Veto | null;
}
export default class MatchOverview extends React.Component<IProps> {
render() {
const { match, teams, show } = this.props;
const left = teams.find(team => team._id === match.left.id);
const right = teams.find(team => team._id === match.right.id);
if(!match || !left || !right) return null;
return (
<div className={`match-overview ${show ? 'show':''}`}>
<div className="match-overview-title">
Upcoming match
</div>
<div className="match-overview-teams">
<div className="match-overview-team">
<div className="match-overview-team-logo">
<TeamLogo team={left} height={40} />
</div>
<div className="match-overview-team-name">{left.name}</div>
</div>
<div className="match-overview-vs">vs</div>
<div className="match-overview-team">
<div className="match-overview-team-logo">
<TeamLogo team={right} height={40} />
</div>
<div className="match-overview-team-name">{right.name}</div>
</div>
</div>
</div>
);
}
}
const MatchOverview = ({ match, teams, show }: IProps) => {
const left = teams.find((team) => team._id === match.left.id);
const right = teams.find((team) => team._id === match.right.id);
if (!match || !left || !right) return null;
return (
<div className={`match-overview ${show ? "show" : ""}`}>
<div className="match-overview-title">
Upcoming match
</div>
<div className="match-overview-teams">
<div className="match-overview-team">
<div className="match-overview-team-logo">
<TeamLogo team={left} height={40} />
</div>
<div className="match-overview-team-name">{(left.shortName || left.name).substring(0, 4)}</div>
</div>
<div className="match-overview-vs">vs</div>
<div className="match-overview-team">
<div className="match-overview-team-logo">
<TeamLogo team={right} height={40} />
</div>
<div className="match-overview-team-name">{(right.shortName || right.name).substring(0, 4)}</div>
</div>
</div>
</div>
);
};
export default MatchOverview;
@@ -39,4 +39,4 @@
flex: unset;
background-color: rgba(0,0,0,0.6);
font-size: 30px;
}
}
+30 -114
View File
@@ -1,27 +1,10 @@
import React from 'react';
import { actions, configs } from '../../App';
import * as I from '../../api/interfaces';
import { useState } from 'react';
import PlayerOverview from '../PlayerOverview/PlayerOverview';
import MatchOverview from '../MatchOverview/MatchOverview';
import TeamOverview from '../TeamOverview/TeamOverview';
import { Map, Player } from 'csgogsi-socket';
import api from '../../api/api';
interface IState {
player: {
data: I.Player | null,
show: boolean
},
match: {
data: I.Match | null,
show: boolean,
teams: I.Team[],
},
team: {
data: I.Team | null,
show: boolean
}
}
import { Map, Player } from 'csgogsi';
import * as I from './../../API/types';
import api from './../../API';
import { useConfig, useOnConfigChange } from '../../API/contexts/actions';
interface IProps {
match: I.Match | null,
@@ -29,97 +12,30 @@ interface IProps {
players: Player[]
}
export default class Overview extends React.Component<IProps, IState> {
constructor(props: IProps){
super(props);
this.state = {
player: {
data: null,
show: false
},
match: {
data: null,
show: false,
teams: []
},
team: {
data: null,
show: false,
}
}
}
loadTeams = async () => {
const { match } = this.state;
if(!match.data || !match.data.left.id || !match.data.right.id) return;
const teams = await Promise.all([api.teams.getOne(match.data.left.id), api.teams.getOne(match.data.right.id)]);
const Overview = ({ match, map, players }: IProps) => {
const [ teams, setTeams ] = useState<I.Team[]>([]);
const mapName = map.name.substring(map.name.lastIndexOf('/')+1);
const previewData = useConfig("preview_settings");
useOnConfigChange('preview_settings', async data => {
console.log(data);
if(!data?.match_preview?.match?.left.id || !data?.match_preview?.match?.right.id) return;
const teams = await Promise.all([api.teams.getOne(data?.match_preview?.match?.left.id), api.teams.getOne(data?.match_preview?.match?.right.id)]);
if(!teams[0] || !teams[1]) return;
this.setState(state => {
state.match.teams = teams;
return state;
});
}
componentDidMount() {
configs.onChange((data: any) => {
if(!data || !data.preview_settings) return;
this.setState({
player: {
data: (data.preview_settings.player_preview && data.preview_settings.player_preview.player) || null,
show: Boolean(data.preview_settings.player_preview_toggle)
},
team: {
data: (data.preview_settings.team_preview && data.preview_settings.team_preview.team) || null,
show: Boolean(data.preview_settings.team_preview_toggle)
},
match: {
data: (data.preview_settings.match_preview && data.preview_settings.match_preview.match) || null,
show: Boolean(data.preview_settings.match_preview_toggle),
teams: this.state.match.teams
}
}, this.loadTeams);
});
actions.on("toggleUpcomingMatch", () => {
this.setState(state => {
state.match.show = !state.match.show;
return state;
})
})
actions.on("togglePlayerPreview", () => {
this.setState(state => {
state.player.show = !state.player.show;
return state;
})
})
}
getVeto = () => {
const { map, match } = this.props;
if(!match) return null;
const mapName = map.name.substring(map.name.lastIndexOf('/')+1);
const veto = match.vetos.find(veto => veto.mapName === mapName);
if(!veto) return null;
return veto;
}
renderPlayer = () => {
const { player } = this.state;
if(!player.data) return null;
return <PlayerOverview round={this.props.map.round + 1} player={player.data} players={this.props.players} show={player.show} veto={this.getVeto()} />
}
renderMatch = () => {
const { match } = this.state;
if(!match.data || !match.teams[0] || !match.teams[1]) return null;
return <MatchOverview match={match.data} show={match.show} veto={this.getVeto()} teams={match.teams}/>
}
renderTeam = () => {
const { team } = this.state;
if(!team.data) return null;
return <TeamOverview team={team.data} show={team.show} veto={this.getVeto()} />
}
render() {
return (
<>
{this.renderPlayer()}
{this.renderMatch()}
{this.renderTeam()}
</>
);
}
setTeams(teams);
}, []);
const playerData = previewData?.player_preview?.player;
const matchData = previewData?.match_preview?.match;
const veto = match?.vetos.find(veto => veto.mapName === mapName) || null;
return (<>
{ playerData ? <PlayerOverview round={map.round + 1} player={playerData} players={players} show={!!previewData.player_preview_toggle} veto={veto} /> : null}
{ matchData && teams[0] && teams[1] ? <MatchOverview match={matchData} veto={veto} teams={teams} show={!!previewData.match_preview_toggle} /> : null }
</>)
}
export default Overview;
+13 -13
View File
@@ -1,17 +1,17 @@
import React from "react";
import { PhaseRaw } from "csgogsi-socket";
import { PhaseRaw } from "csgogsi";
interface IProps {
phase: PhaseRaw | null
phase: PhaseRaw | null;
}
export default class Pause extends React.Component<IProps> {
render() {
const { phase } = this.props;
return (
<div id={`pause`} className={phase && phase.phase === "paused" ? 'show' : ''}>
PAUSE
</div>
);
}
}
const Pause = ({ phase }: IProps) => {
return (
<div
id={`pause`}
className={phase && phase.phase === "paused" ? "show" : ""}
>
PAUSE
</div>
);
};
export default Pause;
+26 -18
View File
@@ -1,22 +1,30 @@
import React from "react";
import { Map, PhaseRaw } from "csgogsi-socket";
import { Map, PhaseRaw } from "csgogsi";
interface IProps {
phase: PhaseRaw | null,
map: Map
phase: PhaseRaw | null;
map: Map;
}
export default class Timeout extends React.Component<IProps> {
render() {
const { phase, map } = this.props;
const time = phase && Math.abs(Math.ceil(parseFloat(phase.phase_ends_in)));
const team = phase && phase.phase === "timeout_t" ? map.team_t : map.team_ct;
return (
<div id={`timeout`} className={`${time && time > 2 && phase && (phase.phase === "timeout_t" || phase.phase === "timeout_ct") ? 'show' : ''} ${phase && (phase.phase === "timeout_t" || phase.phase === "timeout_ct") ? phase.phase.substr(8): ''}`}>
{ team.name } TIMEOUT
</div>
);
}
}
const Timeout = ({ phase, map }: IProps) => {
const time = phase && Math.abs(Math.ceil(parseFloat(phase.phase_ends_in)));
const team = phase && phase.phase === "timeout_t" ? map.team_t : map.team_ct;
return (
<div
id={`timeout`}
className={`${
time && time > 2 && phase &&
(phase.phase === "timeout_t" || phase.phase === "timeout_ct")
? "show"
: ""
} ${
phase && (phase.phase === "timeout_t" || phase.phase === "timeout_ct")
? phase.phase.substring(8)
: ""
}`}
>
{team.name} TIMEOUT
</div>
);
};
export default Timeout;
+64 -68
View File
@@ -1,10 +1,8 @@
import React from 'react';
import * as I from '../../api/interfaces';
import { avatars } from './../../api/avatars';
import { apiUrl } from '../../api/api';
import * as I from '../../API/types';
import { getCountry } from '../countries';
import { Player } from 'csgogsi-socket';
import { Player } from 'csgogsi';
import "./playeroverview.scss";
import { apiUrl } from '../../API';
interface IProps {
player: I.Player,
@@ -14,21 +12,34 @@ interface IProps {
round: number
}
export default class PlayerOverview extends React.Component<IProps> {
sum = (data: number[]) => data.reduce((a, b) => a + b, 0);
const sum = (data: number[]) => data.reduce((a, b) => a + b, 0);
getData = () => {
const { veto, player, round } = this.props;
if(!player || !veto || !veto.rounds) return null;
const calcWidth = (val: number | string, max?: number) => {
const value = Number(val);
if(value === 0) return 0;
let maximum = max;
if(!maximum) {
maximum = Math.ceil(value/100)*100;
}
if(value > maximum){
return 100;
}
return 100*value/maximum;
}
const PlayerOverview = ({ player, show, veto, players, round }: IProps) => {
if(!player || !veto || !veto.rounds) return null;
const getData = () => {
if(!veto.rounds) return null;
const stats = veto.rounds.map(round => round ? round.players[player.steamid] : {
kills: 0,
killshs: 0,
damage: 0
}).filter(data => !!data);
const overall = {
damage: this.sum(stats.map(round => round.damage)),
kills: this.sum(stats.map(round => round.kills)),
killshs: this.sum(stats.map(round => round.killshs)),
damage: sum(stats.map(round => round.damage)),
kills: sum(stats.map(round => round.kills)),
killshs: sum(stats.map(round => round.killshs)),
};
const data = {
adr: stats.length !== 0 ? (overall.damage/(round-1)).toFixed(0) : '0',
@@ -39,66 +50,51 @@ export default class PlayerOverview extends React.Component<IProps> {
}
return data;
}
calcWidth = (val: number | string, max?: number) => {
const value = Number(val);
if(value === 0) return 0;
let maximum = max;
if(!maximum) {
maximum = Math.ceil(value/100)*100;
}
if(value > maximum){
return 100;
}
return 100*value/maximum;
}
render() {
const { player, veto, players } = this.props;
const data = this.getData();
if(!player || !veto || !veto.rounds || !data) return null;
let url = null;
// const avatarData = avatars.find(avatar => avatar.steamid === player.steamid);
const avatarData = avatars[player.steamid];
if(avatarData && avatarData.url){
url = avatarData.url;
}
const countryName = player.country ? getCountry(player.country) : null;
let side = '';
const inGamePlayer = players.find(inGamePlayer => inGamePlayer.steamid === player.steamid);
if(inGamePlayer) side = inGamePlayer.team.side;
return (
<div className={`player-overview ${this.props.show ? 'show':''} ${side}`}>
<div className="player-overview-picture">
{url ? <img src={url} alt={`${player.username}'s avatar`}/> : null}
</div>
<div className="player-overview-username">{url && countryName ? <img src={`${apiUrl}files/img/flags/${countryName.replace(/ /g, "-")}.png`} className="flag" alt={countryName}/> : null }{player.username.toUpperCase()}</div>
<div className="player-overview-stats">
<div className="player-overview-stat">
<div className="label">KILLS: {data.kills}</div>
<div className="panel">
<div className="filling" style={{width:`${this.calcWidth(data.kills, data.kills <= 30 ? 30 : 40)}%`}}></div>
</div>
const data = getData();
if(!data) return null;
const url = player.avatar;
const countryName = player.country ? getCountry(player.country) : null;
let side = '';
const inGamePlayer = players.find(inGamePlayer => inGamePlayer.steamid === player.steamid);
if(inGamePlayer) side = inGamePlayer.team.side;
return (
<div className={`player-overview ${show ? 'show':''} ${side}`}>
<div className="player-overview-picture">
{url ? <img src={url} alt={`${player.username}'s avatar`}/> : null}
</div>
<div className="player-overview-username">{url && countryName ? <img src={`${apiUrl}files/img/flags/${countryName.replace(/ /g, "-")}.png`} className="flag" alt={countryName}/> : null }{player.username.toUpperCase()}</div>
<div className="player-overview-stats">
<div className="player-overview-stat">
<div className="label">KILLS: {data.kills}</div>
<div className="panel">
<div className="filling" style={{width:`${calcWidth(data.kills, data.kills <= 30 ? 30 : 40)}%`}}></div>
</div>
<div className="player-overview-stat">
<div className="label">HS: {data.hsp}%</div>
<div className="panel">
<div className="filling" style={{width:`${this.calcWidth(data.hsp, 100)}%`}}></div>
</div>
</div>
<div className="player-overview-stat">
<div className="label">HS: {data.hsp}%</div>
<div className="panel">
<div className="filling" style={{width:`${calcWidth(data.hsp, 100)}%`}}></div>
</div>
<div className="player-overview-stat">
<div className="label">ADR: {data.adr}</div>
<div className="panel">
<div className="filling" style={{width:`${this.calcWidth(data.adr)}%`}}></div>
</div>
</div>
<div className="player-overview-stat">
<div className="label">ADR: {data.adr}</div>
<div className="panel">
<div className="filling" style={{width:`${calcWidth(data.adr)}%`}}></div>
</div>
<div className="player-overview-stat">
<div className="label">KPR: {data.kpr}</div>
<div className="panel">
<div className="filling" style={{width:`${this.calcWidth(Number(data.kpr)*100)}%`}}></div>
</div>
</div>
<div className="player-overview-stat">
<div className="label">KPR: {data.kpr}</div>
<div className="panel">
<div className="filling" style={{width:`${calcWidth(Number(data.kpr)*100)}%`}}></div>
</div>
</div>
</div>
);
}
</div>
);
}
export default PlayerOverview;
+44 -64
View File
@@ -1,70 +1,50 @@
import React from 'react';
import CameraContainer from '../Camera/Container';
import CameraContainer from "../Camera/Container";
import PlayerCamera from "./../Camera/Camera";
import { avatars } from './../../api/avatars';
import { Skull } from './../../assets/Icons';
import { configs } from '../../App';
import { apiUrl } from '../../api/api';
import { Skull } from "./../../assets/Icons";
import { useConfig } from "../../API/contexts/actions";
import { apiUrl } from "../../API";
interface IProps {
steamid: string,
teamId?: string | null,
slot?: number,
height?: number,
width?: number,
showSkull?: boolean,
showCam?: boolean,
sidePlayer?: boolean
steamid: string;
url: string | null;
slot?: number;
height?: number;
width?: number;
showSkull?: boolean;
showCam?: boolean;
sidePlayer?: boolean;
teamId?: string | null
}
export default class Avatar extends React.Component<IProps, { replaceAvatar: 'never' | 'if_missing' | 'always' }> {
constructor(props: IProps){
super(props);
this.state = {
replaceAvatar: 'never'
}
}
componentDidMount() {
const onDataChange = (data:any) => {
if(!data) return;
const display = data.display_settings;
if(!display) return;
this.setState({
replaceAvatar: display.replace_avatars || 'never'
})
};
configs.onChange(onDataChange);
onDataChange(configs.data);
}
getAvatarUrl = () => {
const avatarData = avatars[this.props.steamid] && avatars[this.props.steamid].url ? avatars[this.props.steamid].url : null;
const Avatar = (
{ steamid, url, height, width, showCam, showSkull, sidePlayer, teamId }: IProps,
) => {
const data = useConfig("display_settings");
if(this.state.replaceAvatar === 'always' || (this.state.replaceAvatar === 'if_missing' && !avatarData)){
return this.props.teamId ? `${apiUrl}api/teams/logo/${this.props.teamId}` : avatarData || null;
}
return avatarData || null;
}
render() {
const { showCam, steamid, width, height, showSkull, sidePlayer } = this.props;
//const url = avatars.filter(avatar => avatar.steamid === this.props.steamid)[0];
const avatarUrl = this.getAvatarUrl();
if (!avatarUrl) {
return null;
}
return (
<div className={`avatar`}>
{
showCam ? ( sidePlayer ? <div className="videofeed"><PlayerCamera steamid={steamid} visible={true} /></div> : <CameraContainer observedSteamid={steamid} />) : null
}
{
showSkull ? <Skull height={height} width={width} /> : <img src={avatarUrl} height={height} width={width} alt={'Avatar'} />
}
</div>
);
}
}
const avatarUrl = teamId && (data?.replace_avatars === "always" || (data?.replace_avatars === "if_missing" && !url)) ? `${apiUrl}api/teams/logo/${teamId}` : url;
if(!avatarUrl && !showCam) return null;
return (
<div className={`avatar`}>
{showCam
? (sidePlayer
? (
<div className="videofeed">
<PlayerCamera steamid={steamid} visible={true} />
</div>
)
: <CameraContainer observedSteamid={steamid} />)
: null}
{showSkull
? <Skull height={height} width={width} />
: (
avatarUrl ? <img
src={avatarUrl}
height={height}
width={width}
alt={"Avatar"}
/> : null
)}
</div>
);
};
export default Avatar;
+71 -91
View File
@@ -1,106 +1,86 @@
import React from "react";
import { Player } from "csgogsi-socket";
import React, { useState } from "react";
import { Player } from "csgogsi";
import Weapon from "./../Weapon/Weapon";
import Avatar from "./Avatar";
import TeamLogo from "./../MatchBar/TeamLogo";
import "./observed.scss";
import { apiUrl } from './../../api/api';
import { getCountry } from "./../countries";
import { ArmorHelmet, ArmorFull, HealthFull, Bullets } from './../../assets/Icons';
import { Veto } from "../../api/interfaces";
import { actions } from "../../App";
import { apiUrl } from './../../API';
import { useAction } from "../../API/contexts/actions";
class Statistic extends React.PureComponent<{ label: string; value: string | number, }> {
render() {
return (
<div className="stat">
<div className="label">{this.props.label}</div>
<div className="value">{this.props.value}</div>
</div>
);
}
}
export default class Observed extends React.Component<{ player: Player | null, veto: Veto | null, round: number }, { showCam: boolean }> {
constructor(props: any){
super(props);
this.state = {
showCam: true
}
}
componentDidMount() {
actions.on('toggleCams', () => {
console.log(this.state.showCam)
this.setState({ showCam: !this.state.showCam });
});
}
getAdr = () => {
const { veto, player } = this.props;
if (!player || !veto || !veto.rounds) return null;
const damageInRounds = veto.rounds.map(round => round ? round.players[player.steamid] : {
kills: 0,
killshs: 0,
damage: 0
}).filter(data => !!data).map(roundData => roundData.damage);
return damageInRounds.reduce((a, b) => a + b, 0) / (this.props.round - 1);
}
render() {
if (!this.props.player) return '';
const { player } = this.props;
const country = player.country || player.team.country;
const weapons = Object.values(player.weapons).map(weapon => ({ ...weapon, name: weapon.name.replace("weapon_", "") }));
const currentWeapon = weapons.filter(weapon => weapon.state === "active")[0];
const grenades = weapons.filter(weapon => weapon.type === "Grenade");
const { stats } = player;
const ratio = stats.deaths === 0 ? stats.kills : stats.kills / stats.deaths;
const countryName = country ? getCountry(country) : null;
return (
<div className={`observed ${player.team.side}`}>
<div className="main_row">
{<Avatar teamId={player.team.id} steamid={player.steamid} height={140} width={140} showCam={this.state.showCam} slot={player.observer_slot} />}
<TeamLogo team={player.team} height={35} width={35} />
<div className="username_container">
<div className="username">{player.name}</div>
<div className="real_name">{player.realName}</div>
</div>
<div className="flag">{countryName ? <img src={`${apiUrl}files/img/flags/${countryName.replace(/ /g, "-")}.png`} alt={countryName} /> : ''}</div>
<div className="grenade_container">
{grenades.map(grenade => <React.Fragment key={`${player.steamid}_${grenade.name}_${grenade.ammo_reserve || 1}`}>
<Weapon weapon={grenade.name} active={grenade.state === "active"} isGrenade />
{
grenade.ammo_reserve === 2 ? <Weapon weapon={grenade.name} active={grenade.state === "active"} isGrenade /> : null}
</React.Fragment>)}
</div>
const Statistic = React.memo(({ label, value }: { label: string; value: string | number, }) => {
return (
<div className="stat">
<div className="label">{label}</div>
<div className="value">{value}</div>
</div>
);
});
const Observed = ({ player }: { player: Player | null }) => {
const [ showCam, setShowCam ] = useState(true);
useAction('toggleCams', () => {
setShowCam(p => !p);
});
if (!player) return null;
const country = player.country || player.team.country;
const currentWeapon = player.weapons.filter(weapon => weapon.state === "active")[0];
const grenades = player.weapons.filter(weapon => weapon.type === "Grenade");
const { stats } = player;
const ratio = stats.deaths === 0 ? stats.kills : stats.kills / stats.deaths;
const countryName = country ? getCountry(country) : null;
return (
<div className={`observed ${player.team.side}`}>
<div className="main_row">
<Avatar teamId={player.team.id} url={player.avatar} steamid={player.steamid} height={140} width={140} showCam={showCam} slot={player.observer_slot} />
<TeamLogo team={player.team} height={35} width={35} />
<div className="username_container">
<div className="username">{player.name}</div>
<div className="real_name">{player.realName}</div>
</div>
<div className="stats_row">
<div className="health_armor_container">
<div className="health-icon icon">
<HealthFull />
</div>
<div className="health text">{player.state.health}</div>
<div className="armor-icon icon">
{player.state.helmet ? <ArmorHelmet /> : <ArmorFull />}
</div>
<div className="health text">{player.state.armor}</div>
<div className="flag">{countryName ? <img src={`${apiUrl}files/img/flags/${countryName.replace(/ /g, "-")}.png`} alt={countryName} /> : ''}</div>
<div className="grenade_container">
{grenades.map(grenade => <React.Fragment key={`${player.steamid}_${grenade.name}_${grenade.ammo_reserve || 1}`}>
<Weapon weapon={grenade.name} active={grenade.state === "active"} isGrenade />
{
grenade.ammo_reserve === 2 ? <Weapon weapon={grenade.name} active={grenade.state === "active"} isGrenade /> : null}
</React.Fragment>)}
</div>
</div>
<div className="stats_row">
<div className="health_armor_container">
<div className="health-icon icon">
<HealthFull />
</div>
<div className="statistics">
<Statistic label={"K"} value={stats.kills} />
<Statistic label={"A"} value={stats.assists} />
<Statistic label={"D"} value={stats.deaths} />
<Statistic label={"K/D"} value={ratio.toFixed(2)} />
<div className="health text">{player.state.health}</div>
<div className="armor-icon icon">
{player.state.helmet ? <ArmorHelmet /> : <ArmorFull />}
</div>
<div className="ammo">
<div className="ammo_icon_container">
<Bullets />
</div>
<div className="ammo_counter">
<div className="ammo_clip">{(currentWeapon && currentWeapon.ammo_clip) || "-"}</div>
<div className="ammo_reserve">/{(currentWeapon && currentWeapon.ammo_reserve) || "-"}</div>
</div>
<div className="health text">{player.state.armor}</div>
</div>
<div className="statistics">
<Statistic label={"K"} value={stats.kills} />
<Statistic label={"A"} value={stats.assists} />
<Statistic label={"D"} value={stats.deaths} />
<Statistic label={"K/D"} value={ratio.toFixed(2)} />
</div>
<div className="ammo">
<div className="ammo_icon_container">
<Bullets />
</div>
<div className="ammo_counter">
<div className="ammo_clip">{(currentWeapon && currentWeapon.ammo_clip) || "-"}</div>
<div className="ammo_reserve">/{(currentWeapon && currentWeapon.ammo_reserve) || "-"}</div>
</div>
</div>
</div>
);
}
</div>
);
}
export default Observed;
+11 -10
View File
@@ -1,10 +1,10 @@
import React from "react";
import * as I from "csgogsi-socket";
import * as I from "csgogsi";
import Weapon from "./../Weapon/Weapon";
import Avatar from "./Avatar";
import Armor from "./../Indicators/Armor";
import Bomb from "./../Indicators/Bomb";
import Defuse from "./../Indicators/Defuse";
import React from "react";
interface IProps {
player: I.Player,
@@ -24,9 +24,9 @@ const compareWeapon = (weaponOne: I.WeaponRaw, weaponTwo: I.WeaponRaw) => {
return false;
}
const compareWeapons = (weaponsObjectOne: { [key: string]: I.WeaponRaw }, weaponsObjectTwo: { [key: string]: I.WeaponRaw }) => {
const weaponsOne = Object.values(weaponsObjectOne).sort((a, b) => (a.name as any) - (b.name as any))
const weaponsTwo = Object.values(weaponsObjectTwo).sort((a, b) => (a.name as any) - (b.name as any))
const compareWeapons = (weaponsObjectOne: I.Weapon[], weaponsObjectTwo: I.Weapon[]) => {
const weaponsOne = [...weaponsObjectOne].sort((a, b) => a.name.localeCompare(b.name))
const weaponsTwo = [...weaponsObjectTwo].sort((a, b) => a.name.localeCompare(b.name))
if (weaponsOne.length !== weaponsTwo.length) return false;
@@ -58,6 +58,8 @@ const arePlayersEqual = (playerOne: I.Player, playerTwo: I.Player) => {
playerOne.state.equip_value === playerTwo.state.equip_value &&
playerOne.state.adr === playerTwo.state.adr &&
playerOne.avatar === playerTwo.avatar &&
!!playerOne.team.id === !!playerTwo.team.id &&
playerOne.team.side === playerTwo.team.side &&
playerOne.country === playerTwo.country &&
playerOne.realName === playerTwo.realName &&
compareWeapons(playerOne.weapons, playerTwo.weapons)
@@ -65,7 +67,6 @@ const arePlayersEqual = (playerOne: I.Player, playerTwo: I.Player) => {
return false;
}
const Player = ({ player, isObserved }: IProps) => {
const weapons = Object.values(player.weapons).map(weapon => ({ ...weapon, name: weapon.name.replace("weapon_", "") }));
@@ -76,7 +77,7 @@ const Player = ({ player, isObserved }: IProps) => {
return (
<div className={`player ${player.state.health === 0 ? "dead" : ""} ${isObserved ? 'active' : ''}`}>
<div className="player_data">
<Avatar teamId={player.team.id} steamid={player.steamid} height={57} width={57} showSkull={false} showCam={false} sidePlayer={true} />
<Avatar teamId={player.team.id} steamid={player.steamid} url={player.avatar} height={57} width={57} showSkull={false} showCam={false} sidePlayer={true} />
<div className="dead-stats">
<div className="labels">
<div className="stat-label">K</div>
@@ -104,7 +105,7 @@ const Player = ({ player, isObserved }: IProps) => {
<div className="row">
<div className="armor_and_utility">
<Bomb player={player} />
<Armor player={player} />
<Armor health={player.state.health} armor={player.state.armor} helmet={player.state.helmet} />
<Defuse player={player} />
</div>
<div className="money">${player.state.money}</div>
@@ -131,5 +132,5 @@ const arePropsEqual = (prevProps: Readonly<IProps>, nextProps: Readonly<IProps>)
return arePlayersEqual(prevProps.player, nextProps.player);
}
//export default React.memo(Player, arePropsEqual);
export default Player;
export default React.memo(Player, arePropsEqual);
//export default Player;
+12 -15
View File
@@ -1,6 +1,5 @@
import React from 'react';
import Player from './Player'
import * as I from 'csgogsi-socket';
import * as I from 'csgogsi';
import './players.scss';
interface Props {
@@ -9,17 +8,15 @@ interface Props {
side: 'right' | 'left',
current: I.Player | null,
}
export default class TeamBox extends React.Component<Props> {
render() {
return (
<div className={`teambox ${this.props.team.side} ${this.props.side}`}>
{this.props.players.map(player => <Player
key={player.steamid}
player={player}
isObserved={!!(this.props.current && this.props.current.steamid === player.steamid)}
/>)}
</div>
);
}
const TeamBox = ({players, team, side, current}: Props) => {
return (
<div className={`teambox ${team.side} ${side}`}>
{players.map(player => <Player
key={player.steamid}
player={player}
isObserved={!!(current && current.steamid === player.steamid)}
/>)}
</div>
);
}
export default TeamBox;
+129 -74
View File
@@ -1,9 +1,9 @@
import React from 'react';
import { Bomb } from 'csgogsi-socket';
import maps, { ScaleConfig, MapConfig, ZoomAreas } from './maps';
import './index.css';
import type { Bomb, Side } from 'csgogsi';
import maps, { MapConfig, ZoomAreas } from './maps';
import './index.scss';
import { RadarPlayerObject, RadarGrenadeObject } from './interface';
import config from './config';
import { parsePosition } from './utils';
interface IProps {
players: RadarPlayerObject[];
grenades: RadarGrenadeObject[];
@@ -12,99 +12,154 @@ interface IProps {
zoom?: ZoomAreas;
mapConfig: MapConfig,
reverseZoom: string,
parsePosition: (position: number[], size: number, config: ScaleConfig) => number[]
}
const isShooting = (lastShoot: number) => (new Date()).getTime() - lastShoot <= 250;
type Explosion = {
position: number[],
grenadeId: string
}
const isShooting = (lastShoot: number) => (new Date()).getTime() - lastShoot <= 250;
class App extends React.Component<IProps> {
constructor(props: IProps) {
super(props);
this.state = {
players: [],
grenades: [],
bomb: null
}
/*
const SMOKE_PARTICLE_BASE_AMOUNT = 10;
//const PARTICLE_MAP_SOURCE = Array(SMOKE_PARTICLE_BASE_AMOUNT**2).fill(0);
const SMOKE_PARTICLE_SIZE_ABSOLUT = config.smokeSize/SMOKE_PARTICLE_BASE_AMOUNT;
const PARTICLE_SIDE = `${SMOKE_PARTICLE_SIZE_ABSOLUT}px`;
const FRAG_RADIUS = 40;
//const MAX_DISTANCE_BETWEEN_FRAG_AND_SMOKE = config.smokeSize + FRAG_RADIUS;
const getDistance = (X: number[], Y: number[]) => {
const a = X[0] - Y[0];
const b = X[1] - Y[1];
return Math.sqrt( a*a + b*b );
}
const getPosOfIndex = (index: number, origin: number[]) => {
const leftI = index%10;
const topI = Math.floor(index/10);
return ([origin[0] - config.smokeSize/2 + (leftI + 0.5) * SMOKE_PARTICLE_SIZE_ABSOLUT, origin[1] - config.smokeSize/2 + (topI + 0.5)*SMOKE_PARTICLE_SIZE_ABSOLUT]);
}
const Particle = ({ index, explosions, origin }: { index: number, origin: number[], explosions: Explosion[] }) => {
const PARTICLE_POSITION = getPosOfIndex(index, origin);
const isHidden = getDistance(PARTICLE_POSITION, origin) > config.smokeSize/2 || explosions.some(expl => getDistance(expl.position, PARTICLE_POSITION) <= FRAG_RADIUS);
return (<div className={`particle ${isHidden ? 'hide':''}`} style={{ width: PARTICLE_SIDE, height: PARTICLE_SIDE}}/>);
}
*/
const Grenade = ({ reverseZoom, type, state, visible, position, flames, side }: { explosions: Explosion[], reverseZoom: string, side: Side | null, flames: boolean, type: RadarGrenadeObject["type"], state: RadarGrenadeObject["state"], visible: boolean, position: number[] }) => {
if (flames) {
return null;
}
renderGrenade = (grenade: RadarGrenadeObject) => {
if ("flames" in grenade) {
return null;
}
const { reverseZoom } = this.props;
if(type === "smoke" && (state === "landed" || state === "exploded")){
return (
<div key={grenade.id} className={`grenade ${grenade.type} ${grenade.side || ''} ${grenade.state} ${grenade.visible ? 'visible':'hidden'}`}
<div className={`grenade ${type} ${state} ${side || ''} ${visible ? 'visible':'hidden'}`}
style={{
transform: `translateX(${grenade.position[0].toFixed(2)}px) translateY(${grenade.position[1].toFixed(2)}px) translateZ(10px) scale(${reverseZoom})`,
transform: `translateX(${position[0]}px) translateY(${position[1]}px) translateZ(10px) scale(${reverseZoom})`,
}}>
<div className="content" style={{ width: config.smokeSize, height: config.smokeSize }}>
<div className="explode-point"></div>
<div className="background"></div>
<div className="background">
</div>
</div>
</div>
)
}
renderDot = (player: RadarPlayerObject) => {
const { reverseZoom } = this.props;
return (
<div className={`grenade ${type} ${state} ${side || ''} ${visible ? 'visible':'hidden'}`}
style={{
transform: `translateX(${position[0]}px) translateY(${position[1]}px) translateZ(10px) scale(${reverseZoom})`,
}}>
<div className="content">
<div className="explode-point"></div>
<div className="background"></div>
</div>
</div>
)
}
const Bomb = ({ bomb, mapConfig, reverseZoom }: { reverseZoom: string, bomb?: Bomb | null, mapConfig: MapConfig }) => {
if(!bomb) return null;
if(bomb.state === "carried" || bomb.state === "planting") return null;
if("config" in mapConfig){
const position = parsePosition(bomb.position, mapConfig.config);
if(!position) return null;
return (
<div key={player.id}
className={`player ${player.shooting? 'shooting':''} ${player.flashed ? 'flashed':''} ${player.side} ${player.hasBomb ? 'hasBomb':''} ${player.isActive ? 'active' : ''} ${!player.isAlive ? 'dead' : ''} ${player.visible ? 'visible':'hidden'}`}
<div className={`bomb ${bomb.state} visible`}
style={{
transform: `translateX(${player.position[0].toFixed(2)}px) translateY(${player.position[1].toFixed(2)}px) translateZ(10px) scale(${reverseZoom})`,
transform: `translateX(${position[0].toFixed(2)}px) translateY(${position[1].toFixed(2)}px) translateZ(10px) scale(${reverseZoom})`
}}>
<div className="content">
<div className="explode-point"></div>
<div className="background"></div>
</div>
</div>
)
}
return mapConfig.configs.map(config => {
const position = parsePosition(bomb.position, config.config);
if(!position) return null;
return (
<div className={`bomb ${bomb.state} ${config.isVisible(bomb.position[2]) ? 'visible':'hidden'}`}
style={{
transform: `translateX(${position[0].toFixed(2)}px) translateY(${position[1].toFixed(2)}px) translateZ(10px) scale(${reverseZoom})`
}}>
<div className="content">
<div className="explode-point"></div>
<div className="background"></div>
</div>
</div>
)
});
}
const PlayerDot = ({ player, reverseZoom }: { reverseZoom: string, player: RadarPlayerObject }) => {
const isShootingNow = isShooting(player.lastShoot);
//console.log('x',isShooting(player.lastShoot), player.steamid);
return (
<div
className={`player ${player.shooting? 'shooting':''} ${player.flashed ? 'flashed':''} ${player.side} ${player.hasBomb ? 'hasBomb':''} ${player.isActive ? 'active' : ''} ${!player.isAlive ? 'dead' : ''} ${player.visible ? 'visible':'hidden'}`}
style={{
transform: `translateX(${player.position[0].toFixed(2)}px) translateY(${player.position[1].toFixed(2)}px) translateZ(10px) scale(${reverseZoom})`,
}}>
<div className="content" style={{
width: config.playerSize * player.scale,
height: config.playerSize * player.scale,
height: config.playerSize * player.scale
}}>
<div className="background-fire" style={{ transform: `rotate(${-90 + player.position[2]}deg)`, opacity: isShooting(player.lastShoot) ? 1 : 0 }} ><div className="bg"/></div>
<div className="background" style={{ transform: `rotate(${45 + player.position[2]}deg)` }}></div>
<div className="label">{player.label}</div>
</div>
)
}
renderBomb = () => {
const { bomb, mapConfig, reverseZoom } = this.props;
if(!bomb) return null;
if(bomb.state === "carried" || bomb.state === "planting") return null;
if("config" in mapConfig){
const position = this.props.parsePosition(bomb.position, 30, mapConfig.config);
if(!position) return null;
return (
<div className={`bomb ${bomb.state} visible`}
style={{
transform: `translateX(${position[0].toFixed(2)}px) translateY(${position[1].toFixed(2)}px) translateZ(10px) scale(${reverseZoom})`
}}>
<div className="explode-point"></div>
<div className="background"></div>
<div className="background-fire" style={{ transform: `rotate(${-90 + player.position[2]}deg)`, opacity: isShootingNow ? 1 : 0 }} ><div className="bg"/></div>
<div className="background" style={{ transform: `rotate(${45 + player.position[2]}deg)` }}></div>
<div className="label">{player.label}</div>
</div>
)
}
return mapConfig.configs.map(config => {
const position = this.props.parsePosition(bomb.position, 30, config.config);
if(!position) return null;
return (
<div className={`bomb ${bomb.state} ${config.isVisible(bomb.position[2]) ? 'visible':'hidden'}`}
style={{
transform: `translateX(${position[0].toFixed(2)}px) translateY(${position[1].toFixed(2)}px) translateZ(10px)`
}}>
<div className="explode-point"></div>
<div className="background"></div>
</div>
)
});
}
render() {
const { players, grenades, zoom } = this.props;
</div>
)
}
const style: React.CSSProperties = { backgroundImage: `url(${maps[this.props.mapName].file})` }
const Radar = ({ players, grenades, mapConfig, bomb, mapName, zoom, reverseZoom }: IProps) => {
//if(players.length === 0) return null;
const style: React.CSSProperties = { backgroundImage: `url(${maps[mapName].file})` }
if(zoom){
style.transform = `scale(${zoom.zoom})`;
style.transformOrigin = `${zoom.origin[0]}px ${zoom.origin[1]}px`;
}
//if(players.length === 0) return null;
const explosions = grenades.filter(grenade => grenade.type === "frag" && grenade.state === "exploded");
return <div className="map" style={style}>
{players.map(this.renderDot)}
{grenades.map(this.renderGrenade)}
{this.renderBomb()}
{players.map(player => <PlayerDot reverseZoom={reverseZoom} key={player.id} player={player} />)}
{grenades.map(grenade => <Grenade explosions={explosions.map(g => ({ position: g.position, grenadeId: g.id }))} reverseZoom={reverseZoom} side={grenade.side} key={grenade.id} type={grenade.type} state={grenade.state} visible={grenade.visible} position={grenade.position} flames={"flames" in grenade} />)}
<Bomb reverseZoom={reverseZoom} bomb={bomb} mapConfig={mapConfig} />
</div>;
}
}
export default App;
export default Radar;
+58 -301
View File
@@ -1,322 +1,79 @@
import React from 'react';
import { Player, Bomb } from 'csgogsi-socket';
import maps, { ScaleConfig } from './maps';
import { Player, Bomb, Grenade, FragOrFireBombOrFlashbandGrenade } from 'csgogsi';
import maps from './maps';
import LexoRadar from './LexoRadar';
import { ExtendedGrenade, Grenade, RadarPlayerObject, RadarGrenadeObject } from './interface';
import config from './config';
import { RadarPlayerObject, RadarGrenadeObject } from './interface';
import { EXPLODE_TIME_FRAG, explosionPlaces, extendGrenade, extendPlayer, grenadesStates, playersStates } from './utils';
import { GSI } from '../../../API/HUD';
const DESCALE_ON_ZOOM = true;
let playersStates: Player[][] = [];
let grenadesStates: ExtendedGrenade[][] = [];
const directions: Record<string, number> = {};
type ShootingState = {
ammo: number,
weapon: string,
lastShoot: number
}
let shootingState: Record<string, ShootingState> = {};
const calculateDirection = (player: Player) => {
if (directions[player.steamid] && !player.state.health) return directions[player.steamid];
const [forwardV1, forwardV2] = player.forward;
let direction = 0;
const [axisA, axisB] = [Math.asin(forwardV1), Math.acos(forwardV2)].map(axis => axis * 180 / Math.PI);
if (axisB < 45) {
direction = Math.abs(axisA);
} else if (axisB > 135) {
direction = 180 - Math.abs(axisA);
} else {
direction = axisB;
}
if (axisA < 0) {
direction = -(direction -= 360);
}
if (!directions[player.steamid]) {
directions[player.steamid] = direction;
}
const previous = directions[player.steamid];
let modifier = previous;
modifier -= 360 * Math.floor(previous / 360);
modifier = -(modifier -= direction);
if (Math.abs(modifier) > 180) {
modifier -= 360 * Math.abs(modifier) / modifier;
}
directions[player.steamid] += modifier;
return directions[player.steamid];
}
interface IProps {
players: Player[],
bomb?: Bomb | null,
player: Player | null,
grenades?: any
grenades: Grenade[]
size?: number,
mapName: string
}
class App extends React.Component<IProps> {
round = (n: number) => {
const r = 0.02;
return Math.round(n / r) * r;
GSI.prependListener("data", () => {
const currentGrenades = GSI.current?.grenades || []
grenadesStates.unshift(currentGrenades);
grenadesStates.splice(5);
playersStates.unshift(GSI.current?.players || []);
playersStates.splice(5);
});
GSI.prependListener("data", data => {
const { last } = GSI;
if(!last) return;
for(const grenade of data.grenades.filter((grenade): grenade is FragOrFireBombOrFlashbandGrenade => grenade.type === "frag")){
const old = last.grenades.find((oldGrenade): oldGrenade is FragOrFireBombOrFlashbandGrenade => oldGrenade.id === grenade.id);
if(!old) continue;
if(grenade.lifetime >= EXPLODE_TIME_FRAG && old.lifetime < EXPLODE_TIME_FRAG){
explosionPlaces[grenade.id] = grenade.position;
}
}
parsePosition = (position: number[], size: number, config: ScaleConfig) => {
if (!(this.props.mapName in maps)) {
return [0, 0];
for(const grenadeId of Object.keys(explosionPlaces)){
const doesExist = data.grenades.some(grenade => grenade.id === grenadeId);
if(!doesExist){
delete explosionPlaces[grenadeId];
}
const left = config.origin.x + (position[0] * config.pxPerUX) - (size / 2);
const top = config.origin.y + (position[1] * config.pxPerUY) - (size / 2);
return [this.round(left), this.round(top)];
}
});
parseGrenadePosition = (grenade: ExtendedGrenade, config: ScaleConfig) => {
if (!("position" in grenade)) {
return null;
}
let size = 30;
if (grenade.type === "smoke") {
size = 60;
}
return this.parsePosition(grenade.position.split(", ").map(pos => Number(pos)), size, config);
}
getGrenadePosition = (grenade: ExtendedGrenade, config: ScaleConfig) => {
const grenadeData = grenadesStates.slice(0, 5).map(grenades => grenades.filter(gr => gr.id === grenade.id)[0]).filter(pl => !!pl);
if (grenadeData.length === 0) return null;
const positions = grenadeData.map(grenadeEntry => this.parseGrenadePosition(grenadeEntry, config)).filter(posData => posData !== null) as number[][];
if (positions.length === 0) return null;
const entryAmount = positions.length;
let x = 0;
let y = 0;
for (const position of positions) {
x += position[0];
y += position[1];
}
const LexoRadarContainer = ({ size = 300, mapName, bomb, player, players, grenades }: IProps) => {
const offset = (size - (size * size / 1024)) / 2;
return [x / entryAmount, y / entryAmount];
}
getPosition = (player: Player, mapConfig: ScaleConfig, scale: number) => {
const playerData = playersStates.slice(0, 5).map(players => players.filter(pl => pl.steamid === player.steamid)[0]).filter(pl => !!pl);
if (playerData.length === 0) return [0, 0];
const positions = playerData.map(playerEntry => this.parsePosition(playerEntry.position, config.playerSize * scale, mapConfig));
const entryAmount = positions.length;
let x = 0;
let y = 0;
for (const position of positions) {
x += position[0];
y += position[1];
}
const degree = calculateDirection(player);
return [x / entryAmount, y / entryAmount, degree];
}
mapPlayer = (active: Player | null) => (player: Player): RadarPlayerObject | RadarPlayerObject[] | null => {
if (!(this.props.mapName in maps)) {
return null;
}
const weapons = player.weapons ? Object.values(player.weapons) : [];
const weapon = weapons.find(weapon => weapon.state === "active" && weapon.type !== "C4" && weapon.type !== "Knife" && weapon.type !== "Grenade");
const shooting: ShootingState = { ammo: weapon && weapon.ammo_clip || 0, weapon: weapon && weapon.name || '', lastShoot: 0 };
const lastShoot = shootingState[player.steamid] || shooting;
let isShooting = false;
if (shooting.weapon === lastShoot.weapon && shooting.ammo < lastShoot.ammo) {
isShooting = true;
}
shooting.lastShoot = isShooting ? (new Date()).getTime() : lastShoot.lastShoot;
shootingState[player.steamid] = shooting;
const map = maps[this.props.mapName];
const playerObject: RadarPlayerObject = {
id: player.steamid,
label: player.observer_slot !== undefined ? player.observer_slot : "",
side: player.team.side,
position: [],
visible: true,
isActive: !!active && active.steamid === player.steamid,
forward: 0,
steamid: player.steamid,
isAlive: player.state.health > 0,
hasBomb: !!Object.values(player.weapons).find(weapon => weapon.type === "C4"),
flashed: player.state.flashed > 35,
shooting: isShooting,
lastShoot: shooting.lastShoot,
scale: 1,
player
}
if ("config" in map) {
const scale = map.config.originHeight === undefined ? 1 : (1 + (player.position[2] - map.config.originHeight) / 1000);
playerObject.scale = scale;
const position = this.getPosition(player, map.config, scale);
playerObject.position = position;
return playerObject;
}
return map.configs.map(config => {
const scale = config.config.originHeight === undefined ? 1 : (1 + (player.position[2] - config.config.originHeight) / 750);
playerObject.scale = scale;
return ({
...playerObject,
position: this.getPosition(player, config.config, scale),
id: `${player.steamid}_${config.id}`,
visible: config.isVisible(player.position[2])
})
});
}
mapGrenade = (extGrenade: ExtendedGrenade) => {
if (!(this.props.mapName in maps)) {
return null;
}
const map = maps[this.props.mapName];
if (extGrenade.type === "inferno") {
const mapFlame = (id: string) => {
if ("config" in map) {
return ({
position: this.parsePosition(extGrenade.flames[id].split(", ").map(pos => Number(pos)), 12, map.config),
id: `${id}_${extGrenade.id}`,
visible: true
});
}
return map.configs.map(config => ({
id: `${id}_${extGrenade.id}_${config.id}`,
visible: config.isVisible(extGrenade.flames[id].split(", ").map(Number)[2]),
position: this.parsePosition(extGrenade.flames[id].split(", ").map(pos => Number(pos)), 12, config.config)
}));
}
const flames = Object.keys(extGrenade.flames).map(mapFlame).flat();
const flameObjects: RadarGrenadeObject[] = flames.map(flame => ({
...flame,
side: extGrenade.side,
type: 'inferno',
state: 'landed'
}));
return flameObjects;
}
if ("config" in map) {
const position = this.getGrenadePosition(extGrenade, map.config);
if (!position) return null;
const grenadeObject: RadarGrenadeObject = {
type: extGrenade.type,
state: 'inair',
side: extGrenade.side,
position,
id: extGrenade.id,
visible: true
}
if (extGrenade.type === "smoke") {
if (extGrenade.effecttime !== "0.0") {
grenadeObject.state = "landed";
if (Number(extGrenade.effecttime) >= 16.5) {
grenadeObject.state = 'exploded';
}
}
} else if (extGrenade.type === 'flashbang' || extGrenade.type === 'frag') {
if (Number(extGrenade.lifetime) >= 1.25) {
grenadeObject.state = 'exploded';
}
}
return grenadeObject;
}
return map.configs.map(config => {
const position = this.getGrenadePosition(extGrenade, config.config);
if (!position) return null;
const grenadeObject: RadarGrenadeObject = {
type: extGrenade.type,
state: 'inair',
side: extGrenade.side,
position,
id: `${extGrenade.id}_${config.id}`,
visible: config.isVisible(extGrenade.position.split(", ").map(Number)[2])
}
if (extGrenade.type === "smoke") {
if (extGrenade.effecttime !== "0.0") {
grenadeObject.state = "landed";
if (Number(extGrenade.effecttime) >= 16.5) {
grenadeObject.state = 'exploded';
}
}
} else if (extGrenade.type === 'flashbang' || extGrenade.type === 'frag') {
if (Number(extGrenade.lifetime) >= 1.25) {
grenadeObject.state = 'exploded';
}
}
return grenadeObject;
}).filter((grenade): grenade is RadarGrenadeObject => grenade !== null);
}
getSideOfGrenade = (grenade: Grenade) => {
const owner = this.props.players.find(player => player.steamid === grenade.owner);
if (!owner) return null;
return owner.team.side;
}
render() {
const players: RadarPlayerObject[] = this.props.players.map(this.mapPlayer(this.props.player)).filter((player): player is RadarPlayerObject => player !== null).flat();
playersStates.unshift(this.props.players);
if (playersStates.length > 5) {
playersStates = playersStates.slice(0, 5);
}
let grenades: RadarGrenadeObject[] = [];
const currentGrenades = Object.keys(this.props.grenades as { [key: string]: Grenade }).map(grenadeId => ({ ...this.props.grenades[grenadeId], id: grenadeId, side: this.getSideOfGrenade(this.props.grenades[grenadeId]) })) as ExtendedGrenade[];
if (currentGrenades) {
grenades = currentGrenades.map(this.mapGrenade).filter(entry => entry !== null).flat() as RadarGrenadeObject[];
grenadesStates.unshift(currentGrenades);
}
if (grenadesStates.length > 5) {
grenadesStates = grenadesStates.slice(0, 5);
}
const size = this.props.size || 300;
const offset = (size - (size * size / 1024)) / 2;
const config = maps[this.props.mapName];
const zooms = config && config.zooms || [];
const activeZoom = zooms.find(zoom => zoom.threshold(players.map(pl => pl.player)));
const reverseZoom = 1/(activeZoom && activeZoom.zoom || 1);
// s*(1024-s)/2048
if (!(this.props.mapName in maps)) {
return <div className="map-container" style={{ width: size, height: size, transform: `scale(${size / 1024})`, top: -offset, left: -offset }}>
Unsupported map
</div>;
}
if (!(mapName in maps)) {
return <div className="map-container" style={{ width: size, height: size, transform: `scale(${size / 1024})`, top: -offset, left: -offset }}>
<LexoRadar
players={players}
grenades={grenades}
parsePosition={this.parsePosition}
bomb={this.props.bomb}
mapName={this.props.mapName}
mapConfig={maps[this.props.mapName]}
zoom={activeZoom}
reverseZoom={DESCALE_ON_ZOOM ? reverseZoom.toFixed(2) : '1'}
/>
Unsupported map
</div>;
}
const playersExtended: RadarPlayerObject[] = players.map(pl => extendPlayer({ player: pl, steamId: player?.steamid || null, mapName })).filter((player): player is RadarPlayerObject => player !== null).flat();
const grenadesExtended = grenades.map(grenade => extendGrenade({ grenade, side: playersExtended.find(player => player.steamid === grenade.owner)?.side || 'CT', mapName })).filter(entry => entry !== null).flat() as RadarGrenadeObject[];
const config = maps[mapName];
const zooms = config && config.zooms || [];
const activeZoom = zooms.find(zoom => zoom.threshold(playersExtended.map(pl => pl.player)));
const reverseZoom = 1/(activeZoom && activeZoom.zoom || 1);
// s*(1024-s)/2048
return <div className="map-container" style={{ width: size, height: size, transform: `scale(${size / 1024})`, top: -offset, left: -offset }}>
<LexoRadar
players={playersExtended}
grenades={grenadesExtended}
bomb={bomb}
mapName={mapName}
mapConfig={config}
zoom={activeZoom}
reverseZoom={DESCALE_ON_ZOOM ? reverseZoom.toFixed(2) : '1'}
/>
</div>;
}
export default App;
export default LexoRadarContainer;
Binary file not shown.
+2 -1
View File
@@ -1,5 +1,6 @@
const config = {
playerSize: 60,
playerSize: 70,
smokeSize: 50
}
export default config;
@@ -51,12 +51,20 @@ html, body, .map-container {
}
.map .player, .map .grenade, .map .bomb {
position: absolute;
height:30px;
width:30px;
height:0px;
width:0px;
display: flex;
align-items: center;
justify-content: center;
transition: opacity 0.5s ease;
.content {
position: absolute;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
}
/*transition: all 0.1s ease;/**/
}
.map .player .background {
@@ -66,7 +74,7 @@ html, body, .map-container {
background-position: center;
background-size: contain;
background-repeat: no-repeat;
transition:transform 0.2s ease;
transition:transform 0.2s linear;
}
.map .player .background-fire {
position: absolute;
@@ -140,10 +148,12 @@ html, body, .map-container {
}
*/
.map .player.active {
width:120%;
height:120%;
z-index: 3;
}
.map .player.active .content {
width:48px;
height:48px;
}
.map .grenade .background {
border-radius:50%;
background-size: contain;
@@ -157,9 +167,6 @@ html, body, .map-container {
opacity: 1;
transition: opacity 1s;
}
.map .grenade.smoke {
transition: all 0.5s;
}
.map .grenade.smoke.inair .background {
background-color: transparent !important;
border: none !important;
@@ -167,7 +174,6 @@ html, body, .map-container {
filter: invert(1);
}
.map .grenade.smoke.exploded .background {
opacity: 0;
}
.map .grenade.flashbang, .map .grenade.frag {
filter: invert(1);
@@ -183,6 +189,8 @@ html, body, .map-container {
.map .grenade .explode-point, .map .bomb .explode-point {
position: absolute;
width: 2px;
top: calc(50% - 1px);
left: calc(50% - 1px);
height: 2px;
border-radius: 0.08px;
}
@@ -194,7 +202,6 @@ html, body, .map-container {
opacity: 0;
}
.map .grenade.smoke .background {
border: 5px solid grey;
background-color: rgba(255,255,255,0.5);
}
.map .grenade.smoke.CT .background {
@@ -214,9 +221,8 @@ html, body, .map-container {
width:12px;
height:12px;
}
.map .grenade.smoke {
width:60px;
height:60px;
.map .grenade .content {
position: absolute;
}
.map .grenade.inferno .background {
background-color: red;
@@ -270,16 +276,29 @@ html, body, .map-container {
background: red;
}
@keyframes Hidden {
from {
}
to {
display: none !important;
}
.map .player.dead .background {
display: none;
}
.map .player.dead .label {
background: transparent;
}
.map .player.dead.CT .label, .map .player.CT .label div {
color: var(--color-new-ct);
}
.map .player.dead.T .label, .map .player.T .label div {
color: var(--color-new-t);
}
.map .hidden {
opacity: 0;
animation: Hidden 1s ease 1s 1;
animation-fill-mode: forwards;/**/
opacity: 0 !important;
}
}
.map .grenade {
&.smoke {
&.exploded, &.landed {
.background {
display: flex;
flex-wrap: wrap;
}
}
}
}
+2 -27
View File
@@ -1,4 +1,4 @@
import { Player, Side } from "csgogsi";
import { Player, Side, Grenade } from "csgogsi";
export interface RadarPlayerObject {
id: string,
@@ -26,30 +26,5 @@ export interface RadarGrenadeObject {
visible: boolean,
id: string,
}
export interface GrenadeBase {
owner: string,
type: 'decoy' | 'smoke' | 'frag' | 'firebomb' | 'flashbang' | 'inferno'
lifetime: string
}
export interface DecoySmokeGrenade extends GrenadeBase {
position: string,
velocity: string,
type: 'decoy' | 'smoke',
effecttime: string,
}
export interface DefaultGrenade extends GrenadeBase {
position: string,
type: 'frag' | 'firebomb' | 'flashbang',
velocity: string,
}
export interface InfernoGrenade extends GrenadeBase {
type: 'inferno',
flames: { [key: string]: string }
}
export type Grenade = DecoySmokeGrenade | DefaultGrenade | InfernoGrenade;
export type ExtendedGrenade = Grenade & { id: string, side: Side | null, };
export type ExtendedGrenade = Grenade & { side: Side | null, };
@@ -1,15 +0,0 @@
import radar from './radar.png'
const config = {
"config": {
"origin": {
"x": 536.3392873296655,
"y": 638.0789844851904
},
"pxPerUX": 0.1907910426894958,
"pxPerUY": -0.18993888105312648
},
"file":radar
}
export default config;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

@@ -7,8 +7,7 @@ const config = {
"y": 340.2921393569175
},
"pxPerUX": 0.20118507589946494,
"pxPerUY": -0.20138282875746794,
"originHeight": -170,
"pxPerUY": -0.20138282875746794
},
"file": radar
}
@@ -1,4 +1,3 @@
import { Player } from 'csgogsi-socket';
import radar from './radar.png'
const high = {
@@ -32,21 +31,6 @@ const config = {
isVisible: (height: number) => height < 11700,
},
],
zooms: [{
threshold: (players: Player[]) => {
const alivePlayers = players.filter(player => player.state.health);
return alivePlayers.length > 0 && alivePlayers.every(player => player.position[2] < 11700)
},
origin: [472, 1130],
zoom: 2
}, {
threshold: (players: Player[]) => {
const alivePlayers = players.filter(player => player.state.health);
return alivePlayers.length > 0 && players.filter(player => player.state.health).every(player => player.position[2] >= 11700);
},
origin: [528, 15],
zoom: 1.75
}],
file: radar
}
+5 -8
View File
@@ -6,17 +6,15 @@ import de_train from './de_train';
import de_overpass from './de_overpass';
import de_nuke from './de_nuke';
import de_vertigo from './de_vertigo';
import de_anubis from './de_anubis';
import de_ancient from './de_ancient';
import api from '../../../../api/api';
import { Player } from 'csgogsi-socket';
import api from '../../../../API';
import { Player } from 'csgogsi';
export type ZoomAreas = {
threshold: (players: Player[]) => boolean;
origin: number[],
zoom: number
}
export interface ScaleConfig {
origin: {
x:number,
@@ -29,7 +27,7 @@ export interface ScaleConfig {
interface SingleLayer {
config: ScaleConfig,
file: string,
file: string
zooms?: ZoomAreas[]
}
@@ -39,7 +37,7 @@ interface DoubleLayer {
config: ScaleConfig,
isVisible: (height: number) => boolean
}[],
file: string,
file: string
zooms?: ZoomAreas[]
}
@@ -54,8 +52,7 @@ const maps: { [key: string] : MapConfig} = {
de_overpass,
de_nuke,
de_vertigo,
de_ancient,
de_anubis
de_ancient
}
api.maps.get().then(fallbackMaps => {
+244
View File
@@ -0,0 +1,244 @@
import { Player, Side, Grenade } from "csgogsi";
import maps, { ScaleConfig } from "./maps";
import { ExtendedGrenade, RadarGrenadeObject, RadarPlayerObject } from "./interface";
import { InfernoGrenade } from "csgogsi";
export const playersStates: Player[][] = [];
export const grenadesStates: Grenade[][] = [];
const directions: { [key: string]: number } = {};
export const explosionPlaces: Record<string, number[]> = {};
type ShootingState = {
ammo: number,
weapon: string,
lastShoot: number
}
let shootingState: Record<string, ShootingState> = {};
const calculateDirection = (player: Player) => {
if (directions[player.steamid] && !player.state.health) return directions[player.steamid];
const [forwardV1, forwardV2] = player.forward;
let direction = 0;
const [axisA, axisB] = [Math.asin(forwardV1), Math.acos(forwardV2)].map(axis => axis * 180 / Math.PI);
if (axisB < 45) {
direction = Math.abs(axisA);
} else if (axisB > 135) {
direction = 180 - Math.abs(axisA);
} else {
direction = axisB;
}
if (axisA < 0) {
direction = -(direction -= 360);
}
if (!directions[player.steamid]) {
directions[player.steamid] = direction;
}
const previous = directions[player.steamid];
let modifier = previous;
modifier -= 360 * Math.floor(previous / 360);
modifier = -(modifier -= direction);
if (Math.abs(modifier) > 180) {
modifier -= 360 * Math.abs(modifier) / modifier;
}
directions[player.steamid] += modifier;
return directions[player.steamid];
}
export const round = (n: number) => {
const r = 0.02;
return Math.round(n / r) * r;
}
export const parsePosition = (position: number[], config: ScaleConfig) => {
const left = config.origin.x + (position[0] * config.pxPerUX);
const top = config.origin.y + (position[1] * config.pxPerUY);
return [round(left), round(top)];
}
export const parsePlayerPosition = (player: Player, mapConfig: ScaleConfig) => {
const playerData = playersStates.slice(0, 5).map(players => players.filter(pl => pl.steamid === player.steamid)[0]).filter(pl => !!pl);
if (playerData.length === 0) return [0, 0];
const positions = playerData.map(playerEntry => parsePosition(playerEntry.position, mapConfig));
const entryAmount = positions.length;
let x = 0;
let y = 0;
for (const position of positions) {
x += position[0];
y += position[1];
}
const degree = calculateDirection(player);
return [x / entryAmount, y / entryAmount, degree];
}
const parseGrenadePosition = (grenade: ExtendedGrenade, config: ScaleConfig) => {
if(grenade.id in explosionPlaces) return parsePosition(explosionPlaces[grenade.id], config);
const grenadeData = grenadesStates.slice(0, 5).map(grenades => grenades.filter(gr => gr.id === grenade.id)[0]).filter(pl => !!pl);
if (grenadeData.length === 0) return "position" in grenade ? parsePosition(grenade.position, config) : null;
const positions = grenadeData.map(grenadeEntry => ("position" in grenadeEntry ? parsePosition(grenadeEntry.position, config) : null)).filter(posData => posData !== null) as number[][];
if (positions.length === 0) return null;
const entryAmount = positions.length;
let x = 0;
let y = 0;
for (const position of positions) {
x += position[0];
y += position[1];
}
return [x / entryAmount, y / entryAmount];
}
export const EXPLODE_TIME_FRAG = 1.6;
export const EXPLODE_TIME_FLASH = 1.45;
export const extendGrenade = ({grenade, mapName, side }: { side: Side, grenade: Grenade, mapName: string}) => {
// const owner = this.props.players.find(player => player.steamid === grenade.owner);
const extGrenade: ExtendedGrenade = {
...grenade,
side:/* owner?.team.side ||*/ side
}
const map = maps[mapName];
if (extGrenade.type === "inferno") {
const mapFlame = (flame: InfernoGrenade["flames"][number]) => {
if ("config" in map) {
return ({
position: parsePosition(flame.position, map.config),
id: `${flame.id}_${extGrenade.id}`,
visible: true
});
}
return map.configs.map(config => ({
id: `${flame}_${extGrenade.id}_${config.id}`,
visible: config.isVisible(flame.position[2]),
position: parsePosition(flame.position, config.config)
}));
}
const flames = extGrenade.flames.map(mapFlame).flat();
const flameObjects: RadarGrenadeObject[] = flames.map(flame => ({
...flame,
side: extGrenade.side,
type: 'inferno',
state: 'landed'
}));
return flameObjects;
}
if ("config" in map) {
const position = parseGrenadePosition(extGrenade, map.config);
if (!position) return null;
const grenadeObject: RadarGrenadeObject = {
type: extGrenade.type,
state: 'inair',
side: extGrenade.side,
position,
id: extGrenade.id,
visible: true
}
if (extGrenade.type === "smoke") {
if (extGrenade.effecttime !== 0) {
grenadeObject.state = "landed";
if (extGrenade.effecttime >= 16.5) {
grenadeObject.state = 'exploded';
}
}
} else if ((extGrenade.type === 'flashbang' && extGrenade.lifetime >= EXPLODE_TIME_FLASH) || (extGrenade.type === 'frag' && extGrenade.lifetime >= EXPLODE_TIME_FRAG)) {
grenadeObject.state = 'exploded';
}
return grenadeObject;
}
return map.configs.map(config => {
const position = parseGrenadePosition(extGrenade, config.config);
if (!position) return null;
const grenadeObject: RadarGrenadeObject = {
type: extGrenade.type,
state: 'inair',
side: extGrenade.side,
position,
id: `${extGrenade.id}_${config.id}`,
visible: config.isVisible(extGrenade.position[2])
}
if (extGrenade.type === "smoke") {
if (extGrenade.effecttime !== 0) {
grenadeObject.state = "landed";
if (extGrenade.effecttime >= 16.5) {
grenadeObject.state = 'exploded';
}
}
} else if ((extGrenade.type === 'flashbang' && extGrenade.lifetime >= EXPLODE_TIME_FLASH) || (extGrenade.type === 'frag' && extGrenade.lifetime >= EXPLODE_TIME_FRAG)) {
grenadeObject.state = 'exploded';
}
return grenadeObject;
}).filter((grenade): grenade is RadarGrenadeObject => grenade !== null);
}
export const extendPlayer = ({ player, steamId, mapName }: { mapName: string, player: Player, steamId: string | null}): RadarPlayerObject | RadarPlayerObject[] | null => {
const weapons = player.weapons ? Object.values(player.weapons) : [];
const weapon = weapons.find(weapon => weapon.state === "active" && weapon.type !== "C4" && weapon.type !== "Knife" && weapon.type !== "Grenade");
const shooting: ShootingState = { ammo: weapon && weapon.ammo_clip || 0, weapon: weapon && weapon.name || '', lastShoot: 0 };
const lastShoot = shootingState[player.steamid] || shooting;
let isShooting = false;
if (shooting.weapon === lastShoot.weapon && shooting.ammo < lastShoot.ammo) {
isShooting = true;
}
shooting.lastShoot = isShooting ? (new Date()).getTime() : lastShoot.lastShoot;
shootingState[player.steamid] = shooting;
const map = maps[mapName];
const playerObject: RadarPlayerObject = {
id: player.steamid,
label: player.observer_slot !== undefined ? player.observer_slot : "",
side: player.team.side,
position: [],
visible: true,
isActive: steamId === player.steamid,
forward: 0,
scale: 1,
steamid: player.steamid,
flashed: player.state.flashed > 35,
shooting: isShooting,
lastShoot: shooting.lastShoot,
isAlive: player.state.health > 0,
hasBomb: !!Object.values(player.weapons).find(weapon => weapon.type === "C4"),
player
}
if ("config" in map) {
const scale = map.config.originHeight === undefined ? 1 : (1 + (player.position[2] - map.config.originHeight) / 1000);
playerObject.scale = scale;
const position = parsePlayerPosition(player, map.config);
playerObject.position = position;
return playerObject;
}
return map.configs.map(config => {
const scale = config.config.originHeight === undefined ? 1 : (1 + (player.position[2] - config.config.originHeight) / 750);
playerObject.scale = scale;
return ({
...playerObject,
position: parsePlayerPosition(player, config.config),
id: `${player.steamid}_${config.id}`,
visible: config.isVisible(player.position[2])
})
});
}
+13 -43
View File
@@ -1,50 +1,20 @@
import React from "react";
import { isDev } from './../../api/api';
import { CSGO } from "csgogsi-socket";
import { CSGO } from "csgogsi";
import LexoRadarContainer from './LexoRadar/LexoRadarContainer';
interface Props { radarSize: number, game: CSGO }
interface State {
showRadar: boolean,
loaded: boolean,
boltobserv:{
css: boolean,
maps: boolean
}
const Radar = ({ radarSize, game }: Props) => {
const { players, player, bomb, grenades, map } = game;
return <LexoRadarContainer
players={players}
player={player}
bomb={bomb}
grenades={grenades}
size={radarSize}
mapName={map.name.substring(map.name.lastIndexOf('/')+1)}
/>
}
export default class Radar extends React.Component<Props, State> {
state = {
showRadar: true,
loaded: !isDev,
boltobserv: {
css: true,
maps: true
}
}
async componentDidMount(){
/*if(isDev){
const response = await fetch('hud.json');
const hud = await response.json();
const boltobserv = {
css: Boolean(hud && hud.boltobserv && hud.boltobserv.css),
maps: Boolean(hud && hud.boltobserv && hud.boltobserv.maps)
}
this.setState({boltobserv, loaded: true});
}*/
}
render() {
const { players, player, bomb, grenades, map } = this.props.game;
return <LexoRadarContainer
players={players}
player={player}
bomb={bomb}
grenades={grenades}
size={this.props.radarSize}
mapName={map.name.substring(map.name.lastIndexOf('/')+1)}
/>
}
}
export default Radar;
+44 -56
View File
@@ -1,70 +1,58 @@
import React from "react";
import { useState } from "react";
import "./radar.scss";
import { Match, Veto } from "../../api/interfaces";
import { Map, CSGO, Team } from 'csgogsi-socket';
import { actions } from './../../App';
import { Match, Veto } from "../../API/types";
import { Map, CSGO, Team } from 'csgogsi';
import Radar from './Radar'
import TeamLogo from "../MatchBar/TeamLogo";
import { useAction } from "../../API/contexts/actions";
interface Props { match: Match | null, map: Map, game: CSGO }
interface State { showRadar: boolean, radarSize: number, showBig: boolean }
export default class RadarMaps extends React.Component<Props, State> {
state = {
showRadar: true,
radarSize: 350,
showBig: false
}
componentDidMount() {
actions.on('radarBigger', () => this.radarChangeSize(20));
actions.on('radarSmaller', () => this.radarChangeSize(-20));
actions.on('toggleRadar', () => { this.setState(state => ({ showRadar: !state.showRadar })) });
const RadarMaps = ({ match, map, game }: Props) => {
const [ radarSize, setRadarSize ] = useState(366);
const [ showBig, setShowBig ] = useState(false);
actions.on("toggleRadarView", () => {
this.setState({showBig:!this.state.showBig});
});
}
radarChangeSize = (delta: number) => {
const newSize = this.state.radarSize + delta;
this.setState({ radarSize: newSize > 0 ? newSize : this.state.radarSize });
}
render() {
const { match } = this.props;
const { radarSize, showBig, showRadar } = this.state;
const size = showBig ? 600 : radarSize;
return (
<div id={`radar_maps_container`} className={`${!showRadar ? 'hide' : ''} ${showBig ? 'preview':''}`}>
<div className="radar-component-container" style={{width: `${size}px`, height: `${size}px`}}><Radar radarSize={size} game={this.props.game} /></div>
{match ? <MapsBar match={this.props.match} map={this.props.map} game={this.props.game} /> : null}
</div>
);
}
useAction('radarBigger', () => {
setRadarSize(p => p+10);
}, []);
useAction('radarSmaller', () => {
setRadarSize(p => p-10);
}, []);
useAction('toggleRadarView', () => {
setShowBig(p => !p);
}, []);
return (
<div id={`radar_maps_container`} className={` ${showBig ? 'preview':''}`}>
{match ? <MapsBar match={match} map={map} game={game} /> : null}
<Radar radarSize={showBig ? 600: radarSize} game={game} />
</div>
);
}
class MapsBar extends React.PureComponent<Props> {
render() {
const { match, map } = this.props;
if (!match || !match.vetos.length) return '';
const picks = match.vetos.filter(veto => veto.type !== "ban" && veto.mapName);
if (picks.length > 3) {
const current = picks.find(veto => map.name.includes(veto.mapName));
if (!current) return null;
return <div id="maps_container">
{<MapEntry veto={current} map={map} team={current.type === "decider" ? null : map.team_ct.id === current.teamId ? map.team_ct : map.team_t} />}
</div>
}
export default RadarMaps;
const MapsBar = ({ match, map }: Props) => {
if (!match || !match.vetos.length) return '';
const picks = match.vetos.filter(veto => veto.type !== "ban" && veto.mapName);
if (picks.length > 3) {
const current = picks.find(veto => map.name.includes(veto.mapName));
if (!current) return null;
return <div id="maps_container">
{match.vetos.filter(veto => veto.type !== "ban").filter(veto => veto.teamId || veto.type === "decider").map(veto => <MapEntry key={veto.mapName} veto={veto} map={this.props.map} team={veto.type === "decider" ? null : map.team_ct.id === veto.teamId ? map.team_ct : map.team_t} />)}
<div className="bestof">Best of {match.matchType.replace("bo", "")}</div>
{<MapEntry veto={current} map={map} team={current.type === "decider" ? null : map.team_ct.id === current.teamId ? map.team_ct : map.team_t} />}
</div>
}
return <div id="maps_container">
<div className="bestof">Best of {match.matchType.replace("bo", "")}</div>
{match.vetos.filter(veto => veto.type !== "ban").filter(veto => veto.teamId || veto.type === "decider").map(veto => <MapEntry key={veto.mapName} veto={veto} map={map} team={veto.type === "decider" ? null : map.team_ct.id === veto.teamId ? map.team_ct : map.team_t} />)}
</div>
}
class MapEntry extends React.PureComponent<{ veto: Veto, map: Map, team: Team | null }> {
render() {
const { veto, map, team } = this.props;
return <div className="veto_entry">
<div className="team_logo">{team ? <TeamLogo team={team} /> : null}</div>
<div className={`map_name ${map.name.includes(veto.mapName) ? 'active' : ''}`}>{veto.mapName}</div>
</div>
}
const MapEntry = ({ veto, map }: { veto: Veto, map: Map, team: Team | null }) => {
return <div className="veto_entry">
<div className={`map_name ${map.name.includes(veto.mapName) ? 'active' : ''}`}>{veto.mapName.replace("de_", "")}</div>
</div>
}
+22 -10
View File
@@ -3,7 +3,6 @@
top: 10px;
left: 10px;
border: none;
background-color: rgba(0,0,0,0.5);
transition: all 1s;
.map-container {
transition: all 1s;
@@ -24,18 +23,24 @@
perspective: 500px;
}
}
.radar-component-container {
width: 350px;
height:350px;
overflow: hidden;
}
#maps_container {
width: 100%;
height: 30px;
display: flex;
flex-direction: row;
justify-content: space-evenly;
background-color: rgba(0,0,0,0.5);
color: white;
background-color: var(--sub-panel-color);
.bestof {
width: 121px;
font-size: 16px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
text-transform: uppercase;
}
}
.veto_entry {
display: flex;
@@ -59,8 +64,15 @@
width: 23px;
}
}
.map_name.active {
text-shadow: 0 0 15px white;
font-weight: 600;
.map_name {
font-size:12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.1em;
opacity: 0.5;
&.active {
opacity: 1;
}
}
}
+42 -40
View File
@@ -1,45 +1,47 @@
import React from 'react';
import React from "react";
class LossBox extends React.PureComponent<{ active: boolean, side: 'CT' | 'T' }>{
render(){
return <div className={`loss-box ${this.props.side} ${this.props.active ? 'active':''}`}></div>
}
}
const LossBox = React.memo(({ active, side }: { active: boolean; side: "CT" | "T" }) => {
return (
<div
className={`loss-box ${side} ${
active ? "active" : ""
}`}
>
</div>
);
});
interface Props {
side: 'left' | 'right',
team: 'CT' | 'T',
loss: number,
equipment: number,
money: number,
show: boolean,
side: "left" | "right";
team: "CT" | "T";
loss: number;
equipment: number;
money: number;
show: boolean;
}
export default class Money extends React.PureComponent<Props> {
render() {
return (
<div className={`moneybox ${this.props.side} ${this.props.team} ${this.props.show ? "show" : "hide"}`}>
<div className="loss_container">
<LossBox side={this.props.team} active={(this.props.loss-1400)/500 >= 4} />
<LossBox side={this.props.team} active={(this.props.loss-1400)/500 >= 3} />
<LossBox side={this.props.team} active={(this.props.loss-1400)/500 >= 2} />
<LossBox side={this.props.team} active={(this.props.loss-1400)/500 >= 1} />
</div>
<div className="money_container">
<div className="title">Loss Bonus</div>
<div className="value">${this.props.loss}</div>
</div>
<div className="money_container">
<div className="title">Team Money</div>
<div className="value">${this.props.money}</div>
</div>
<div className="money_container">
<div className="title">Equipment Value</div>
<div className="value">${this.props.equipment}</div>
</div>
</div>
);
}
}
const Money = ({ side, team, loss, equipment, money, show }: Props) => {
return (
<div className={`moneybox ${side} ${team} ${show ? "show" : "hide"}`}>
<div className="loss_container">
<LossBox side={team} active={(loss - 1400) / 500 >= 4} />
<LossBox side={team} active={(loss - 1400) / 500 >= 3} />
<LossBox side={team} active={(loss - 1400) / 500 >= 2} />
<LossBox side={team} active={(loss - 1400) / 500 >= 1} />
</div>
<div className="money_container">
<div className="title">Loss Bonus</div>
<div className="value">${loss}</div>
</div>
<div className="money_container">
<div className="title">Team Money</div>
<div className="value">${money}</div>
</div>
<div className="money_container">
<div className="title">Equipment Value</div>
<div className="value">${equipment}</div>
</div>
</div>
);
};
export default Money;
+27 -44
View File
@@ -1,49 +1,32 @@
import React from 'react';
import { useState } from 'react';
import './sideboxes.scss'
import {configs, hudIdentity} from './../../App';
import { apiUrl } from '../../api/api';
import { apiUrl } from './../../API';
import { useConfig, useOnConfigChange } from '../../API/contexts/actions';
import { hudIdentity } from '../../API/HUD';
export default class SideBox extends React.Component<{ side: 'left' | 'right', hide: boolean}, { title: string, subtitle: string, image?: string }> {
constructor(props: any) {
super(props);
this.state = {
title:'Title',
subtitle:'Content',
}
}
const Sidebox = ({side, hide} : { side: 'left' | 'right', hide: boolean}) => {
const [ image, setImage ] = useState<string | null>(null);
const data = useConfig('display_settings');
componentDidMount() {
configs.onChange((data:any) => {
if(!data) return;
const display = data.display_settings;
if(!display) return;
if(`${this.props.side}_title` in display){
this.setState({title:display[`${this.props.side}_title`]})
}
if(`${this.props.side}_subtitle` in display){
this.setState({subtitle:display[`${this.props.side}_subtitle`]})
}
if(`${this.props.side}_image` in display){
const imageUrl = `${apiUrl}api/huds/${hudIdentity.name || 'dev'}/display_settings/${this.props.side}_image?isDev=${hudIdentity.isDev}&cache=${(new Date()).getTime()}`;
this.setState({image:imageUrl})
}
});
}
render() {
const { image, title, subtitle} = this.state;
if(!title) return '';
return (
<div className={`sidebox ${this.props.side} ${this.props.hide ? 'hide':''}`}>
<div className="title_container">
<div className="title">{title}</div>
<div className="subtitle">{subtitle}</div>
</div>
<div className="image_container">
{image ? <img src={image} id={`image_left`} alt={'Left'}/>:''}
</div>
useOnConfigChange('display_settings', data => {
if(data && `${side}_image` in data){
const imageUrl = `${apiUrl}api/huds/${hudIdentity.name || 'dev'}/display_settings/${side}_image?isDev=${hudIdentity.isDev}&cache=${(new Date()).getTime()}`;
setImage(imageUrl);
}
}, []);
if(!data || !data[`${side}_title`]) return null;
return (
<div className={`sidebox ${side} ${hide ? 'hide':''}`}>
<div className="title_container">
<div className="title">{data[`${side}_title`]}</div>
<div className="subtitle">{data[`${side}_subtitle`]}</div>
</div>
);
}
<div className="image_container">
{image ? <img src={image} id={`image_left`} alt={'Left'}/>:null}
</div>
</div>
);
}
export default Sidebox;
+58 -42
View File
@@ -1,12 +1,11 @@
import React from "react";
import Weapon from "./../Weapon/Weapon";
import { Player, WeaponRaw, Side } from "csgogsi-socket";
import { Player, Side, WeaponRaw } from "csgogsi";
interface Props {
sides?: 'reversed',
show: boolean;
side: 'CT' | 'T',
players: Player[]
sides?: "reversed";
show: boolean;
side: "CT" | "T";
players: Player[];
}
function utilityState(amount: number) {
@@ -49,17 +48,30 @@ function utilityColor(amount: number) {
function sum(grenades: WeaponRaw[], name: string) {
return (
grenades.filter(grenade => grenade.name === name).reduce((prev, next) => ({ ...next, ammo_reserve: (prev.ammo_reserve || 0) + (next.ammo_reserve || 0) }), { name: "", ammo_reserve: 0 })
grenades.filter((grenade) => grenade.name === name).reduce(
(prev, next) => ({
...next,
ammo_reserve: (prev.ammo_reserve || 0) + (next.ammo_reserve || 0),
}),
{ name: "", ammo_reserve: 0 },
)
.ammo_reserve || 0
);
}
function parseGrenades(players: Player[], side: Side) {
const grenades = players
.filter(player => player.team.side === side)
.map(player => Object.values(player.weapons).filter(weapon => weapon.type === "Grenade"))
.filter((player) => player.team.side === side)
.map((player) =>
Object.values(player.weapons).filter((weapon) =>
weapon.type === "Grenade"
)
)
.flat()
.map(grenade => ({ ...grenade, name: grenade.name.replace("weapon_", "") }));
.map((grenade) => ({
...grenade,
name: grenade.name.replace("weapon_", ""),
}));
return grenades;
}
@@ -69,40 +81,44 @@ export function summarise(players: Player[], side: Side) {
hg: sum(grenades, "hegrenade"),
flashes: sum(grenades, "flashbang"),
smokes: sum(grenades, "smokegrenade"),
inc: sum(grenades, "incgrenade") + sum(grenades, "molotov")
inc: sum(grenades, "incgrenade") + sum(grenades, "molotov"),
};
}
class GrenadeContainer extends React.PureComponent<{ grenade: string; amount: number }> {
render() {
return (
<div className="grenade_container">
<div className="grenade_image">
<Weapon weapon={this.props.grenade} active={false} isGrenade />
</div>
<div className="grenade_amount">x{this.props.amount}</div>
const GrenadeContainer = (
{ grenade, amount }: { grenade: string; amount: number },
) => {
return (
<div className="grenade_container">
<div className="grenade_image">
<Weapon weapon={grenade} active={false} isGrenade />
</div>
);
}
}
<div className="grenade_amount">x{amount}</div>
</div>
);
};
export default class SideBox extends React.Component<Props> {
render() {
const grenades = summarise(this.props.players, this.props.side);
const total = Object.values(grenades).reduce((a, b) => a+b, 0);
return (
<div className={`utilitybox ${this.props.side || ''} ${this.props.show ? "show" : "hide"}`}>
<div className="title_container">
<div className="title">Utility Level -&nbsp;</div>
<div className="subtitle" style={{color: utilityColor(total)}}>{utilityState(total)}</div>
</div>
<div className="grenades_container">
<GrenadeContainer grenade="smokegrenade" amount={grenades.smokes} />
<GrenadeContainer grenade={this.props.side === 'CT' ? 'incgrenade' : 'molotov'} amount={grenades.inc} />
<GrenadeContainer grenade="flashbang" amount={grenades.flashes} />
<GrenadeContainer grenade="hegrenade" amount={grenades.hg} />
</div>
</div>
);
}
}
const SideBox = ({ players, side, show }: Props) => {
const grenades = summarise(players, side);
const total = Object.values(grenades).reduce((a, b) => a + b, 0);
return (
<div className={`utilitybox ${side || ""} ${show ? "show" : "hide"}`}>
<div className="title_container">
<div className="title">Utility Level -&nbsp;</div>
<div className="subtitle" style={{ color: utilityColor(total) }}>
{utilityState(total)}
</div>
</div>
<div className="grenades_container">
<GrenadeContainer grenade="smokegrenade" amount={grenades.smokes} />
<GrenadeContainer
grenade={side === "CT" ? "incgrenade" : "molotov"}
amount={grenades.inc}
/>
<GrenadeContainer grenade="flashbang" amount={grenades.flashes} />
<GrenadeContainer grenade="hegrenade" amount={grenades.hg} />
</div>
</div>
);
};
export default SideBox;
-18
View File
@@ -1,18 +0,0 @@
import React from 'react';
import * as I from '../../api/interfaces';
import "./teamoverview.scss";
interface IProps {
team: I.Team,
show: boolean,
veto: I.Veto | null
}
export default class TeamOverview extends React.Component<IProps> {
render() {
if(!this.props.team) return null;
return (
null
);
}
}
+14 -45
View File
@@ -1,49 +1,18 @@
import React from "react";
import { GSI } from "./../../App";
import BombTimer from "./Countdown";
import { MAX_TIMER, useBombTimer } from "./Countdown";
import { C4 } from "./../../assets/Icons";
export default class Bomb extends React.Component<any, { height: number; show: boolean }> {
constructor(props: any) {
super(props);
this.state = {
height: 0,
show: false
};
}
hide = () => {
this.setState({ show: false, height: 100 });
};
componentDidMount() {
const bomb = new BombTimer(time => {
let height = time > 40 ? 4000 : time * 100;
this.setState({ height: height / 40 });
});
bomb.onReset(this.hide);
GSI.on("data", data => {
if (data.bomb && data.bomb.countdown) {
if (data.bomb.state === "planted") {
this.setState({ show: true });
return bomb.go(data.bomb.countdown);
}
if (data.bomb.state !== "defusing") {
this.hide();
}
} else {
this.hide();
}
});
}
render() {
return (
<div id={`bomb_container`}>
<div className={`bomb_timer ${this.state.show ? "show" : "hide"}`} style={{ height: `${this.state.height}%` }}></div>
<div className={`bomb_icon ${this.state.show ? "show" : "hide"}`}>
<C4 fill="white" />
</div>
const Bomb = () => {
const bombData = useBombTimer();
const show = bombData.state === "planted" || bombData.state === "defusing";
return (
<div id={`bomb_container`}>
<div className={`bomb_timer ${show ? "show" : "hide"}`} style={{ height: `${bombData.bombTime*100/MAX_TIMER.bomb}%` }}></div>
<div className={`bomb_icon ${show ? "show" : "hide"}`}>
<C4 fill="white" />
</div>
);
}
</div>
);
}
export default Bomb;
+77 -40
View File
@@ -1,46 +1,83 @@
export default class Countdown {
last: number;
time: number;
step: (time: number) => void;
on: boolean;
resetFunc?: Function;
import { Bomb, Events, Player } from "csgogsi";
import { useEffect, useRef, useState } from "react";
import { GSI } from "../../API/HUD";
constructor(step: (time: number) => void){
this.last = 0;
this.time = 0;
this.on = false;
this.step = step;
}
onReset(func: Function) {
this.resetFunc = func;
}
stepWrapper = (time: number) =>{
if(this.time < 0) return this.reset();
if(!this.on) return this.reset();
if(!this.last) this.last = time;
if(this.time !== Number((this.time - (time - this.last)/1000))){
this.time = Number((this.time - (time - this.last)/1000));
this.step(this.time);
export const MAX_TIMER = {
planting: 3,
defuse_kit: 5,
defuse_nokit: 10,
bomb: 40
}
const findNewTime = (current: number, newTime: number) => Math.abs(current - newTime) > 2 ? newTime : current;
export const useBombTimer = () => {
const [ player, setPlayerSteamId ] = useState<Player | null>(null);
const [ bombState, setBombState ] = useState<Bomb["state"] | null>(null);
const [ site, setBombSite ] = useState<string | null>(null);
const [ plantTime, setPlantTime ] = useState(0);
const [ bombTime, setBombTime ] = useState(0);
const [ defuseTime, setDefuseTime ] = useState(0);
// Inner loop logic
const previousTimeRef = useRef(0);
const rAFRef = useRef<number>();
useEffect(() => {
const onData: Events["data"] = data => {
const { bomb } = data;
const bombPlayer = bomb?.player || null;
const state = bomb?.state || null;
const site = bomb?.site || null;
const countdown = parseFloat(bomb?.countdown || '0');
setPlayerSteamId(bombPlayer);
setBombState(state);
setBombSite(site);
const plantNewTime = state === "planting" ? countdown : 0;
const defuseNewTime = state === "defusing" ? countdown : 0;
setPlantTime(curr => findNewTime(curr, plantNewTime));
setDefuseTime(curr => findNewTime(curr, defuseNewTime));
setBombTime(p => state === "planted" ? findNewTime(p, countdown) : p);
}
GSI.on("data", onData);
const animationFrame = (time: number) => {
if(previousTimeRef.current){
const deltaTime = time - previousTimeRef.current;
const dTs = deltaTime/1000;
setPlantTime(p => p <= 0 ? 0 : p - dTs);
setDefuseTime(p => p <= 0 ? 0 : p - dTs);
setBombTime(p => p <= 0 ? 0 : p - dTs);
}
previousTimeRef.current = time;
rAFRef.current = requestAnimationFrame(animationFrame);
}
rAFRef.current = requestAnimationFrame(animationFrame);
return () => {
GSI.off("data", onData);
if(rAFRef.current) cancelAnimationFrame(rAFRef.current);
}
this.last =time;
if(this.last) requestAnimationFrame(this.stepWrapper)
}
}, []);
go(duration: string | number){
//console.log("STARTED WITH ", duration);
if(typeof duration === "string") duration = Number(duration);
if(Math.abs(duration - this.time) > 2) this.time = duration;
this.on = true;
if(!this.last ) requestAnimationFrame(this.stepWrapper);
}
reset(){
this.last = 0;
this.time = 0;
this.on = false;
if(this.resetFunc) this.resetFunc();
}
}
return ({
state: bombState,
player,
site,
defuseTime,
bombTime,
plantTime
})
}
+26 -28
View File
@@ -1,41 +1,39 @@
import React from "react";
import { Timer } from "../MatchBar/MatchBar";
import { Player } from "csgogsi";
import * as I from "./../../assets/Icons";
import { MAX_TIMER } from "./Countdown";
interface IProps {
timer: Timer | null;
side: "right" | "left"
}
export default class Bomb extends React.Component<IProps> {
getCaption = (type: "defusing" | "planting", player: Player | null) => {
if(!player) return null;
if(type === "defusing"){
return <>
<I.Defuse height={22} width={22} fill="var(--color-new-ct)" />
<div className={'CT'}>{player.name} is defusing the bomb</div>
</>;
}
const getCaption = (type: "defusing" | "planting", player: Player | null) => {
if(!player) return null;
if(type === "defusing"){
return <>
<I.SmallBomb height={22} fill="var(--color-new-t)"/>
<div className={'T'}>{player.name} is planting the bomb</div>
<I.Defuse height={22} width={22} fill="var(--color-new-ct)" />
<div className={'CT'}>{player.name} is defusing the bomb</div>
</>;
}
render() {
const { side, timer } = this.props;
return (
<div className={`defuse_plant_container ${side} ${timer && timer.active ? 'show' :'hide'}`}>
{
timer ?
<div className={`defuse_plant_caption`}>
{this.getCaption(timer.type, timer.player)}
</div> : null
}
<div className="defuse_plant_bar" style={{ width: `${(timer && timer.width) || 0}%` }}></div>
</div>
);
}
return <>
<I.SmallBomb height={22} fill="var(--color-new-t)"/>
<div className={'T'}>{player.name} is planting the bomb</div>
</>;
}
const Bomb = ({ timer, side }: IProps) =>{
if(!timer) return null;
return (
<div className={`defuse_plant_container ${side} ${timer && timer.active ? 'show' :'hide'}`}>
{
timer ?
<div className={`defuse_plant_caption`}>
{getCaption(timer.type, timer.player)}
</div> : null
}
<div className="defuse_plant_bar" style={{ width: `${(timer.time * 100 / (timer.type === "planting" ? MAX_TIMER.planting : timer.player?.state.defusekit ? MAX_TIMER.defuse_kit : MAX_TIMER.defuse_nokit ))}%` }}></div>
</div>
);
}
export default Bomb;
+65 -70
View File
@@ -1,5 +1,5 @@
import React from 'react';
import * as I from './../../api/interfaces';
import * as I from './../../API/types';
import { apiUrl } from '../../API';
interface MatchData {
left: { name: string; score: string | number; logo: string };
@@ -11,83 +11,79 @@ interface Props {
teams: I.Team[]
}
export default class Ladder extends React.Component<Props> {
joinParents = (matchup: I.TournamentMatchup, matchups: I.TournamentMatchup[]) => {
const { tournament } = this.props;
if (!tournament || !matchup) return matchup;
const joinParents = (matchup: I.TournamentMatchup, matchups: I.TournamentMatchup[]) => {
if (!matchup) return matchup;
if (matchup.parents.length) return matchup;
if (matchup.parents.length) return matchup;
const parents = matchups.filter(m => m.winner_to === matchup._id || m.loser_to === matchup._id);
if (!parents.length) return matchup;
matchup.parents.push(...parents.map(parent => this.joinParents(parent, matchups)));
const parents = matchups.filter(m => m.winner_to === matchup._id || m.loser_to === matchup._id);
if (!parents.length) return matchup;
matchup.parents.push(...parents.map(parent => joinParents(parent, matchups)));
return matchup;
return matchup;
};
const copyMatchups = (currentMatchups: I.TournamentMatchup[]): I.DepthTournamentMatchup[] => {
const matchups = JSON.parse(JSON.stringify(currentMatchups)) as I.DepthTournamentMatchup[];
return matchups;
};
const setDepth = (matchups: I.DepthTournamentMatchup[], matchup: I.DepthTournamentMatchup, depth: number, force = false) => {
const getParents = (matchup: I.DepthTournamentMatchup) => {
return matchups.filter(parent => parent.loser_to === matchup._id || parent.winner_to === matchup._id);
};
copyMatchups = (): I.DepthTournamentMatchup[] => {
if (!this.props.tournament) return [];
const matchups = JSON.parse(JSON.stringify(this.props.tournament.matchups)) as I.DepthTournamentMatchup[];
return matchups;
if (!matchup.depth || force) {
matchup.depth = depth;
getParents(matchup).forEach(matchup => setDepth(matchups, matchup, depth + 1));
}
if (matchup.depth <= depth - 1) {
setDepth(matchups, matchup, depth - 1, true);
}
return matchup;
};
const getMatch = ({ matchup, matches, teams: allTeams}: { matches: I.Match[], teams: I.Team[], matchup: I.TournamentMatchup}) => {
const matchData: MatchData = {
left: { name: 'TBD', score: '-', logo: '' },
right: { name: 'TBD', score: '-', logo: '' }
};
const match = matches.find(match => match.id === matchup.matchId);
if (!match) return matchData;
const teams = [
allTeams.find(team => team._id === match.left.id),
allTeams.find(team => team._id === match.right.id)
];
if (teams[0]) {
matchData.left.name = teams[0].name;
matchData.left.score = match.left.wins;
matchData.left.logo = teams[0].logo;
}
if (teams[1]) {
matchData.right.name = teams[1].name;
matchData.right.score = match.right.wins;
matchData.right.logo = teams[1].logo;
}
return matchData;
};
setDepth = (matchups: I.DepthTournamentMatchup[], matchup: I.DepthTournamentMatchup, depth: number, force = false) => {
const getParents = (matchup: I.DepthTournamentMatchup) => {
return matchups.filter(parent => parent.loser_to === matchup._id || parent.winner_to === matchup._id);
};
if (!matchup.depth || force) {
matchup.depth = depth;
getParents(matchup).forEach(matchup => this.setDepth(matchups, matchup, depth + 1));
}
if (matchup.depth <= depth - 1) {
this.setDepth(matchups, matchup, depth - 1, true);
}
return matchup;
};
getMatch = (matchup: I.TournamentMatchup) => {
const { matches } = this.props;
const matchData: MatchData = {
left: { name: 'TBD', score: '-', logo: '' },
right: { name: 'TBD', score: '-', logo: '' }
};
const match = matches.find(match => match.id === matchup.matchId);
if (!match) return matchData;
const teams = [
this.props.teams.find(team => team._id === match.left.id),
this.props.teams.find(team => team._id === match.right.id)
];
if (teams[0]) {
matchData.left.name = teams[0].name;
matchData.left.score = match.left.wins;
matchData.left.logo = teams[0].logo;
}
if (teams[1]) {
matchData.right.name = teams[1].name;
matchData.right.score = match.right.wins;
matchData.right.logo = teams[1].logo;
}
return matchData;
};
renderBracket = (
const Ladder = ({ tournament, matches, teams }: Props) => {
const renderBracket = (
matchup: I.DepthTournamentMatchup | null | undefined,
depth: number,
fromChildId: string | undefined,
childVisibleParents: number,
isLast = false
) => {
const { tournament, matches } = this.props;
if (!matchup || !tournament) return null;
const match = this.getMatch(matchup);
const match = getMatch({ teams: teams, matches: matches, matchup});
if (fromChildId === matchup.loser_to) return null;
const parentsToRender = matchup.parents.filter(matchupParent => matchupParent.loser_to !== matchup._id);
if (matchup.depth > depth) {
return (
<div className="empty-bracket">
{this.renderBracket(matchup, depth + 1, fromChildId, parentsToRender.length)}
{renderBracket(matchup, depth + 1, fromChildId, parentsToRender.length)}
<div className="connector"></div>
</div>
);
@@ -97,8 +93,8 @@ export default class Ladder extends React.Component<Props> {
return (
<div className={`bracket depth-${depth}`}>
<div className="parent-brackets">
{this.renderBracket(matchup.parents[0], depth + 1, matchup._id, parentsToRender.length)}
{this.renderBracket(matchup.parents[1], depth + 1, matchup._id, parentsToRender.length)}
{renderBracket(matchup.parents[0], depth + 1, matchup._id, parentsToRender.length)}
{renderBracket(matchup.parents[1], depth + 1, matchup._id, parentsToRender.length)}
</div>
<div className="bracket-details">
<div
@@ -110,14 +106,14 @@ export default class Ladder extends React.Component<Props> {
<div className={`match-details ${isCurrent ? 'current':''}`}>
<div className="team-data">
<div className="team-logo">
{match.left.logo ? <img src={match.left.logo} alt="Logo" /> : null}
{match.left.logo ? <img src={`${apiUrl}api/teams/logo/direct/${match.left.logo}`} alt="Logo" /> : null}
</div>
<div className="team-name">{match.left.name}</div>
<div className="team-score">{match.left.score}</div>
</div>
<div className="team-data">
<div className="team-logo">
{match.right.logo ? <img src={match.right.logo} alt="Logo" /> : null}
{match.right.logo ? <img src={`${apiUrl}api/teams/logo/direct/${match.right.logo}`} alt="Logo" /> : null}
</div>
<div className="team-name">{match.right.name}</div>
<div className="team-score">{match.right.score}</div>
@@ -132,14 +128,13 @@ export default class Ladder extends React.Component<Props> {
);
};
render() {
const { tournament } = this.props;
if (!tournament) return null;
const matchups = this.copyMatchups();
const matchups = copyMatchups(tournament.playoffs.matchups);
const gf = matchups.find(matchup => matchup.winner_to === null);
if (!gf) return null;
const joinedParents = this.joinParents(gf, matchups);
const matchupWithDepth = this.setDepth(matchups, joinedParents as I.DepthTournamentMatchup, 0);
return this.renderBracket(matchupWithDepth, 0, undefined, 2, true);
}
const joinedParents = joinParents(gf, matchups);
const matchupWithDepth = setDepth(matchups, joinedParents as I.DepthTournamentMatchup, 0);
return renderBracket(matchupWithDepth, 0, undefined, 2, true);
}
export default Ladder;
+43 -54
View File
@@ -1,62 +1,51 @@
import React from 'react';
import './tournament.scss';
import { actions } from '../../App';
import * as I from './../../api/interfaces';
import api from '../../api/api';
import * as I from './../../API/types';
import api from './../../API';
import Ladder from './Ladder';
interface State {
tournament: I.Tournament | null,
teams: I.Team[],
matches: I.Match[],
show: boolean,
}
export default class Tournament extends React.Component<{}, State> {
constructor(props: {}) {
super(props);
this.state = {
tournament: null,
matches: [],
teams: [],
show: false
}
}
async componentDidMount() {
const { tournament } = await api.tournaments.get();
if(tournament){
actions.on("showTournament", async (show: string) => {
if(show !== "show"){
return this.setState({show: false});
}
this.setState({tournament}, () => {
this.setState({show:true})
import { useAction } from '../../API/contexts/actions';
import { useEffect, useState } from 'react';
const Tournament = () => {
const [ show, setShow ] = useState(false);
const [ teams, setTeams ] = useState<I.Team[]>([]);
const [ matches, setMatches ] = useState<I.Match[]>([]);
const [ tournament, setTournament ] = useState<I.Tournament | null>(null);
useAction("showTournament", (data) => {
setShow(data === "show");
});
useEffect(() => {
api.tournaments.get().then(({ tournament }) => {
if(tournament){
setTournament(tournament);
Promise.allSettled([api.match.get(), api.teams.get()]).then(([matches, teams]) =>{
setTeams(teams.status === "fulfilled" ? teams.value : []);
setMatches(matches.status === "fulfilled" ? matches.value : []);
});
});
Promise.all([api.match.get(), api.teams.get()]).then(([matches, teams]) =>{
this.setState({matches, teams});
});
}
}
render() {
const { tournament, matches, teams, show } = this.state;
if(!tournament) return null;
return (
<div className={`ladder-container ${show ? 'show':''}`}>
<div className="tournament-data">
{ tournament.logo ? <img src={`data:image/jpeg;base64,${tournament.logo}`} alt={tournament.name} /> : null }
<div className="tournament-name">
{tournament.name}
</div>
}
})
}, []);
if(!tournament) return null;
return (
<div className={`ladder-container ${show ? 'show':''}`}>
<div className="tournament-data">
{ tournament.logo ? <img src={`data:image/jpeg;base64,${tournament.logo}`} alt={tournament.name} /> : null }
<div className="tournament-name">
{tournament.name}
</div>
<Ladder
tournament={tournament}
matches={matches}
teams={teams}
/>
</div>
);
}
<Ladder
tournament={tournament}
matches={matches}
teams={teams}
/>
</div>
);
}
export default React.memo(Tournament);
+20 -37
View File
@@ -1,43 +1,26 @@
import React from 'react';
import './trivia.scss';
import { useAction, useConfig } from '../../API/contexts/actions';
import React, { useState } from 'react';
import {configs, actions} from './../../App';
const Trivia = () => {
const [ show, setShow ] = useState(false);
const data = useConfig('trivia');
export default class Trivia extends React.Component<any, { title: string, content: string, show: boolean }> {
constructor(props: any) {
super(props);
this.state = {
title:'Title',
content:'Content',
show: false
}
}
useAction('triviaState', (state) => {
setShow(state === "show");
});
componentDidMount() {
configs.onChange((data:any) => {
if(!data) return;
const trivia = data.trivia;
if(!trivia) return;
if(trivia.title && trivia.content){
this.setState({title:trivia.title, content:trivia.content})
}
});
actions.on("triviaState", (state: any) => {
this.setState({show: state === "show"})
});
actions.on("toggleTrivia", () => {
this.setState({show: !this.state.show})
});
}
render() {
return (
<div className={`trivia_container ${this.state.show ? 'show': 'hide'}`}>
<div className="title">{this.state.title}</div>
<div className="content">{this.state.content}</div>
</div>
);
}
useAction('toggleCams', () => {
setShow(p => !p);
});
return (
<div className={`trivia_container ${show ? 'show': 'hide'}`}>
<div className="title">{data?.title}</div>
<div className="content">{data?.content}</div>
</div>
);
}
export default React.memo(Trivia);
+22 -16
View File
@@ -1,19 +1,25 @@
import React from 'react';
import * as Weapons from './../../assets/Weapons';
import React from "react";
import * as Weapons from "./../../assets/Weapons";
interface IProps extends React.SVGProps<SVGSVGElement> {
weapon: string,
active: boolean,
isGrenade?: boolean
weapon: string;
active: boolean;
isGrenade?: boolean;
}
export default class WeaponImage extends React.Component<IProps> {
render() {
const { weapon, active, isGrenade, ...rest } = this.props;
const Weapon = (Weapons as any)[weapon];
const { className, ...svgProps } = rest;
if(!Weapon) return null;
return (
<Weapon fill="white" className={`${active ? 'active':''} weapon ${isGrenade ? 'grenade' : ''} ${className || ''}`} {...svgProps} />
);
}
}
const WeaponImage = ({ weapon, active, isGrenade, ...rest }: IProps) => {
const weaponId = weapon.replace("weapon_", "");
const Weapon = (Weapons as any)[weaponId];
const { className, ...svgProps } = rest;
if (!Weapon) return null;
return (
<Weapon
fill="white"
className={`${active ? "active" : ""} weapon ${
isGrenade ? "grenade" : ""
} ${className || ""}`}
{...svgProps}
/>
);
};
export default React.memo(WeaponImage);