new game logic

This commit is contained in:
Kirill Ivlev 2024-10-30 23:26:06 +04:00
parent ed28fe6090
commit 34eea8ac2e
6 changed files with 57 additions and 12 deletions

View file

@ -1,15 +1,19 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { CreateNewQueueItemCommand } from '../commands/create-new-queue-item.command';
import { GameService } from '../game.service';
import {Logger} from "@nestjs/common";
@CommandHandler(CreateNewQueueItemCommand)
export class CreateNewQueueItemCommandHandler implements ICommandHandler<CreateNewQueueItemCommand> {
private logger = new Logger(CreateNewQueueItemCommandHandler.name);
constructor(
private gameService: GameService,
) {
}
async execute(command: CreateNewQueueItemCommand): Promise<any> {
this.logger.verbose(`Adding new queue item ${command.type} for ${command.target}`);
await this.gameService.addTaskToGameQueue(command.target, command.type, command.text);
return Promise.resolve(undefined);
}

View file

@ -326,7 +326,7 @@ export class GuestsService {
AccusativeCase: guest.get(StringHelper.getPropertyName(GuestPropertiesConsts.NameAccusativeCase)),
GenitiveCase: guest.get(StringHelper.getPropertyName(GuestPropertiesConsts.NameGenitiveCase))
}, [...screpaDictManyInvalidAnswersDict])
await this.commandBus.execute(new CreateNewQueueItemCommand(guest.telegramId, GameQueueTypes.screpaAnounce, text));
//await this.commandBus.execute(new CreateNewQueueItemCommand(guest.telegramId, GameQueueTypes.screpaAnounce, text));
// await this.commandBus.execute(new CreateNewQueueItemCommand(guest.telegramId, GameQueueTypes.penalty));
this.logger.verbose(`Reset invalidAnswerInRow, since user received penalty`);
guest.invalidAnswersInRow = 0;

View file

@ -18,6 +18,7 @@ export class QuizController {
@Post('proceed')
async Get() {
console.log('proceed with game')
return this.quizService.proceedWithGame();
}

View file

@ -14,8 +14,8 @@ import {getRandomInt} from 'src/helpers/rand-number';
import {Messages} from "../messaging/tg.text";
import {CreateNewQueueItemCommand} from "../game/commands/create-new-queue-item.command";
import {GameQueueTypes} from "../schemas/game-queue.schema";
import {ConfigService} from "@nestjs/config";
import {Config, ConfigDocument, ConfigSchema} from "../schemas/config.schema";
import {IncreasePlayerWinningRateCommand} from "../game/commands/increase-player-winning-rate.command";
import {SocketEvents} from "../shared/events.consts";
@Injectable({ scope: Scope.TRANSIENT })
export class QuizService {
@ -54,8 +54,7 @@ export class QuizService {
async validateAnswer(answer: string, id: number) {
this.logger.verbose(`enter validate answer ${answer} ${id}`);
const question = await this.get();
question.answered = true;
//question.answered = true;
await question.save();
const regexp = new RegExp(
Object.keys(this.answerNumbers)
@ -72,7 +71,7 @@ export class QuizService {
const filtered = answer.replace(regexp, '').trim();
const isAnswerValid = question.valid === filtered;
if(question.userAnswers.find(answer => answer.user === id)) {
this.logger.verbose("question->useranswer is already containing record");
this.logger.verbose("question->user answer is already containing record");
return;
}
question.userAnswers.push({
@ -85,12 +84,12 @@ export class QuizService {
console.log(question);
this.logger.verbose("question saved with user details")
if (question.valid === filtered) {
question.answered = true;
//question.answered = true;
question.answeredBy = id;
this.logger.verbose(`extra ${question.note}`);
this.eventBus.publish(
new ValidAnswerReceivedEvent(id, filtered, question.note),
);
// this.eventBus.publish(
// new ValidAnswerReceivedEvent(id, filtered, question.note),
// );
await question.save();
await this.markQuestionStorageAsAnsweredCorrectly(question.text);
return true;
@ -122,10 +121,50 @@ export class QuizService {
async proceedWithGame() {
this.logger.verbose(`[proceedWithGame] Executing proceed with game`);
await this.calculateScore();
//this.sharedService.sendSocketNotificationToAllClients(SocketEvents.GameQueueItem, {});
await this.commandBus.execute(new ProceedGameQueueCommand());
return Promise.resolve(true);
}
private async calculateScore() {
const question = await this.get();
this.logger.verbose(`[calculateScore] enter `);
const playerAnswers = question.userAnswers.map((answer) => {
return {
user: answer.user,
valid: answer.valid,
time: answer.time.getTime()
}
});
console.log(playerAnswers);
const sortedAnswers = playerAnswers.sort((a, b) => a.time - b.time);
const winner = sortedAnswers.find((answer) => answer.valid);
if(winner) {
const totalWinningScore = 100;
sortedAnswers.forEach((answer) => {
this.commandBus.execute(new IncreasePlayerWinningRateCommand(answer.user,
totalWinningScore / sortedAnswers.filter((answer) => answer.valid).length))
});
await this.commandBus.execute(new IncreasePlayerWinningRateCommand(sortedAnswers[0].user, 20));
await this.commandBus.execute(new CreateNewQueueItemCommand(winner.user, GameQueueTypes.showresults));
}
const invalidAnswers = sortedAnswers.filter((answer) => !answer.valid)
if(invalidAnswers.length > 0) {
const lastInvalidAnswer = invalidAnswers[invalidAnswers.length - 1];
if(!lastInvalidAnswer) {
return;
}
await this.commandBus.execute(new CreateNewQueueItemCommand(lastInvalidAnswer.user, GameQueueTypes.showresults));
await this.commandBus.execute(new CreateNewQueueItemCommand(lastInvalidAnswer.user, GameQueueTypes.penalty, "лох"));
}
}
private async getNextQuestion() {
let question = await this.questionStorageModel
.findOne({ isAnswered: false })

View file

@ -7,6 +7,7 @@ export enum GameQueueTypes {
penalty = 'penalty',
playExtraCard = 'play_extra_card',
screpaAnounce = 'screpa',
showresults = 'show_results',
}
export type GameQueueDocument = GameQueue & Document;

View file

@ -15,7 +15,7 @@ export class VoiceController {
@Header('content-disposition', 'inline')
async textToSpeechSSML(@Query() dto: TtsRequestDto) {
if (Boolean(this.configService.get<boolean>('ENABLE_VOICE')) === true) {
return new StreamableFile(await this.voiceService.textToFile(dto, true));
//return new StreamableFile(await this.voiceService.textToFile(dto, true));
} else {
return new NotFoundException('Voice disabled');
}
@ -27,7 +27,7 @@ export class VoiceController {
async getText(@Query() dto: TtsRequestDto) {
dto.text = translit(dto.text);
if (Boolean(this.configService.get<boolean>('ENABLE_VOICE')) === true) {
return new StreamableFile(await this.voiceService.textToFile(dto));
//return new StreamableFile(await this.voiceService.textToFile(dto));
} else {
return new NotFoundException('Voice disabled');
}