Skip to content
This repository has been archived by the owner on Jan 12, 2023. It is now read-only.

Commit

Permalink
style: warnings fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
Sciator committed Dec 16, 2020
1 parent 4c229ea commit 6b393de
Show file tree
Hide file tree
Showing 10 changed files with 67 additions and 66 deletions.
2 changes: 1 addition & 1 deletion ui/src/core/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const throwReturn = <T>(message: string): T => {
export const shuffle = <T>(arr: T[]) => {
const swap = (i: number, j: number) => {
[arr[i], arr[j]] = [arr[j], arr[i]];
}
};

for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
Expand Down
34 changes: 17 additions & 17 deletions ui/src/logic/game/game.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Engine, World, Bodies, Vector, Composite, Body, Events } from "matter-js";
import { Engine, World, Bodies, Vector, Body, Events } from "matter-js";
import { throwReturn } from "../../core/common";
import { GameAI } from "../gameAi/GameAi";
import { createSensorExecutor, SensorExecutor } from "./sensors";
Expand Down Expand Up @@ -41,15 +41,15 @@ export type GameInput = {


export enum EGameStateObjectType {
player, bullet, wall
player, bullet, wall,
}

export type GameStateObject = {
/** engine body */
body: Body,
type: EGameStateObjectType,
health: number,
}
};

export type GameStatePlayer = GameStateObject & {
type: EGameStateObjectType.player,
Expand Down Expand Up @@ -176,11 +176,11 @@ export class Game {
let vec = Vector.rotate(Vector.create(1, 0), body.angle);
vec = Vector.mult(vec, 5);
Body.setVelocity(body, vec);
player.health -= .0005
player.health -= .0005;
}
if (x.rotate !== 0) {
Body.setAngularVelocity(body, x.rotate * .3);
player.health -= Math.abs(x.rotate) * .005
player.health -= Math.abs(x.rotate) * .005;
}
if (x.use) {
this.use(player);
Expand Down Expand Up @@ -211,14 +211,14 @@ export class Game {
} else if (alivePlayers.length === 0) {
this.gameState.winner = -2;
}
};
}

private processBullets() {
const { gameState: { bullets } } = this;
// todo: based on current step delta
bullets.forEach(x => { x.health -= .01 });
bullets.forEach(x => { x.health -= .01; });

bullets.map(x => {
bullets.forEach(x => {
const { body, health } = x;
const { speed, velocity } = body;

Expand All @@ -233,12 +233,14 @@ export class Game {
const bulletSize = 5;
const itemCooldown = 2000;

// todo: check ammo
// todo: check ammo
const { body: { position, angle }, item } = player;
const { gameState: { bullets }, settings: { game: { playerSize } } } = this;

if (item.cooldown !== 0)
if (item.cooldown !== 0){
player.health -= .2;
return;
}
item.cooldown = itemCooldown;

const distance = playerSize + bulletSize + 1;
Expand All @@ -257,9 +259,7 @@ export class Game {
type: EGameStateObjectType.bullet,
health: 1,
body,
})

player.health -= .1;
});
}

// todo: move all sensor related things into GameAI folder
Expand Down Expand Up @@ -294,17 +294,17 @@ export class Game {
player.health -= damage;
bullet.health -= damage;
} else if (objects[1].type === EGameStateObjectType.bullet) {
objects.forEach(x => x.health /= 2)
objects.forEach(x => x.health /= 2);
}
}
}
};

pairs.forEach(processColisionPair);
}

constructor(userSettings: Partial<GameSettings> = {}) {
const settings = this.settings = mergeSettings(Game.SETTINGS_DEFAULT, userSettings);
// create engine (as any for ignoring deprecated warning
// create engine (as any for ignoring deprecated warning
// - no other function to create engine known)
this.engine = (Engine as any).create();
const world = this.world;
Expand Down Expand Up @@ -345,7 +345,7 @@ export class Game {
timeRemaining: settings.game.maxGameLength,
};

Events.on(this.engine, "collisionStart", this.onCollision.bind(this))
Events.on(this.engine, "collisionStart", this.onCollision.bind(this));

this.sensorExecutor = createSensorExecutor(this);
}
Expand Down
2 changes: 1 addition & 1 deletion ui/src/logic/game/sensors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Engine, Vector, Composite, Bodies, Body } from "matter-js";
import { Vector, Body } from "matter-js";
import { raycast } from "../../utils/raycast";
import { Game } from "./game";

Expand Down
16 changes: 8 additions & 8 deletions ui/src/logic/gameAi/GameAi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { IAProcessGenerationFunction, IASelectionFunctionType } from "../ai/ga/g
import { GeneticAlgorithmNeuralNet } from "../ai/gann/gann";
import { NeuralNet } from "../ai/nn/nn";
import { IANNActivationFunction } from "../ai/nn/nnActivationFunctions";
import { Game, GameSettings } from "../game/game";
import { GameSettings } from "../game/game";
import { GameAiEval } from "./GameAiEval";


Expand All @@ -27,7 +27,7 @@ export type GameAIInitParams = {
/** sensor angles from center to both side (in radians) */
sensors: number[]
}
}
};

/**
* class for training game bots
Expand All @@ -47,8 +47,8 @@ export class GameAI {
selection: {
type: IASelectionFunctionType.percent,
value: 10,
}
}
},
},
},
nnInit: {
hiddenLayers: [8, 8, 8],
Expand All @@ -57,7 +57,7 @@ export class GameAI {
aiParams: {
sensors: [Math.PI * 1 / 4, Math.PI * 1 / 8, Math.PI * 1 / 32],
},
}
};

private onGameEnd: (() => void) | undefined = undefined;

Expand All @@ -80,15 +80,15 @@ export class GameAI {
queue.pop()!,
queue.pop()
// create fake player if second not present so it's dna score will not be affected
?? { dna: dnas[randInt(dnas.length)], games: 0, wins: 0 }
?? { dna: dnas[randInt(dnas.length)], games: 0, wins: 0 },
];
players.forEach(p => { p.games++; });

const evaler = new GameAiEval(players.map(x => x.dna), this.gameSettings);
evaler.run();
const winner = evaler.game.gameState.winner;
if (winner >= 0) {
players.forEach(x => x.wins--)
players.forEach(x => x.wins--);
players[winner].wins += 20;
} else {
players.forEach(x => x.wins -= 0.5);
Expand Down Expand Up @@ -125,7 +125,7 @@ export class GameAI {
inputs,
hiddens: ai.nnInit.hiddenLayers,
outputs,
}
},
},
_environment: { _environmentBatch },
});
Expand Down
10 changes: 5 additions & 5 deletions ui/src/logic/gameAi/GameAiEval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ const numFromType = (type: EGameStateObjectType | "none" | "unknown") => {
console.warn("unknown type of sensor");
return -1;
}
}
};

/** distance of two vecotrs */
const dist = (vec1: Vector, vec2: Vector) => Vector.magnitude(Vector.add(vec1, Vector.neg(vec2)))
const dist = (vec1: Vector, vec2: Vector) => Vector.magnitude(Vector.add(vec1, Vector.neg(vec2)));

/**
* class for evaling game with bots
Expand All @@ -61,7 +61,7 @@ export class GameAiEval {
const outputs = GameAiEval.NN_OUTPUTS;
const inputs = GameAiEval.NN_INPUTS_GET({ sensors });
return NeuralNet.create({
layerScheme: { hiddens, inputs, outputs }, afunction
layerScheme: { hiddens, inputs, outputs }, afunction,
});
}

Expand All @@ -86,13 +86,13 @@ export class GameAiEval {
use: numbers[1] >= .5,
walk: numbers[2] >= .5,
switch: numbers[3],
}
};
}

/** Calculates all turns until all done */
public run() {
while (!this.done) {
this.next()
this.next();
}
}

Expand Down
16 changes: 8 additions & 8 deletions ui/src/logic/gameAi/GameAiLiveTrain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { GameAiEval } from "./GameAiEval";

export type GameAiLiveTrainConst = {
hiddens: number[],
}
};

export type Bot = {
health: number,
Expand All @@ -28,7 +28,7 @@ export class GameAiLiveTrain {
/** how many hp will player get after game when survives */
healthGrowAfterGame: .2,
sensors: [Math.PI * 1 / 4, Math.PI * 1 / 8, Math.PI * 1 / 32],
}
};

public bots: Bot[];

Expand All @@ -45,7 +45,7 @@ export class GameAiLiveTrain {

/** calculate next ai steps. increment last of all bots -> select two bots and play with them -> create new bots from maxed up bots */
public next() {
const { healthGrowAfterGame, healthMultiplier, maxPop, sensors } = this.params;
const { healthGrowAfterGame, healthMultiplier, maxPop } = this.params;
const { bots } = this;
bots.sort((a, b) => - a.games + b.games + (- a.wins + b.wins) * 1_000);

Expand Down Expand Up @@ -94,10 +94,10 @@ export class GameAiLiveTrain {

bot.bonus += exceedingHealth * bonusMultiplier;
}
})
});

if (resHealth.some(x => x <= 0))
resHealth.forEach((x, i) => { if (x > 0) selected[i].wins++; })
resHealth.forEach((x, i) => { if (x > 0) selected[i].wins++; });

selected.forEach(x => { x.lastGame = 0; x.games++; });

Expand Down Expand Up @@ -126,17 +126,17 @@ export class GameAiLiveTrain {

console.log("new bot created");
bot.bonus--;
bots.push({ bonus: 0, games: 0, wins: 0, health: this.params.healthMultiplier, lastGame: 0, nn: bot.nn.mutate(.01) })
bots.push({ bonus: 0, games: 0, wins: 0, health: this.params.healthMultiplier, lastGame: 0, nn: bot.nn.mutate(.01) });
}
}


constructor(constructorParams: GameAiLiveTrainConst, paramsOveride: Partial<GameAiLiveTrain["params"]>) {
const params = this.params = { ...this.params, ...paramsOveride };
const { hiddens } = constructorParams;
const { healthGrowAfterGame, healthMultiplier, maxPop, sensors } = params;
const { sensors } = params;

this.bots = range(params.maxPop).map(x => ({
this.bots = range(params.maxPop).map(() => ({
bonus: 0,
health: params.healthMultiplier,
games: 0,
Expand Down
14 changes: 7 additions & 7 deletions ui/src/views/MainPage.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { Card, Row, Col } from "antd";
import React, { useState } from "react";
import { Analyze } from "./Analyze";
import { PlayPage } from "./Play";
import { Settings, TSettingState } from "./Settings";
import { History } from "./History";
import { RunAI } from "./RunAI";
import { GameAI } from "../logic/gameAi/GameAi";
import { GameAiEval } from "../logic/gameAi/GameAiEval";
import { NeuralNet } from "../logic/ai/nn/nn";
// import { GameAI } from "../logic/gameAi/GameAi";
// import { Analyze } from "./Analyze";
// import { Settings, TSettingState } from "./Settings";
// import { History } from "./History";
// import { GameAiEval } from "../logic/gameAi/GameAiEval";

const { defaultInitParams } = GameAI;
// const { defaultInitParams } = GameAI;

type TMainPageProps = {

};

export const MainPage: React.FC<TMainPageProps> = () => {
const [aiSettings, setAiSettings] = useState<TSettingState>(defaultInitParams as any);
// const [aiSettings, setAiSettings] = useState<TSettingState>(defaultInitParams as any);
const [snapshot, setSnapshot] = useState<NeuralNet[] | undefined>(undefined);

return <>
Expand Down
19 changes: 11 additions & 8 deletions ui/src/views/Play.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,32 @@ export const PlayPage: React.FC<TRunnerProps> = ({ capture, snapshot }) => {
const ref = useRef<HTMLDivElement>(undefined as any);
const [renderer, setRenderer] = useState<Render | undefined>(undefined);
const setRunning = runningState[1];
const running = runningState[0];

const canStart = !(runningState[0] || !snapshot);

const start = () => {
if (!canStart) return;
setRunning(true);
setEvaler(new GameAiEval(snapshot!, Game.SETTINGS_DEFAULT));
}
};

const stop = () => {
setRunning(false);
}
};



useEffect(() => {
if (runningState[0]) return;
if (running) return;
if (renderer)
Render.stop(renderer)
Render.stop(renderer);
setRenderer(undefined);
if (ref.current) ref.current.innerHTML = "";
}, [renderer, runningState[0]])
}, [renderer, running]);

useEffect(() => {
if (!ref.current || !evaler || !runningState[0]) return;
if (!ref.current || !evaler || !running) return;
// if (!ref.current) return;
const element = ref.current;

Expand Down Expand Up @@ -115,7 +118,7 @@ export const PlayPage: React.FC<TRunnerProps> = ({ capture, snapshot }) => {
const rafLoop = () => {
step();
if (!game.isGameOver) {
// if ([runningState[0]])
if (running)
requestAnimationFrame(rafLoop);
} else {

Expand All @@ -126,7 +129,7 @@ export const PlayPage: React.FC<TRunnerProps> = ({ capture, snapshot }) => {
requestAnimationFrame(rafLoop);

Render.run(render);
}, [evaler])
}, [evaler, running]);

const button = runningState[0]
? <Button onClick={stop}>Stop</Button>
Expand Down
Loading

0 comments on commit 6b393de

Please sign in to comment.