Skip to content

Commit

Permalink
More tests, and some fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Pelayori committed Apr 27, 2024
1 parent 008d580 commit 47e4a78
Show file tree
Hide file tree
Showing 11 changed files with 90 additions and 20 deletions.
8 changes: 7 additions & 1 deletion src/main/java/com/uniovi/controllers/GameController.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,15 @@ public String getMultiplayerGame() {

@GetMapping("/multiplayerGame/{code}")
public String joinMultiplayerGame(@PathVariable String code, HttpSession session, Principal principal, Model model) {
if (!multiplayerSessionService.existsCode(code)) {
model.addAttribute("errorKey", "multi.code.invalid");
return "game/multiplayerGame";
}

Optional<Player> player = playerService.getUserByUsername(principal.getName());
Player p = player.orElse(null);
isMultiPlayer=true;
if(playerService.changeMultiplayerCode(p.getId(),code)){
if (playerService.changeMultiplayerCode(p.getId(),code)) {
multiplayerSessionService.addToLobby(code,p.getId());
model.addAttribute("multiplayerGameCode",code);
session.setAttribute("multiplayerCode",code);
Expand Down Expand Up @@ -153,6 +158,7 @@ public List<String> updatePlayerList(@PathVariable String code) {
Collections.sort(playerNames);
return playerNames;
}

@GetMapping("/game/lobby")
public String createLobby( HttpSession session, Model model) {
int code = Integer.parseInt((String)session.getAttribute("multiplayerCode"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ public interface MultiplayerSessionService {
void addToLobby(String code, Long id);

void changeScore(String code,Long id,int score);

boolean existsCode(String code);
}
35 changes: 24 additions & 11 deletions src/main/java/com/uniovi/services/impl/MultiplayerSessionImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public Map<Player, Integer> getPlayersWithScores(int multiplayerCode) {
List<Player> sortedPlayers = playerScores.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
.toList();

Map<Player, Integer> playersSorted = new HashMap<>();
for (Player player : sortedPlayers) {
Expand All @@ -45,25 +45,38 @@ public Map<Player, Integer> getPlayersWithScores(int multiplayerCode) {

@Override
public void multiCreate(String code, Long id) {
Player p = playerRepository.findById(id).get();
multiplayerSessionRepository.save(new MultiplayerSession(code,p));
Player p = playerRepository.findById(id).orElse(null);

if (p != null)
multiplayerSessionRepository.save(new MultiplayerSession(code,p));
}

@Override
@Transactional
public void addToLobby(String code, Long id) {
Player p = playerRepository.findById(id).get();
MultiplayerSession ms=multiplayerSessionRepository.findByMultiplayerCode(code);
ms.addPlayer(p);
multiplayerSessionRepository.save(ms);
Player p = playerRepository.findById(id).orElse(null);

if (p != null) {
MultiplayerSession ms = multiplayerSessionRepository.findByMultiplayerCode(code);
ms.addPlayer(p);
multiplayerSessionRepository.save(ms);
}
}

@Override
@Transactional
public void changeScore(String code, Long id, int score) {
Player p = playerRepository.findById(id).get();
MultiplayerSession ms=multiplayerSessionRepository.findByMultiplayerCode(code);
ms.getPlayerScores().put(p,score);
multiplayerSessionRepository.save(ms);
Player p = playerRepository.findById(id).orElse(null);

if (p != null) {
MultiplayerSession ms = multiplayerSessionRepository.findByMultiplayerCode(code);
ms.getPlayerScores().put(p, score);
multiplayerSessionRepository.save(ms);
}
}

@Override
public boolean existsCode(String code) {
return multiplayerSessionRepository.findByMultiplayerCode(code) != null;
}
}
8 changes: 5 additions & 3 deletions src/main/java/com/uniovi/services/impl/PlayerServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,19 @@
import org.springframework.stereotype.Service;
import com.uniovi.entities.Role;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Service
public class PlayerServiceImpl implements PlayerService {
private final PlayerRepository playerRepository;
private final RoleService roleService;
private final PasswordEncoder passwordEncoder;

private MultiplayerSessionService multiplayerSessionService;
private final MultiplayerSessionService multiplayerSessionService;
private final Random random = new SecureRandom();

public PlayerServiceImpl(PlayerRepository playerRepository, RoleService roleService, MultiplayerSessionService multiplayerSessionService,PasswordEncoder passwordEncoder) {
this.playerRepository = playerRepository;
Expand Down Expand Up @@ -190,7 +192,7 @@ public int createMultiplayerGame(Long id){
return -1;

Player p = player.get();
int code = (int)Math.floor(Math.random()*10000);
int code = random.nextInt(10000);
p.setMultiplayerCode(code);
playerRepository.save(p);
return code;
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/messages.properties
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ multi.results =Ver resultados
multi.finished= Partida finalizada
multi.points = Puntuaciones
multi.menu = Ir a la página de inicio
multi.code.invalid = Código de partida inválido
# -------------------Statements for the apiHome.html file---------------------
api.doc.title=Documentación de la API
api.doc.description=Esta es la documentación de la API de WIQ. Aquí puedes encontrar información sobre los recursos disponibles, los parámetros que aceptan y los ejemplos de uso.
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/messages_en.properties
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ multi.results = See results
multi.finished= Finished game
multi.points = Points
multi.menu =Go to home page

multi.code.invalid = Invalid game code

# -------------------Statements for the apiHome.html file---------------------
api.doc.title=API Documentation
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/messages_es.properties
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ multi.results =Ver resultados
multi.finished= Partida finalizada
multi.points = Puntuaciones
multi.menu = Ir a la página de inicio

multi.code.invalid = Código de partida inválido

# -------------------Statements for the apiHome.html file---------------------
api.doc.title=Documentación de la API
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/messages_fr.properties
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ multi.results=Voir les résultats
multi.finished= Jeu terminé
multi.points = Points
multi.menu =aller à la page d'accueil

multi.code.invalid = Code invalide

# -------------------Statements for the apiHome.html file---------------------
api.doc.title=Documentation de l'API
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/templates/game/multiplayerGame.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<nav th:replace="~{fragments/nav}"></nav>

<div class="container" style="text-align: center">
<span class="alert alert-danger" th:if="${errorKey}" th:text="#{${errorKey}}"></span>
<label id="label-code" class="form-label col-sm-10 text-center mb-3" for="code" th:text="#{multi.label}"></label>
<div class="form-group col-sm-8 mx-auto">
<input type="text" class="form-control w-80 mx-auto" id="code" name="code"
Expand Down
26 changes: 25 additions & 1 deletion src/test/java/com/uniovi/steps/GameStep.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
Expand All @@ -18,12 +19,13 @@
import java.util.List;

public class GameStep extends Wiq_IntegrationTests {

@Autowired
private InsertSampleDataService dataService;
@Autowired
private QuestionGeneratorService questionGeneratorService;

private String code = "";

private Logger log = LoggerFactory.getLogger(GameStep.class);

@When("I press Play")
Expand Down Expand Up @@ -78,4 +80,26 @@ public void iPressStart() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "id", "startBtn", 5);
elems.get(0).click();
}

@And("I save the code")
public void iSaveACode() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "id", "lobbyCode", 5);
Assertions.assertEquals(1, elems.size());
code = elems.get(0).getText();
}

@And("I fill in the saved code")
public void iFillInTheSavedCode() {
List<WebElement> elems = SeleniumUtils.waitLoadElements(driver, By.xpath("//input[contains(@id,'code')]"), 5);
elems.get(0).sendKeys(code);
elems = SeleniumUtils.waitLoadElementsBy(driver, "id", "joinBtn", 5);
elems.get(0).click();
}

@And("I see the multiplayer results")
public void iSeeTheMultiplayerResults() {
List<WebElement> elems = SeleniumUtils.waitLoadElementsBy(driver, "id", "createBtn", 5);
Assertions.assertEquals(1, elems.size());
elems.get(0).click();
}
}
23 changes: 22 additions & 1 deletion src/test/resources/features/MultiplayerGame.feature
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,25 @@ Feature: I play a multiplayer game
When I press Play With Friends
And I create a code
And I press start
Then I should start playing until I see message "multi.finished"
Then I should start playing until I see message "multi.finished"

Scenario: I start a multiplayer game
Given I am not registered or logged in
And I am on the register page
When I fill in the form with valid data username: "userGame" email: "[email protected]" password: "password" password_confirmation: "password"
And I press the register button
And I go to the home page
When I press Play With Friends
And I create a code
And I save the code
Then I logout
Given I am not registered or logged in
And I am on the register page
When I fill in the form with valid data username: "userGame2" email: "[email protected]" password: "password" password_confirmation: "password"
And I press the register button
And I go to the home page
And I press Play With Friends
And I fill in the saved code
And I press start
Then I should start playing until I see message "multi.finished"
And I see the multiplayer results

0 comments on commit 47e4a78

Please sign in to comment.