Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.ezcode.codetest.application.game.dto.request.encounter;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;

@Schema(description = "배틀 요청")
public record BattleRequest(

@Schema(description = "배틀 토큰")
@NotBlank(message = "배틀 토큰은 반드시 입력해야합니다.")
String battleToken

) {
}

Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package org.ezcode.codetest.application.game.dto.request.encounter;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

@Schema(description = "인카운터 선택지 결정 요청")
public record EncounterChoiceRequest(

@Schema(description = "인카운터 토큰")
@NotBlank(message = "인카운터 토큰은 반드시 입력해야합니다.")
String encounterToken,

@NotNull(message = "인카운터를 선택지를 선택해주세요.(true, false)")
@Schema(description = "인카운터 선택지 결정(true:yes, false:no)")
Boolean playerDecision
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,15 @@ public record RandomEncounterSaveRequest(

@NotBlank(message = "설명란은 필수입니다.")
@Schema(description = "저장할 인카운터의 설명 및 묘사")
String encounterText
String encounterText,

@NotBlank(message = "인카운터 선택지 1 입력은 필수입니다.")
@Schema(description = "인카운터 선택지 1 메시지")
String choice1Text,

@NotBlank(message = "인카운터 선택지 2 입력은 필수입니다.")
@Schema(description = "인카운터 선택지 2 메시지")
String choice2Text

) {
public RandomEncounter toRandomEncounter() {
Expand All @@ -33,6 +41,8 @@ public RandomEncounter toRandomEncounter() {
.activated(true)
.name(name)
.encounterText(encounterText)
.choice1Text(choice1Text)
.choice2Text(choice2Text)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ public record EncounterResponse(
@Schema(description = "인카운터 설명 및 묘사")
String encounterText,

@Schema(description = "인카운터 선택지 1")
String choice1Text,

@Schema(description = "인카운터 선택지 2")
String choice2Text,

@Schema(description = "현재 인카운터 활성 여부")
boolean activated

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ public record MatchingBattleResponse(
@Schema(description = "두 플레이어 간 조우했을 시 상황묘사")
String message,

@Schema(description = "적 플레이어의 캐릭터 ID")
Long enemyId
@Schema(description = "적 플레이어의 캐릭터(jwtToken) ID")
String enemyIdToken

) {
public static MatchingBattleResponse of(boolean isEnemyStrongThanMe, String message, Long enemyId) {
public static MatchingBattleResponse of(boolean isEnemyStrongThanMe, String message, String enemyIdToken) {

return new MatchingBattleResponse(isEnemyStrongThanMe, message, enemyId);
return new MatchingBattleResponse(isEnemyStrongThanMe, message, enemyIdToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,34 @@
@Schema(description = "인카운터 매칭 요청에 대한 응답")
public record MatchingEncounterResponse(

@Schema(description = "인카운터 ID")
Long id,
@Schema(description = "인카운터 ID(jwt 토큰)")
String id,

@Schema(description = "인카운터 카테고리")
EncounterCategory encounterCategory,

@Schema(description = "인카운터 이름")
String name,

@Schema(description = "인카운터 선택지 1")
String choice1Text,

@Schema(description = "인카운터 선택지 2")
String choice2Text,

@Schema(description = "인카운터 설명/묘사")
String encounterText

) {
public static MatchingEncounterResponse from(RandomEncounter encounter) {
public static MatchingEncounterResponse from(RandomEncounter encounter, String encounterIdToken) {

return MatchingEncounterResponse.builder()
.encounterCategory(encounter.getEncounterCategory())
.id(encounter.getId())
.id(encounterIdToken)
.name(encounter.getName())
.encounterText(encounter.getEncounterText())
.choice1Text(encounter.getChoice1Text())
.choice2Text(encounter.getChoice2Text())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.List;

import org.ezcode.codetest.application.game.dto.mapper.GameMapper;
import org.ezcode.codetest.application.game.dto.request.encounter.BattleRequest;
import org.ezcode.codetest.application.game.dto.request.encounter.EncounterChoiceRequest;
import org.ezcode.codetest.application.game.dto.request.skill.SkillEquipRequest;
import org.ezcode.codetest.application.game.dto.request.skill.SkillUnEquipRequest;
Expand All @@ -15,6 +16,7 @@
import org.ezcode.codetest.application.game.dto.response.item.ItemResponse;
import org.ezcode.codetest.application.game.dto.response.skill.SkillGamblingResponse;
import org.ezcode.codetest.application.game.dto.response.skill.SkillResponse;
import org.ezcode.codetest.common.security.util.JwtUtil;
import org.ezcode.codetest.domain.game.model.character.GameCharacter;
import org.ezcode.codetest.domain.game.model.encounter.EncounterHistory;
import org.ezcode.codetest.domain.game.model.encounter.EncounterLog;
Expand All @@ -33,6 +35,7 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;

@Service
Expand All @@ -44,6 +47,7 @@ public class GamePlayUseCase {
private final UserDomainService userDomainService;
private final GameEncounterDomainService encounterDomainService;
private final GameMapper gameMapper;
private final JwtUtil jwtUtil;

@Transactional
public void createCharacter(String email) {
Expand Down Expand Up @@ -134,9 +138,14 @@ public SkillGamblingResponse gamblingForSkill(Long userId) {
}

@Transactional
public BattleHistoryResponse battle(Long playerId, Long enemyId) {
public BattleHistoryResponse battle(Long playerId, BattleRequest request) {

Claims claims = jwtUtil.extractClaims(request.battleToken());

Long enemyId = Long.valueOf(claims.getSubject());

GameCharacter playerCharacter = characterService.getGameCharacter(playerId);

GameCharacter enemyCharacter = characterService.getGameCharacter(enemyId);

BattleLog log = encounterDomainService.battle(playerCharacter, enemyCharacter);
Expand All @@ -152,50 +161,56 @@ public BattleHistoryResponse battle(Long playerId, Long enemyId) {
}

@Transactional
public BattleHistoryResponse randomBattle(Long playerId) {
public BattleHistoryResponse randomBattle(Long userId) {

GameCharacter playerCharacter = characterService.getGameCharacter(playerId);
GameCharacter player = characterService.getGameCharacter(userId);

GameCharacter enemyCharacter = encounterDomainService.getRandomEnemyCharacter(playerId);
GameCharacter enemy = encounterDomainService.getRandomEnemyCharacter(userId, player.getId());

BattleLog log = encounterDomainService.battle(playerCharacter, enemyCharacter);
BattleLog log = encounterDomainService.battle(player, enemy);

encounterDomainService.createBattleHistory(playerCharacter, enemyCharacter, log);
encounterDomainService.createBattleHistory(player, enemy, log);

return BattleHistoryResponse.of(
playerCharacter.getName(),
enemyCharacter.getName(),
player.getName(),
enemy.getName(),
log.getMessages(),
log.getPlayerWin()
);
}

@Transactional
public MatchingBattleResponse randomBattleMatching(Long playerId) {
public MatchingBattleResponse randomBattleMatching(Long userId) {

GameCharacter playerCharacter = characterService.getGameCharacter(playerId);
GameCharacter player = characterService.getGameCharacter(userId);

GameCharacter enemyCharacter = encounterDomainService.getRandomEnemyCharacter(playerId);
GameCharacter enemy = encounterDomainService.getRandomEnemyCharacter(userId, player.getId());

boolean checkStrength = encounterDomainService.compareStrength(playerCharacter, enemyCharacter);
boolean checkStrength = encounterDomainService.compareStrength(player, enemy);

String matchMessage = MatchMessageTemplate.random(playerCharacter.getName(), enemyCharacter.getName());
String matchMessage = MatchMessageTemplate.random(player.getName(), enemy.getName());

Long enemyUserId = enemyCharacter.getUser().getId();
Long enemyUserId = enemy.getUser().getId();

return MatchingBattleResponse.of(checkStrength, matchMessage, enemyUserId);
return MatchingBattleResponse.of(checkStrength, matchMessage, jwtUtil.createGameToken(enemyUserId));
}

@Transactional
public MatchingEncounterResponse randomEncounterMatching() {
public MatchingEncounterResponse randomEncounterMatching(Long userId) {

RandomEncounter encounter = encounterDomainService.getRandomEncounter();
GameCharacter playerCharacter = characterService.getGameCharacter(userId);

return MatchingEncounterResponse.from(encounter);
RandomEncounter encounter = encounterDomainService.getRandomEncounter(playerCharacter.getId());

return MatchingEncounterResponse.from(encounter, jwtUtil.createGameToken(encounter.getId()));
}

@Transactional
public EncounterResultResponse encounterChoice(Long userId, Long encounterId, EncounterChoiceRequest request) {
public EncounterResultResponse encounterChoice(Long userId, EncounterChoiceRequest request) {

Claims claims = jwtUtil.extractClaims(request.encounterToken());

Long encounterId = Long.valueOf(claims.getSubject());

GameCharacter player = characterService.getGameCharacter(userId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public SignupResponse signup(SignupRequest signupRequest) {
userDomainService.createUser(newUser);
userDomainService.createUserAuthType(userAuthType);

bearToken = jwtUtil.createToken(
bearToken = jwtUtil.createAccessToken(
newUser.getId(),
newUser.getEmail(),
newUser.getRole(),
Expand All @@ -83,7 +83,7 @@ public SignupResponse signup(SignupRequest signupRequest) {
existUser.modifyPassword(encodedPassword);
log.info("유저 타입 저장 완료 {}", userAuthType);

bearToken = jwtUtil.createToken(
bearToken = jwtUtil.createAccessToken(
existUser.getId(),
existUser.getEmail(),
existUser.getRole(),
Expand Down Expand Up @@ -120,7 +120,7 @@ public SigninResponse signin(@Valid SigninRequest signinRequest) {

log.info("비밀번호 체크 완료");

String bearToken = jwtUtil.createToken(
String bearToken = jwtUtil.createAccessToken(
loginUser.getId(),
loginUser.getEmail(),
loginUser.getRole(),
Expand Down Expand Up @@ -182,7 +182,7 @@ public RefreshTokenResponse refreshToken(String token) {

User user = userDomainService.getUserById(userId);
log.info("유저 도메인서비스에서 유저 아이디로 유저 찾아옴");
String newAccessToken = jwtUtil.createToken(
String newAccessToken = jwtUtil.createAccessToken(
user.getId(),
user.getEmail(),
user.getRole(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
User loginUser = userDomainService.getUserByEmail(customUserDetails.getEmail());
log.info("loginUser: {}", loginUser);

String accessToken = jwtUtil.createToken(
String accessToken = jwtUtil.createAccessToken(
loginUser.getId(),
loginUser.getEmail(),
loginUser.getRole(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
public class JwtUtil {
private static final String BEARER_PREFIX = "Bearer ";
private static final long TOKEN_EXPIRATION_TIME = 60 * 60 * 24 * 7;
private static final long GAME_TOKEN_EXPIRATION_TIME = 60;

@Value("${jwt.secret}")
private String secretKey;
Expand All @@ -39,7 +40,7 @@ public void init() {
/*
토큰 발급
*/
public String createToken(Long userId, String email, UserRole userRole, String username, String nickname, Tier tier) {
public String createAccessToken(Long userId, String email, UserRole userRole, String username, String nickname, Tier tier) {
if (userId == null || email == null || username == null || nickname == null) {
throw new IllegalArgumentException("토큰에 필요한 필수 매개변수가 null입니다.");
}
Expand All @@ -60,6 +61,22 @@ public String createToken(Long userId, String email, UserRole userRole, String u
.compact();
}

public String createGameToken(Long eventId) {

if (eventId == null) {
throw new IllegalArgumentException("토큰에 필요한 필수 매개변수가 null입니다.");
}

Date date = new Date();

return Jwts.builder()
.setSubject(String.valueOf(eventId))
.setExpiration(new Date(date.getTime() + GAME_TOKEN_EXPIRATION_TIME * 1000L))
.setIssuedAt(date)
.signWith(key, signatureAlgorithm)
.compact();
}

/*
토큰 추출
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ public enum GameExceptionCode implements ResponseCode {
RANDOM_ENCOUNTER_NOT_EXISTS(false, HttpStatus.BAD_REQUEST, "해당 랜덤 인카운터가 존재하지 않습니다."),
RANDOM_ENCOUNTER_MATCHING_FAIL(false, HttpStatus.NOT_FOUND, "현재 매칭가능한 인카운터가 존재하지 않습니다."),
ENCOUNTER_CHOICE_ALREADY_EXISTS(false, HttpStatus.BAD_REQUEST, "이미 존재하는 인카운터 선택지입니다."),
ENCOUNTER_CHOICE_NOT_EXISTS(false, HttpStatus.BAD_REQUEST, "해당 인카운터 선택지가 존재하지 않습니다.");
ENCOUNTER_CHOICE_NOT_EXISTS(false, HttpStatus.BAD_REQUEST, "해당 인카운터 선택지가 존재하지 않습니다."),
ENCOUNTER_TOKEN_EXHAUSTED(false, HttpStatus.BAD_REQUEST, "인카운터 매칭 토큰을 전부 소진했습니다. 6 시간 이후 리필됩니다."),
BATTLE_TOKEN_EXHAUSTED(false, HttpStatus.BAD_REQUEST, "배틀 매칭 토큰을 전부 소진했습니다. 6 시간 이후 리필됩니다."),
PLAYER_TOKEN_BUCKET_NOT_EXISTS(false, HttpStatus.NOT_FOUND, "해당 캐릭터의 매칭 토큰 버킷이 존재하지 않습니다.");

private final boolean success;
private final HttpStatus status;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ public void applyIncreaseStats(Map<Stat, Double> stats) {

public void useGoldForGamble() {

if(gold < 50L) throw new GameException(GameExceptionCode.NOT_ENOUGH_GOLD);
if (gold < 50L)
throw new GameException(GameExceptionCode.NOT_ENOUGH_GOLD);

gold -= 50L;
}
Expand All @@ -101,7 +102,11 @@ public void earnGold(long gold) {
this.gold += gold;
}

public void equipItem(ItemType item , String newItem) {
public void loseGold(long gold) {
this.gold = Math.max(0L, this.gold - gold);
}

public void equipItem(ItemType item, String newItem) {

if (item instanceof WeaponType) {
weaponId = newItem;
Expand Down
Loading