This commit is contained in:
Kirill Ivlev 2024-11-28 01:30:41 +04:00
parent 2b59393d98
commit 2073dcff93
14 changed files with 92 additions and 17 deletions

View file

@ -27,7 +27,7 @@ export class GameProceedGameQueueCommandHandler
return this.cmdBus.execute(new NextQuestionCommand()); return this.cmdBus.execute(new NextQuestionCommand());
} }
this.sharedService.notifyAllClients<IGameQueueSocketEvent>(ClientNotificationType.GameQueueItem, { this.sharedService.notifyAllClients<IGameQueueSocketEvent>(ClientNotificationType.GameQueueItem, {
_id: item.id, _id: item._id,
completed: item.completed, completed: item.completed,
target: item.target, target: item.target,
type: item.type, type: item.type,

View file

@ -250,7 +250,7 @@ export class BanPlayer extends GameCard {
async handle() { async handle() {
await this.commandBus.execute( await this.commandBus.execute(
new SelectTargetPlayerCommand(this.telegramId, DebuffsConsts.bannedFor, 2,false) new SelectTargetPlayerCommand(this.telegramId, DebuffsConsts.bannedFor, getRandomInt(2,3), false)
) )
await this.queryBus.execute(new FilterGuestsWithPropertyQuery(null,null,null)); await this.queryBus.execute(new FilterGuestsWithPropertyQuery(null,null,null));
this.eventBus.subscribe((data) =>{ this.eventBus.subscribe((data) =>{

View file

@ -0,0 +1,4 @@
export class StateChangedEvent {
constructor(state: string) {
}
}

View file

@ -52,7 +52,26 @@ export class GameService implements OnApplicationBootstrap{
} }
async getGameQueueItem() { async getGameQueueItem() {
return this.gameQueueModel.findOne({ completed: false }).exec(); const item = await this.gameQueueModel.aggregate([
{
$match: { completed: false }
},
{
$addFields: {
priority: {
$cond: [{ $eq: ["$type", "versus"] }, 1, 0]
}
}
},
{
$sort: { priority: -1 }
},
{
$limit: 1
}
]).exec();
console.log(item[0]);
return item[0];
} }
async markQueueAsCompleted(id: string| null) { async markQueueAsCompleted(id: string| null) {

View file

@ -13,6 +13,8 @@ import {GuestPropertyNamesConsts} from "../../Consts/guest-property-names.consts
import {SetGuestPropertyCommand} from "../../guests/command/set-guest-property.command"; import {SetGuestPropertyCommand} from "../../guests/command/set-guest-property.command";
import {IVersusBeginSocketEvent, IVersusEndSocketEvent} from "../../Consts/types"; import {IVersusBeginSocketEvent, IVersusEndSocketEvent} from "../../Consts/types";
import {ClientNotificationType} from "../../socket/socket.gateway"; import {ClientNotificationType} from "../../socket/socket.gateway";
import {CreateNewQueueItemCommand} from "../commands/create-new-queue-item.command";
import {GameQueueTypes} from "../../schemas/game-queue.schema";
@Injectable() @Injectable()
export class VersusService { export class VersusService {
@ -42,6 +44,7 @@ export class VersusService {
async beginVersus(player1: number, player2: number) { async beginVersus(player1: number, player2: number) {
const [p1data,p2data] = await Promise.all([this.guestService.findById(player1), this.guestService.findById(player2)]); const [p1data,p2data] = await Promise.all([this.guestService.findById(player1), this.guestService.findById(player2)]);
await this.cmdBus.execute(new CreateNewQueueItemCommand(player1, GameQueueTypes.versus));
await this.sharedService.setConfig(VersusService.configKeyCurrentAction, JSON.stringify({ await this.sharedService.setConfig(VersusService.configKeyCurrentAction, JSON.stringify({
action:'versus', action:'versus',
data: { data: {

View file

@ -76,6 +76,9 @@ export class GuestsService {
async findById(id: number) { async findById(id: number) {
const result = await this.guestModel.findOne({ telegramId: id }).exec(); const result = await this.guestModel.findOne({ telegramId: id }).exec();
if(!result) {
return null;
}
delete result.photo; delete result.photo;
return result; return result;
} }

View file

@ -0,0 +1,17 @@
import {EventsHandler, IEventHandler} from "@nestjs/cqrs";
import {StateChangedEvent} from "../../game/events/state-changed.event";
import {QuizService} from "../quiz.service";
import {Logger} from "@nestjs/common";
@EventsHandler(StateChangedEvent)
export class StateChangedEventHandler implements IEventHandler<StateChangedEvent> {
logger = new Logger(StateChangedEventHandler.name);
constructor(private quizService: QuizService) {
}
async handle(event: StateChangedEvent) {
this.logger.verbose(`[StateChangedEventHandler] enter, event: ${event}}`)
await this.quizService.calculateEndgamePoints();
}
}

View file

@ -26,6 +26,11 @@ export class QuizController {
return this.quizService.proceedWithGame(); return this.quizService.proceedWithGame();
} }
@Post('timeout')
async Timeout() {
return await this.quizService.questionTimeout();
}
@Post('questions') @Post('questions')
async postQuestion(@Body() questionDto: QuestionDto[]) { async postQuestion(@Body() questionDto: QuestionDto[]) {
return await this.quizService.populateQuestions(questionDto); return await this.quizService.populateQuestions(questionDto);

View file

@ -12,12 +12,17 @@ import { MarkQuestionsAsUnansweredCommandHandler } from './command-handlers/mark
import { PenaltyModule } from '../penalty/penalty.module'; import { PenaltyModule } from '../penalty/penalty.module';
import {ConfigModule, ConfigService} from "@nestjs/config"; import {ConfigModule, ConfigService} from "@nestjs/config";
import {Config, ConfigSchema} from "../schemas/config.schema"; import {Config, ConfigSchema} from "../schemas/config.schema";
import {StateChangedEventHandler} from "./event-handlers/state-changed-event.handler";
const cmdHandlers = [ const cmdHandlers = [
GameNextQuestionCommandHandler, GameNextQuestionCommandHandler,
MarkQuestionsAsUnansweredCommandHandler, MarkQuestionsAsUnansweredCommandHandler,
]; ];
const eventHandlers = [
StateChangedEventHandler
]
@Global() @Global()
@Module({ @Module({
imports: [ imports: [
@ -33,6 +38,6 @@ const cmdHandlers = [
], ],
controllers: [QuizController], controllers: [QuizController],
exports: [QuizService], exports: [QuizService],
providers: [QuizService,ConfigService, ...cmdHandlers], providers: [QuizService,ConfigService, ...cmdHandlers, ...eventHandlers],
}) })
export class QuizModule {} export class QuizModule {}

View file

@ -60,6 +60,9 @@ export class QuizService {
); );
// check that answer exist // check that answer exist
const shortAnswers = question.answers.map((answer) => answer.substring(0,50)); const shortAnswers = question.answers.map((answer) => answer.substring(0,50));
if(question.countdownFinished) {
return;
}
const shortValidAnswer = question.valid.substring(0,50); const shortValidAnswer = question.valid.substring(0,50);
if(shortAnswers.indexOf(answer) === -1) { if(shortAnswers.indexOf(answer) === -1) {
this.logger.warn(`[validateAnswer] this question is not on game now`); this.logger.warn(`[validateAnswer] this question is not on game now`);
@ -124,7 +127,7 @@ export class QuizService {
return false; return false;
} }
const diff = Math.abs(new Date(answers[0].time).getTime() - new Date(answers[1].time).getTime()) / 1000; const diff = Math.abs(new Date(answers[0].time).getTime() - new Date(answers[1].time).getTime()) / 1000;
return diff <= 5; return diff <= 1;
} }
async calculateScore() { async calculateScore() {
@ -148,7 +151,7 @@ export class QuizService {
const winner = sortedAnswers.find((answer) => answer.valid); const winner = sortedAnswers.find((answer) => answer.valid);
let targetUser = 0; let targetUser = 0;
if(winner) { if(winner) {
const totalWinningScore = 80; const totalWinningScore = 50;
sortedAnswers.filter(x => x.valid).forEach((answer) => { sortedAnswers.filter(x => x.valid).forEach((answer) => {
this.logger.debug(`Giving 1 point to all who answered right`); this.logger.debug(`Giving 1 point to all who answered right`);
this.commandBus.execute(new IncreasePlayerWinningRateCommand(answer.user, this.commandBus.execute(new IncreasePlayerWinningRateCommand(answer.user,
@ -165,7 +168,7 @@ export class QuizService {
)); ));
} }
} }
await this.commandBus.execute(new IncreasePlayerWinningRateCommand(sortedAnswers[0].user, 15)); await this.commandBus.execute(new IncreasePlayerWinningRateCommand(sortedAnswers[0].user, 5));
this.logger.debug(`Giving 1 point to first`); this.logger.debug(`Giving 1 point to first`);
await this.commandBus.execute(new IncreasePlayerScoreCommand(winner.user,1)); await this.commandBus.execute(new IncreasePlayerScoreCommand(winner.user,1));
targetUser = winner.user; targetUser = winner.user;
@ -214,6 +217,9 @@ export class QuizService {
} }
} }
await this.sharedService.setConfig('endgame-points', JSON.stringify(result)); await this.sharedService.setConfig('endgame-points', JSON.stringify(result));
await this.commandBus.execute(new IncreasePlayerScoreCommand(result.maxInvalidAnswers.id, 2));
await this.commandBus.execute(new IncreasePlayerScoreCommand(result.maxPenalties.id, 2));
await this.commandBus.execute(new IncreasePlayerScoreCommand(result.maxRewards.id, -2));
return result; return result;
} }
@ -340,4 +346,11 @@ export class QuizService {
const res = await this.sharedService.getConfig('endgame-points'); const res = await this.sharedService.getConfig('endgame-points');
return JSON.parse(res.value); return JSON.parse(res.value);
} }
async questionTimeout() {
const question = await this.get();
question.countdownFinished = true;
await question.save();
return question;
}
} }

View file

@ -9,6 +9,7 @@ export enum GameQueueTypes {
screpaAnounce = 'screpa', screpaAnounce = 'screpa',
showresults = 'show_results', showresults = 'show_results',
extra_points = 'extra_points', extra_points = 'extra_points',
versus = 'versus',
} }
export type GameQueueDocument = GameQueue & Document; export type GameQueueDocument = GameQueue & Document;

View file

@ -31,5 +31,7 @@ export class Question {
userAnswers: QuestionAnswer[]; userAnswers: QuestionAnswer[];
@Prop({ default: false }) @Prop({ default: false })
scoreCalculated: boolean; scoreCalculated: boolean;
@Prop({ default: false})
countdownFinished: boolean;
} }
export const QuestionSchema = SchemaFactory.createForClass(Question); export const QuestionSchema = SchemaFactory.createForClass(Question);

View file

@ -38,16 +38,16 @@ export class StateController {
if (setStateDto.value === 'quiz') { if (setStateDto.value === 'quiz') {
this.eventBus.publish(new GameStartedEvent()); this.eventBus.publish(new GameStartedEvent());
} else if(setStateDto.value === 'onboarding') { } else if(setStateDto.value === 'onboarding') {
this.telegramService.send<MqtMessageModel,any>( // this.telegramService.send<MqtMessageModel,any>(
{ cmd: CommandsConsts.SetCommands }, // { cmd: CommandsConsts.SetCommands },
[ // [
{ command: 'start', description: 'главное меню'}, // { command: 'start', description: 'главное меню'},
{ command: 'cards', description: 'сыграть карту'}, // { command: 'cards', description: 'сыграть карту'},
{ command: 'question', description: 'вернутся к вопросу'} // { command: 'question', description: 'вернутся к вопросу'}
] // ]
).subscribe(() => { // ).subscribe(() => {
this.logger.verbose('Bot commands updated'); // this.logger.verbose('Bot commands updated');
}); // });
} else { } else {
this.logger.verbose('reset commands'); this.logger.verbose('reset commands');
this.telegramService.emit({ cmd: CommandsConsts.ResetCommands }, {}); this.telegramService.emit({ cmd: CommandsConsts.ResetCommands }, {});

View file

@ -5,6 +5,7 @@ import { Model } from 'mongoose';
import { EventBus } from '@nestjs/cqrs'; import { EventBus } from '@nestjs/cqrs';
import { PrepareGameEvent } from '../game/events/prepare-game.event'; import { PrepareGameEvent } from '../game/events/prepare-game.event';
import {IStateInfo} from "../Consts/types"; import {IStateInfo} from "../Consts/types";
import {StateChangedEvent} from "../game/events/state-changed.event";
interface StateDTO { interface StateDTO {
name: string; name: string;
@ -35,6 +36,8 @@ export class StateService {
if (newValue === 'onboarding') { if (newValue === 'onboarding') {
this.eventBus.publish(new PrepareGameEvent()); this.eventBus.publish(new PrepareGameEvent());
} }
this.eventBus.publish(new StateChangedEvent(newValue));
const stateEntity = await this.getState(name); const stateEntity = await this.getState(name);
stateEntity.value = newValue; stateEntity.value = newValue;
await stateEntity.save(); await stateEntity.save();