Browse Source

* Formatting / Linting

master
vvandenb 2 years ago
parent
commit
55caa807a9
  1. 2
      back/volume/src/pong/entity/result.entity.ts
  2. 5
      back/volume/src/pong/game/Game.ts
  3. 4
      back/volume/src/pong/pong.module.ts
  4. 23
      back/volume/src/pong/pong.service.ts
  5. 2
      back/volume/src/types.d.ts
  6. 58
      back/volume/src/users/users.controller.ts
  7. 6
      back/volume/src/users/users.module.ts
  8. 4
      back/volume/src/users/users.service.ts
  9. 5
      front/volume/src/components/Pong/Ball.ts
  10. 2
      front/volume/src/components/Pong/ColorPicker.svelte
  11. 7
      front/volume/src/components/Pong/Game.ts
  12. 16
      front/volume/src/components/Pong/MapCustomization.svelte
  13. 5
      front/volume/src/components/Pong/utils.ts

2
back/volume/src/pong/entity/result.entity.ts

@ -14,7 +14,7 @@ export default class Result {
@PrimaryGeneratedColumn() @PrimaryGeneratedColumn()
id: number id: number
@ManyToMany(() => User, (player: User) => player.results, { cascade: true}) @ManyToMany(() => User, (player: User) => player.results, { cascade: true })
players: Array<User | null> // TODO: change to User[] for final version players: Array<User | null> // TODO: change to User[] for final version
@Column('text', { array: true }) @Column('text', { array: true })

5
back/volume/src/pong/game/Game.ts

@ -16,7 +16,6 @@ import { type MapDtoValidated } from '../dtos/MapDtoValidated'
import { type GameUpdate } from '../dtos/GameUpdate' import { type GameUpdate } from '../dtos/GameUpdate'
import { type GameInfo } from '../dtos/GameInfo' import { type GameInfo } from '../dtos/GameInfo'
import { type PongService } from '../pong.service' import { type PongService } from '../pong.service'
import { Injectable, Inject } from '@nestjs/common'
function gameLoop (game: Game): void { function gameLoop (game: Game): void {
const canvasRect: Rect = new Rect( const canvasRect: Rect = new Rect(
@ -34,7 +33,7 @@ function gameLoop (game: Game): void {
game.players[indexPlayerScored].score += 1 game.players[indexPlayerScored].score += 1
if (game.players[indexPlayerScored].score >= DEFAULT_WIN_SCORE) { if (game.players[indexPlayerScored].score >= DEFAULT_WIN_SCORE) {
console.log(`${game.players[indexPlayerScored].name} won!`) console.log(`${game.players[indexPlayerScored].name} won!`)
game.stop() void game.stop()
} }
} }
@ -116,7 +115,7 @@ export class Game {
if (playerIndex !== -1) { if (playerIndex !== -1) {
this.players.splice(playerIndex, 1) this.players.splice(playerIndex, 1)
if (this.players.length < 2) { if (this.players.length < 2) {
this.stop() void this.stop()
} }
} }
} }

4
back/volume/src/pong/pong.module.ts

@ -6,9 +6,7 @@ import { PongService } from './pong.service'
import { UsersModule } from 'src/users/users.module' import { UsersModule } from 'src/users/users.module'
@Module({ @Module({
imports: [ imports: [forwardRef(() => UsersModule), TypeOrmModule.forFeature([Result])],
forwardRef(() => UsersModule),
TypeOrmModule.forFeature([Result])],
providers: [PongGateway, PongService], providers: [PongGateway, PongService],
exports: [PongService] exports: [PongService]
}) })

23
back/volume/src/pong/pong.service.ts

@ -1,4 +1,4 @@
import { Inject, Injectable, forwardRef } from '@nestjs/common' import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm' import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm' import { Repository } from 'typeorm'
import { UsersService } from 'src/users/users.service' import { UsersService } from 'src/users/users.service'
@ -14,28 +14,28 @@ export class PongService {
private readonly usersService: UsersService private readonly usersService: UsersService
) {} ) {}
async updatePlayer (i: number, result: Result) { async updatePlayer (i: number, result: Result): Promise<void> {
const player: User | null = result.players[i] const player: User | null = result.players[i]
if (player == null) return if (player == null) return
player.matchs++ player.matchs++
if (result.score[i] > result.score[Math.abs(i - 1)]) player.wins++ if (result.score[i] > result.score[Math.abs(i - 1)]) player.wins++
else player.looses++ else player.looses++
player.winrate = (100 * player.wins) / player.matchs player.winrate = (100 * player.wins) / player.matchs
player.rank = await this.usersService.getRank(player.ftId) + 1 player.rank = (await this.usersService.getRank(player.ftId)) + 1
//player.results.push(result) // player.results.push(result)
this.usersService.save(player) this.usersService.save(player)
} }
async saveResult (players: Player[]) { async saveResult (players: Player[]): Promise<void> {
let result = new Result() const result = new Result()
let ply = new Array<User | null> const ply = new Array<User | null>()
ply.push(await this.usersService.findUserByName(players[0].name)) ply.push(await this.usersService.findUserByName(players[0].name))
ply.push(await this.usersService.findUserByName(players[1].name)) ply.push(await this.usersService.findUserByName(players[1].name))
result.players = ply; result.players = ply
result.score = [players[0].score, players[1].score] result.score = [players[0].score, players[1].score]
this.resultsRepository.save(result) await this.resultsRepository.save(result)
this.updatePlayer(0, result) await this.updatePlayer(0, result)
this.updatePlayer(1, result) await this.updatePlayer(1, result)
} }
async getHistory (): Promise<Result[]> { async getHistory (): Promise<Result[]> {
@ -48,5 +48,4 @@ export class PongService {
const results = await this.usersService.getResults(ftId) const results = await this.usersService.getResults(ftId)
return results.sort((a, b) => (a.date < b.date ? 1 : -1)) return results.sort((a, b) => (a.date < b.date ? 1 : -1))
} }
} }

2
back/volume/src/types.d.ts

@ -1,5 +1,5 @@
declare module 'passport-42' { declare module 'passport-42' {
export type Profile = any export type Profile = any
export type VerifyCallback = any export type VerifyCallback = any
export class Strategy {} export class Strategy {}!
} }

58
back/volume/src/users/users.controller.ts

@ -11,7 +11,8 @@ import {
Res, Res,
StreamableFile, StreamableFile,
BadRequestException, BadRequestException,
Redirect Redirect,
type NotFoundException
} from '@nestjs/common' } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express' import { FileInterceptor } from '@nestjs/platform-express'
@ -30,59 +31,59 @@ import { ApiBody, ApiConsumes } from '@nestjs/swagger'
import { type Request, Response } from 'express' import { type Request, Response } from 'express'
import { createReadStream } from 'fs' import { createReadStream } from 'fs'
import { join } from 'path' import { join } from 'path'
import type Result from 'src/pong/entity/result.entity'
@Controller() @Controller()
export class UsersController { export class UsersController {
constructor( constructor (
private readonly usersService: UsersService, private readonly usersService: UsersService,
private readonly pongService: PongService private readonly pongService: PongService
) { } ) {}
@Get('all') @Get('all')
async getAllUsers(): Promise<User[]> { async getAllUsers (): Promise<User[]> {
return await this.usersService.findUsers() return await this.usersService.findUsers()
} }
@Get('online') @Get('online')
async getOnlineUsers(): Promise<User[]> { async getOnlineUsers (): Promise<User[]> {
return await this.usersService.findOnlineUsers() return await this.usersService.findOnlineUsers()
} }
@Get('friends') @Get('friends')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getFriends(@FtUser() profile: Profile) { async getFriends (@FtUser() profile: Profile): Promise<User[]> {
return await this.usersService.getFriends(profile.id) return await this.usersService.getFriends(profile.id)
} }
@Get('invits') @Get('invits')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getInvits(@FtUser() profile: Profile) { async getInvits (@FtUser() profile: Profile): Promise<User[]> {
return await this.usersService.getInvits(profile.id) return await this.usersService.getInvits(profile.id)
} }
@Get('leader') @Get('leader')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getLeader() { async getLeader (): Promise<User[]> {
return await this.usersService.getLeader() return await this.usersService.getLeader()
} }
@Get('leader/:id') @Get('leader/:id')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getRank(@Param('id', ParseIntPipe) id: number) { async getRank (@Param('id', ParseIntPipe) id: number): Promise<number> {
return await this.usersService.getRank(id) return await this.usersService.getRank(id)
} }
@Get('history') @Get('history')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getHistory() { async getHistory (): Promise<Result[]> {
return await this.pongService.getHistory() return await this.pongService.getHistory()
} }
@Get('history/:id') @Get('history/:id')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getHistoryById(@Param('id', ParseIntPipe) id: number) { async getHistoryById (@Param('id', ParseIntPipe) id: number): Promise<Result[]> {
return this.pongService.getHistoryById(id) return await this.pongService.getHistoryById(id)
} }
@Post('avatar') @Post('avatar')
@ -107,43 +108,43 @@ export class UsersController {
description: 'A new avatar for the user', description: 'A new avatar for the user',
type: AvatarUploadDto type: AvatarUploadDto
}) })
async addAvatar( async addAvatar (
@FtUser() profile: Profile, @FtUser() profile: Profile,
@UploadedFile() file: Express.Multer.File @UploadedFile() file: Express.Multer.File
) { ): Promise<void> {
await this.usersService.addAvatar(profile.id, file.filename) await this.usersService.addAvatar(profile.id, file.filename)
} }
@Get('avatar') @Get('avatar')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getAvatar( async getAvatar (
@FtUser() profile: Profile, @FtUser() profile: Profile,
@Res({ passthrough: true }) response: Response @Res({ passthrough: true }) response: Response
) { ): Promise<StreamableFile | null> {
return await this.getAvatarById(profile.id, response) return await this.getAvatarById(profile.id, response)
} }
@Get('user/:name') @Get('user/:name')
async getUserByName(@Param('name') username: string): Promise<User | null> { async getUserByName (@Param('name') username: string): Promise<User | null> {
return await this.usersService.findUserByName(username) return await this.usersService.findUserByName(username)
} }
@Get('invit/:id') @Get('invit/:id')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async invitUser( async invitUser (
@FtUser() profile: Profile, @FtUser() profile: Profile,
@Param('id', ParseIntPipe) id: number @Param('id', ParseIntPipe) id: number
) { ): Promise<NotFoundException | null | undefined> {
return await this.usersService.invit(profile.id, id) return await this.usersService.invit(profile.id, id)
} }
@Get('avatar/:id') @Get('avatar/:id')
async getAvatarById( async getAvatarById (
@Param('id', ParseIntPipe) ftId: number, @Param('id', ParseIntPipe) ftId: number,
@Res({ passthrough: true }) response: Response @Res({ passthrough: true }) response: Response
) { ): Promise<StreamableFile | null> {
const user = await this.usersService.findUser(ftId) const user = await this.usersService.findUser(ftId)
if (user == null) return if (user == null) return null
const filename = user.avatar const filename = user.avatar
const stream = createReadStream(join(process.cwd(), 'avatars/' + filename)) const stream = createReadStream(join(process.cwd(), 'avatars/' + filename))
response.set({ response.set({
@ -154,15 +155,15 @@ export class UsersController {
} }
@Get(':id') @Get(':id')
async getUserById( async getUserById (
@Param('id', ParseIntPipe) ftId: number @Param('id', ParseIntPipe) ftId: number
): Promise<User | null> { ): Promise<User | null> {
return await this.usersService.findUser(ftId) return await this.usersService.findUser(ftId)
} }
@Post(":id") @Post(':id')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async createById(@Body() payload: UserDto) { async createById (@Body() payload: UserDto): Promise<User | null> {
const user = await this.usersService.findUser(payload.ftId) const user = await this.usersService.findUser(payload.ftId)
if (user != null) { if (user != null) {
return await this.usersService.update(user, payload) return await this.usersService.update(user, payload)
@ -173,13 +174,13 @@ export class UsersController {
@Get() @Get()
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async getUser(@FtUser() profile: Profile): Promise<User | null> { async getUser (@FtUser() profile: Profile): Promise<User | null> {
return await this.usersService.findUser(profile.id) return await this.usersService.findUser(profile.id)
} }
@Post() @Post()
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async create(@Body() payload: UserDto, @FtUser() profile: Profile) { async create (@Body() payload: UserDto, @FtUser() profile: Profile): Promise<User | null> {
const user = await this.usersService.findUser(profile.id) const user = await this.usersService.findUser(profile.id)
if (user != null) { if (user != null) {
return await this.usersService.update(user, payload) return await this.usersService.update(user, payload)
@ -187,5 +188,4 @@ export class UsersController {
return await this.usersService.create(payload) return await this.usersService.create(payload)
} }
} }
} }

6
back/volume/src/users/users.module.ts

@ -6,11 +6,9 @@ import { UsersService } from './users.service'
import { PongModule } from 'src/pong/pong.module' import { PongModule } from 'src/pong/pong.module'
@Module({ @Module({
imports: [ imports: [forwardRef(() => PongModule), TypeOrmModule.forFeature([User])],
forwardRef(() => PongModule),
TypeOrmModule.forFeature([User])],
controllers: [UsersController], controllers: [UsersController],
providers: [UsersService], providers: [UsersService],
exports: [UsersService] exports: [UsersService]
}) })
export class UsersModule { } export class UsersModule {}

4
back/volume/src/users/users.service.ts

@ -4,13 +4,13 @@ import { EntityNotFoundError, QueryFailedError, Repository } from 'typeorm'
import { User } from './entity/user.entity' import { User } from './entity/user.entity'
import { type UserDto } from './dto/user.dto' import { type UserDto } from './dto/user.dto'
import { type Channel } from 'src/chat/entity/channel.entity' import { type Channel } from 'src/chat/entity/channel.entity'
import Result from 'src/pong/entity/result.entity' import type Result from 'src/pong/entity/result.entity'
@Injectable() @Injectable()
@Catch(QueryFailedError, EntityNotFoundError) @Catch(QueryFailedError, EntityNotFoundError)
export class UsersService { export class UsersService {
constructor ( constructor (
@InjectRepository(User) private readonly usersRepository: Repository<User>, @InjectRepository(User) private readonly usersRepository: Repository<User>
) {} ) {}
save (user: User) { save (user: User) {

5
front/volume/src/components/Pong/Ball.ts

@ -4,10 +4,7 @@ export class Ball {
rect: Rect; rect: Rect;
speed: Point; speed: Point;
constructor( constructor(spawn: Point, size: Point = new Point(20, 20)) {
spawn: Point,
size: Point = new Point(20, 20)
) {
this.rect = new Rect(spawn, size); this.rect = new Rect(spawn, size);
} }

2
front/volume/src/components/Pong/ColorPicker.svelte

@ -3,7 +3,7 @@
</script> </script>
<div> <div>
<input type="color" bind:value={color}> <input type="color" bind:value={color} />
</div> </div>
<style> <style>

7
front/volume/src/components/Pong/Game.ts

@ -20,7 +20,12 @@ export class Game {
elementsColor: string; elementsColor: string;
backgroundColor: string; backgroundColor: string;
constructor(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, elementsColor: string, backgroundColor: string) { constructor(
canvas: HTMLCanvasElement,
context: CanvasRenderingContext2D,
elementsColor: string,
backgroundColor: string
) {
this.canvas = canvas; this.canvas = canvas;
this.context = context; this.context = context;
this.players = []; this.players = [];

16
front/volume/src/components/Pong/MapCustomization.svelte

@ -72,9 +72,21 @@
<h1>Map Customization:</h1> <h1>Map Customization:</h1>
<div> <div>
Width: Width:
<input type="range" min={DEFAULT_MAP_SIZE.x} max=1000 bind:value={map.size.x} on:input={sizeChange} /> <input
type="range"
min={DEFAULT_MAP_SIZE.x}
max="1000"
bind:value={map.size.x}
on:input={sizeChange}
/>
Height: Height:
<input type="range" min={DEFAULT_MAP_SIZE.y} max=800 bind:value={map.size.y} on:input={sizeChange} /> <input
type="range"
min={DEFAULT_MAP_SIZE.y}
max="800"
bind:value={map.size.y}
on:input={sizeChange}
/>
</div> </div>
<canvas <canvas
bind:this={canvas} bind:this={canvas}

5
front/volume/src/components/Pong/utils.ts

@ -32,10 +32,7 @@ export class Rect {
this.size = size; this.size = size;
} }
draw( draw(context: CanvasRenderingContext2D, color: string) {
context: CanvasRenderingContext2D,
color: string
) {
const offset: Point = new Point(this.size.x / 2, this.size.y / 2); const offset: Point = new Point(this.size.x / 2, this.size.y / 2);
context.fillStyle = color; context.fillStyle = color;

Loading…
Cancel
Save