Skip to content
Snippets Groups Projects
Commit 4f210580 authored by Snorre Skjellestad Kristiansen's avatar Snorre Skjellestad Kristiansen
Browse files

Merge branch '39-end-turn-in-frontend' into 'main'

Resolve "end-turn in frontend"

Closes #39

See merge request !43
parents ebba5714 f2610b71
No related branches found
No related tags found
1 merge request!43Resolve "end-turn in frontend"
Pipeline #215772 failed
......@@ -8,15 +8,15 @@ export function checkProjectileHit(gameState: any): boolean {
const bufferZone = 5;
// get the current user
const currentUser = gameState.users[gameState.currentTurn][0];
const currentUserStats = gameState.users[gameState.currentTurn][1];
const currentUserPosition = gameState.users[gameState.currentTurn][1].position;
const currentUser = gameState.users[gameState.currentTurn].user;
const currentUserStats = gameState.users[gameState.currentTurn].stats;
const currentUserPosition = gameState.users[gameState.currentTurn].stats.position;
const turretAngle = currentUserStats.turretAngle;
const turretAngleInRadians = (turretAngle * Math.PI) / 180;
// get the other user
const otherUser = gameState.users[gameState.currentTurn === 0 ? 1 : 0][0];
const otherUserStats = gameState.users[gameState.currentTurn === 0 ? 1 : 0][1];
const otherUser = gameState.users[gameState.currentTurn === 0 ? 1 : 0].user;
const otherUserStats = gameState.users[gameState.currentTurn === 0 ? 1 : 0].stats;
const otherUserPosition = otherUserStats.position;
const euclideanDistance = Math.sqrt(
......
......@@ -6,7 +6,7 @@ import { ITerrain } from './ITerrain';
// interface for a game instance
export interface IGame {
users: [User, IStats][];
users: Array<{ user: User; stats: IStats }>;
currentTurn: number;
lobby: ILobby;
gameStatus: boolean;
......@@ -35,7 +35,7 @@ export interface IGame {
setGameStatus(status: boolean): void;
toggleTurn(): void;
getUsers(): [User, IStats][];
getUsers(): Array<{ user: User; stats: IStats }>;
getTerrain(): ITerrain;
getLastActionTimeStamp(): number;
......
......@@ -16,7 +16,7 @@ export class Game implements IGame {
gameStatus: boolean;
gameId: string;
terrain: ITerrain;
users: [User, IStats][]; // left [0] and right [1] user
users: Array<{ user: User; stats: IStats }>; // left [0] and right [1] user
lastActionTimeStamp: number;
constructor(lobby: ILobby) {
......@@ -27,20 +27,22 @@ export class Game implements IGame {
this.lastActionTimeStamp = Date.now();
// insert the lobby users into the game and create a new stats object for each user
this.users = lobby.getUsers().map((user) => [user, new Stats()]);
this.users = lobby.getUsers().map((user) => {
return { user: user, stats: new Stats() };
});
this.users[0][1].setPosition(100);
this.users[1][1].setPosition(900);
this.users[0].stats.setPosition(100);
this.users[1].stats.setPosition(900);
// set the stats for the left and right user
// todo add random tank type
this.users[0][1].setTankType('M107');
this.users[0][1].setTankDirection('left');
this.users[0][1].setIsMirrored(false); // this mirroring can also be done locally.
this.users[0].stats.setTankType('M107');
this.users[0].stats.setTankDirection('left');
this.users[0].stats.setIsMirrored(false); // this mirroring can also be done locally.
this.users[1][1].setTankType('M1A2');
this.users[1][1].setTankDirection('right');
this.users[1][1].setIsMirrored(true);
this.users[1].stats.setTankType('M1A2');
this.users[1].stats.setTankDirection('right');
this.users[1].stats.setIsMirrored(true);
// make random number 0 or 1 to determine who starts
this.currentTurn = Math.round(Math.random());
......@@ -55,7 +57,7 @@ export class Game implements IGame {
return this.terrain;
}
getUsers(): [User, IStats][] {
getUsers(): Array<{ user: User; stats: IStats }> {
return this.users;
}
......@@ -79,14 +81,14 @@ export class Game implements IGame {
if (!this.isValidUserNumber(user)) {
throw new Error('Unable to update score. Invalid userID.');
}
this.users[user][1].setScore(score);
this.users[user].stats.setScore(score);
}
getScore(user: number): number {
if (!this.isValidUserNumber(user)) {
throw new Error('Unable to get score. Invalid userID.');
}
return this.users[user][1].getScore();
return this.users[user].stats.getScore();
}
getWinner(): User {
......@@ -95,9 +97,9 @@ export class Game implements IGame {
throw new Error('Game is not finished');
}
if (this.getScore(0) > this.getScore(1)) {
return this.users[0][0];
return this.users[0].user;
} else {
return this.users[1][0];
return this.users[1].user;
}
}
getLoser(): User {
......@@ -106,9 +108,9 @@ export class Game implements IGame {
throw new Error('Game is not finished');
}
if (this.getScore(0) < this.getScore(1)) {
return this.users[0][0];
return this.users[0].user;
} else {
return this.users[1][0];
return this.users[1].user;
}
}
......@@ -141,7 +143,7 @@ export class Game implements IGame {
if (checkProjectileHit(newGameState)) {
// The user that was hit is the one not having the current turn
const hitUserIndex = newGameState.currentTurn === 0 ? 1 : 0;
const hitUserStats = newGameState.users[hitUserIndex][1];
const hitUserStats = newGameState.users[hitUserIndex].stats;
// Decrease health by 1 of the user that was hit
const newHealth = hitUserStats.health - 1;
......@@ -153,7 +155,7 @@ export class Game implements IGame {
// Calculate new score
const shooterUserIndex = newGameState.currentTurn;
const shooterUserStats = newGameState.users[shooterUserIndex][1];
const shooterUserStats = newGameState.users[shooterUserIndex].stats;
// const currentScore = shooterUserStats.getScore();
// TODO this will not be saved.
......@@ -208,7 +210,7 @@ export class Game implements IGame {
}
getCurrentTurnUser(): User {
return this.users[this.currentTurn][0];
return this.users[this.currentTurn].user;
}
// make json object of the game state (to send to clients)
......
......@@ -252,8 +252,9 @@ public class FindGameController {
public boolean onResult(Net.HttpResponse response) {
HttpStatus status = response.getStatus();
if (status.getStatusCode() == 200 && !response.getResultAsString().isEmpty()) {
CurrentUser.getCurrentUser().setGameId(response.getResultAsString());
String gameIdResponse = response.getResultAsString();
if (status.getStatusCode() == 200 && !gameIdResponse.isEmpty()) {
CurrentUser.getCurrentUser().setGameId(gameIdResponse);
Gdx.app.postRunnable(gameScreenTransition);
return true;
} else if (status.getStatusCode() == 404) {
......
package com.game.tankwars.controller;
import static com.game.tankwars.model.CurrentUser.getCurrentUser;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.net.HttpRequestBuilder;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
......@@ -11,11 +15,24 @@ import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.JsonWriter;
import com.game.tankwars.Callback;
import com.game.tankwars.ConfigReader;
import com.game.tankwars.HTTPRequestHandler;
import com.game.tankwars.TankWarsGame;
import com.game.tankwars.model.Bullet;
import com.game.tankwars.model.GameState;
import com.game.tankwars.model.Tank;
import com.game.tankwars.model.User;
import com.game.tankwars.view.GameHud;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
public class GameController {
private TankWarsGame tankWarsGame;
......@@ -29,10 +46,15 @@ public class GameController {
private boolean moveRightTouched;
private boolean moveLeftTouched;
private boolean aimUpTouched;
private boolean aimDownTouched;
private String gameId;
private boolean gameStatus = false;
private int currentTurn;
private User opponent;
private Tank opponentTank;
public GameController(Tank tank, TankWarsGame tankWarsGame, GameHud hud) {
this.hud = hud;
......@@ -40,6 +62,9 @@ public class GameController {
this.tankWarsGame = tankWarsGame;
this.touchPos = new Vector3();
this.gameId = getCurrentUser().getGameId();
//fetchCurrentTurn();
this.opponentTank = this.tank;
hud.removeTurnContainer();
hud.removeTurnInformationContainer();
}
......@@ -145,12 +170,7 @@ public class GameController {
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
moveRightTouched = false;
}
});
}
public boolean isGameOver() {
......@@ -167,6 +187,49 @@ public class GameController {
//System.out.println(tank.getPower());
//System.out.println(tank.getPosition());
// end turn for player and send data to server
User currentUser = getCurrentUser().getUser();
// Convert the JSON object to a string
GameState gameState = new GameState(gameId, gameStatus, currentTurn);
Array<User> userArray = new Array<>();
userArray.add(currentUser);
userArray.add(opponent);
Array<Tank> tankArray = new Array<>();
tankArray.add(tank);
tankArray.add(opponentTank);
gameState.setUsers(userArray, tankArray);
Json json = new Json();
json.setOutputType(JsonWriter.OutputType.json);
String content = json.toJson(gameState);
System.out.println(content);
currentTurn = currentTurn == 0 ? 1 : 0;
new HTTPRequestHandler(new Callback() {
@Override
public boolean onResult(Net.HttpResponse response) {
if (response.getStatus().getStatusCode() == -1) return false;
System.out.println(response.getStatus().getStatusCode());
System.out.println(response.getResultAsString());
return true;
}
@Override
public void onFailed(Throwable t) {
System.err.println(t);
}
}, new HttpRequestBuilder()
.newRequest()
.url(ConfigReader.getProperty("backend.url") + "/game/" + gameId + "/move")
.method(Net.HttpMethods.POST)
.header("Content-Type", "application/json")
.content(content)
.build()
).sendRequest();
return true;
}
......@@ -177,4 +240,26 @@ public class GameController {
return null;
}
private void fetchCurrentTurn() {
new HTTPRequestHandler(new Callback() {
@Override
public boolean onResult(Net.HttpResponse response) {
if (response.getStatus().getStatusCode() == -1) return false;
opponent = new User();
return true;
}
@Override
public void onFailed(Throwable t) {
System.err.println(t);
}
}, new HttpRequestBuilder()
.newRequest()
.url(ConfigReader.getProperty("backend.url") + "/" + gameId + "/currentTurn")
.method(Net.HttpMethods.POST)
.header("Content-Type", "application/json")
.content(String.format("{username: %s}", "getCurrentUser().getUser().username"))
.build()
).sendRequest();
}
}
package com.game.tankwars.model;
import com.badlogic.gdx.utils.Array;
import java.util.ArrayList;
import java.util.List;
public class GameState {
String gameId;
boolean gameStatus;
Integer currentTurn;
Array<UserTank> users;
public GameState(String gameId, boolean gameStatus, int currentTurn) {
this.gameId = gameId;
this.gameStatus = gameStatus;
this.currentTurn = currentTurn;
this.users = new Array<>();
}
public void setUsers(Array<User> users, Array<Tank> tanks) {
for (int i = 0; i < users.size; i++) {
Tank tank = tanks.get(i);
GameStateTank gameStateTank = new GameStateTank(
tank.getPosition().x,
tank.getCannonAngle(),
tank.getHealth(),
0,
0,
true,
"direction",
"tankType"
);
User user = users.get(i);
this.users.add(new UserTank(user, gameStateTank));
}
}
public String getGameId() {
return gameId;
}
public void setGameId(String gameId) {
this.gameId = gameId;
}
public boolean isGameStatus() {
return gameStatus;
}
public void setGameStatus(boolean gameStatus) {
this.gameStatus = gameStatus;
}
public Integer getCurrentTurn() {
return currentTurn;
}
public void setCurrentTurn(Integer currentTurn) {
this.currentTurn = currentTurn;
}
public Array<UserTank> getUsers() {
return users;
}
public void setUsers(Array<UserTank> users) {
this.users = users;
}
}
class UserTank {
User user;
GameStateTank stats;
public UserTank(User user, GameStateTank tank) {
this.user = user;
this.stats = tank;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public GameStateTank getStats() {
return stats;
}
public void setStats(GameStateTank stats) {
this.stats = stats;
}
}
class GameStateTank {
float position;
float turretAngle;
Integer health;
Integer ammunition;
Integer score;
boolean isMirrored;
String tankDirection;
String tankType;
public GameStateTank(float position, float turretAngle, int health, int ammunition, int score, boolean isMirrored, String tankDirection, String tankType) {
this.position = position;
this.turretAngle = turretAngle;
this.health = health;
this.ammunition = ammunition;
this.score = score;
this.isMirrored = isMirrored;
this.tankDirection = tankDirection;
this.tankType = tankType;
}
public float getPosition() {
return position;
}
public void setPosition(float position) {
this.position = position;
}
public float getTurretAngle() {
return turretAngle;
}
public void setTurretAngle(float turretAngle) {
this.turretAngle = turretAngle;
}
public Integer getHealth() {
return health;
}
public void setHealth(Integer health) {
this.health = health;
}
public Integer getAmmunition() {
return ammunition;
}
public void setAmmunition(Integer ammunition) {
this.ammunition = ammunition;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public boolean isMirrored() {
return isMirrored;
}
public void setMirrored(boolean mirrored) {
isMirrored = mirrored;
}
public String getTankDirection() {
return tankDirection;
}
public void setTankDirection(String tankDirection) {
this.tankDirection = tankDirection;
}
public String getTankType() {
return tankType;
}
public void setTankType(String tankType) {
this.tankType = tankType;
}
}
......@@ -232,4 +232,8 @@ public class Tank {
}
public int getHealth() {
return health;
}
}
package com.game.tankwars.model;
public class User {
int games;
float highscore;
int losses;
public int wins;
public Integer games;
public Float highscore;
public Integer losses;
public Integer wins;
public String username;
public String id;
private String id;
public User() {
// Initialize default values for the fields
games = 0;
highscore = 0.0f;
losses = 0;
wins = 0;
username = null;
id = null;
}
public Integer getGames() {
return games;
}
public void setGames(Integer games) {
this.games = games;
}
public Float getHighscore() {
return highscore;
}
public void setHighscore(Float highscore) {
this.highscore = highscore;
}
public Integer getLosses() {
return losses;
}
public void setLosses(Integer losses) {
this.losses = losses;
}
public Integer getWins() {
return wins;
}
public void setWins(Integer wins) {
this.wins = wins;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
......
......@@ -109,7 +109,7 @@ public class GameScreen implements Screen {
hud = new GameHud(new FitViewport(TankWarsGame.GAMEPORT_WIDTH, TankWarsGame.GAMEPORT_HEIGHT, hudCam), batch);
controller = new GameController(myTank, tankWarsGame, hud);
Gdx.input.setInputProcessor(hud.getStage());
controller.handleHudEvents();
}
@Override
......@@ -189,7 +189,7 @@ public class GameScreen implements Screen {
@Override
public void show() {
Gdx.input.setInputProcessor(hud.getStage());
}
@Override
public void resize(int width, int height) {
......@@ -208,7 +208,7 @@ public class GameScreen implements Screen {
@Override
public void hide() {
Gdx.input.setInputProcessor(null);
}
@Override
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment