Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // declare const Math: any;
- class Power {
- private from: number;
- private to: number;
- private distance: number;
- constructor(from: number, to: number) {
- this.from = from;
- this.to = to;
- this.distance = this.to - this.from + 1;
- }
- // https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript
- public random(): number {
- return this.from + Math.floor(Math.random() * this.distance);
- }
- }
- class Result {
- public readonly red: number;
- public readonly blue: number;
- public readonly tie: number;
- public readonly total: number;
- constructor(red: number, blue: number, tie: number, total: number) {
- this.red = red;
- this.blue = blue;
- this.tie = tie;
- this.total = total;
- }
- }
- class Player {
- private life: number;
- private readonly power: Power;
- constructor(life: number, power: Power) {
- this.life = life;
- this.power = power;
- }
- public nextPower(): number {
- return this.power.random();
- }
- public changeLife(diff: number) {
- this.life += diff;
- }
- public alive() {
- return this.life > 0;
- }
- }
- class PlayerBuilder {
- private life: number;
- private readonly power: Power;
- constructor(life: number, from: number, to: number) {
- this.life = life;
- this.power = new Power(from, to);
- }
- public build(): Player {
- return new Player(this.life, this.power);
- }
- }
- function kick(a: Player, b: Player) {
- a.changeLife(-b.nextPower());
- }
- function test(count: number, redPlayerBuilder: PlayerBuilder, bluePlayerBuilder: PlayerBuilder): Result {
- const winCountMap = {
- "red": 0,
- "blue": 0,
- };
- let tieCount = 0;
- for (let i = 0; i < count; i++) {
- const redPlayer = redPlayerBuilder.build();
- const bluePlayer = bluePlayerBuilder.build();
- while (redPlayer.alive() && bluePlayer.alive()) {
- kick(redPlayer, bluePlayer);
- kick(bluePlayer, redPlayer);
- }
- const red = redPlayer.alive();
- const blue = bluePlayer.alive();
- if (red) {
- winCountMap["red"] += 1;
- } else if (blue) {
- winCountMap["blue"] += 1;
- } else {
- tieCount += 1;
- }
- }
- return new Result(
- winCountMap["red"],
- winCountMap["blue"],
- tieCount,
- count
- );
- }
- (function () {
- const tries = [
- 1,
- 2,
- 4,
- 8,
- 16,
- 32,
- 64,
- 100,
- 1000,
- 10000,
- 100000,
- ];
- const redPlayerBuilder = new PlayerBuilder(100, 10, 15);
- const bluePlayerBuilder = new PlayerBuilder(90, 8, 20);
- for (let i = 0; i < tries.length; i++) {
- const count = tries[i];
- const result = test(
- count,
- redPlayerBuilder,
- bluePlayerBuilder,
- );
- console.log(`Count: ${count}, red: ${result.red}, blue: ${result.blue}, tie: ${result.tie}, red: ${result.red * 100 / count} %`);
- }
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement