Skip to content

Commit

Permalink
allows players to pick up items in game
Browse files Browse the repository at this point in the history
  • Loading branch information
l-brendle committed Oct 19, 2023
1 parent cca573b commit 2eef9e9
Show file tree
Hide file tree
Showing 18 changed files with 138 additions and 101 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<bal-icon *ngFor="let char of characters" name="account" style="z-index: 1000; position: absolute;" [ngStyle]="{'top': char.posY + 'px', 'left': char.posX + 'px'}" [color]="char.color"></bal-icon>
<bal-icon *ngFor="let pickup of pickups" [name]=pickup.icon style="z-index: 9000; position: absolute;" [ngStyle]="{'top': pickup.posY + 'px', 'left': pickup.posX + 'px'}" [color]="pickup.color"></bal-icon>
<bal-card class="mt-medium">
<bal-card-content class="is-flex fg-small">
<bal-heading level="medium">Mini-Game</bal-heading>
Expand Down
13 changes: 10 additions & 3 deletions angular-frontend/src/app/components/game/game.component.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {Component, HostListener, Input, OnDestroy, OnInit} from '@angular/core';

import { Client } from '@stomp/stompjs';
import {Character} from "../../../model";
import {Character, Pickup} from "../../../model";

@Component({
selector: 'app-game',
Expand All @@ -17,17 +17,22 @@ export class GameComponent implements OnInit, OnDestroy {

// Game stuff
characters: Character[] = [];
pickups: Pickup[] = [];

ngOnInit(): void {
if (this.client.connected) {
this.client.subscribe("/topic/game/character", (payload => this.updateCharacter(JSON.parse(payload.body))))
this.client.subscribe("/topic/game/character_removal", (payload => this.removeCharacter(JSON.parse(payload.body))))
this.client.subscribe("/topic/game/pickups", (payload => this.updatePickups(JSON.parse(payload.body))))

}
}

ngOnDestroy(): void {
if (this.client.connected) {
//this.client.unsubscribe("/topic/chat")
this.client.unsubscribe("/topic/game/character")
this.client.unsubscribe("/topic/game/character_removal")
this.client.unsubscribe("/topic/game/pickups")
}
}

Expand Down Expand Up @@ -78,7 +83,6 @@ export class GameComponent implements OnInit, OnDestroy {

updateCharacter(character : Character) {
const characterIndexToUpdate = this.characters.findIndex((char) => char.name === character.name);
console.log("Character update");
if (characterIndexToUpdate === -1) {
this.characters.push(character);
} else {
Expand All @@ -90,4 +94,7 @@ export class GameComponent implements OnInit, OnDestroy {
this.characters = this.characters.filter(char => char.name != character.name)
}

private updatePickups(pickups: Pickup[]) {
this.pickups = pickups;
}
}
9 changes: 8 additions & 1 deletion angular-frontend/src/model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,14 @@ export interface Cursor {
}

export interface Character {
name: string
name: string;
color: string;
posX: number;
posY: number;
}

export interface Pickup {
icon: string;
color: string;
posX: number;
posY: number;
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.baloise.collab.springbackend;

import lombok.Getter;

public class ColorProvider {

@Getter
private static final String[] colors =
{
"primary", "grey", "success", "warning", "danger"
};
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
@EnableWebSocketMessageBroker
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private final ButtonWebSocketHandler buttonHandler;

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.Optional;

@RequiredArgsConstructor
Expand All @@ -21,10 +23,11 @@ public class ChatWebSocketHandler {

private final ObjectMapper objectMapper;
private final ActiveUserAdministration userAdministration;
private final SimpMessagingTemplate messagingTemplate;

@MessageMapping("/chat")
@SendTo("/topic/chat")
public OutgoingChatMessageDTO handleCursorUpdate(Message<String> message) throws Exception {
public OutgoingChatMessageDTO handleChatMessage(Message<String> message) throws Exception {
var optionalToken = Optional.ofNullable((UsernamePasswordAuthenticationToken) message.getHeaders().get("simpUser"));
String userName = optionalToken.map(AbstractAuthenticationToken::getName).orElse("dummyUser");

Expand All @@ -35,4 +38,10 @@ public OutgoingChatMessageDTO handleCursorUpdate(Message<String> message) throws
return new OutgoingChatMessageDTO(dto.text(), userDTO, dto.clientTimestamp());
}

public void sendSystemChatMessage(String chatMessage) {
var systemUserDTO = new UserDTO("System", "danger");
var message = new OutgoingChatMessageDTO(chatMessage, systemUserDTO, new Date().toString());
messagingTemplate.convertAndSend("/topic/chat", message);
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.baloise.collab.springbackend.chat;

record IncomingChatMessageDTO(
public record IncomingChatMessageDTO(
String text,
String clientTimestamp
) {}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.baloise.collab.springbackend.useradmin.UserDTO;

record OutgoingChatMessageDTO(
public record OutgoingChatMessageDTO(
String text,
UserDTO user,
String timestamp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public class Character {
private long posX;
private long posY;
private Set<String> pressedKeys;
private int score;

private final float speed = 0.1f;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.baloise.collab.springbackend.game;

import com.baloise.collab.springbackend.chat.ChatWebSocketHandler;
import com.baloise.collab.springbackend.useradmin.UserDTO;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
Expand All @@ -21,6 +22,7 @@ public class CharacterController {
private final Set<Character> activeCharacters = new HashSet<>();

private final SimpMessagingTemplate messageSender;
private final ChatWebSocketHandler chatWebSocketHandler;

private final int spawnX = 0;
private final int spawnY = 0;
Expand Down Expand Up @@ -66,6 +68,7 @@ public void moveCharacter(Character character, long frametime) {
private void sendRemoveCharacter(Character character) {
CharacterDTO characterDTO = new CharacterDTO(character.getName(), character.getColor(), character.getPosXRounded(), character.getPosYRounded());
messageSender.convertAndSend("/topic/game/character_removal", characterDTO);
chatWebSocketHandler.sendSystemChatMessage(character.getName() + " reached score: " + character.getScore());
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
public class GameLoopExecutor {

private final CharacterController characterController;
private final PickUpHandler pickUpHandler;
private Long lastFrameTime;

@Getter
Expand All @@ -23,17 +24,23 @@ public void run() throws InterruptedException {
var characters = characterController.getActiveCharacters();
var time = System.currentTimeMillis();
if(!characters.isEmpty()){
characters.forEach(character -> characterController.moveCharacter(character, time-lastFrameTime));
characters.forEach(character -> {
characterController.moveCharacter(character, time-lastFrameTime);
var scoreUpdate = pickUpHandler.collectPickups(character);
character.setScore(character.getScore() + scoreUpdate);
});
}
pickUpHandler.spawnPickupsAndSendToClients();
lastFrameTime = System.currentTimeMillis();
Thread.sleep(50);
Thread.sleep(30);
}
}

@Async
public void quit(){
running = false;
lastFrameTime = 0L;

}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.baloise.collab.springbackend.game;

import com.baloise.collab.springbackend.ButtonMessageDTO;
import com.baloise.collab.springbackend.useradmin.ActiveUserAdministration;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -14,7 +13,6 @@
import org.springframework.stereotype.Controller;

import java.util.Optional;
import java.util.concurrent.Future;

@RequiredArgsConstructor
@Log
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package com.baloise.collab.springbackend.game;

import com.baloise.collab.springbackend.ColorProvider;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Component
@RequiredArgsConstructor
public class PickUpHandler {


private final SimpMessagingTemplate messageSender;
private long lastSpawn;
private final List<Pickup> pickups = new ArrayList<>();

@Getter
private static final String[] icons =
{
"star-shape", "star-full", "web", "twitter"
};

Random random = new Random();

public int collectPickups(Character character) {
var pickupsToCollect = new ArrayList<Pickup>();
pickups.forEach(pickup -> {
var distance = Math.abs(character.getPosX() - pickup.posX())
+ Math.abs(character.getPosY() - pickup.posY());
if(distance < 10) {
pickupsToCollect.add(pickup);
}
});

pickups.removeAll(pickupsToCollect);
return pickupsToCollect.size();
}

public void spawnPickupsAndSendToClients() {
var currentTime = System.currentTimeMillis();
if (currentTime - lastSpawn > 3000) {
lastSpawn = currentTime;
pickups.add(
new Pickup(
icons[random.nextInt(0, icons.length)],
ColorProvider.getColors()[random.nextInt(0, icons.length)],
random.nextInt(0, 1000),
random.nextInt(0, 300)
)
);
}
sendPickupsToClients();
}

public void clearPickupsAndSendToClients() {
pickups.clear();
sendPickupsToClients();
}

public void sendPickupsToClients() {
messageSender.convertAndSend("/topic/game/pickups", pickups);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.baloise.collab.springbackend.game;

public record Pickup(
String icon,
String color,
int posX,
int posY
) {
}
Loading

0 comments on commit 2eef9e9

Please sign in to comment.