<repo_name>wimvanhaaren/backbaseCodeChallenge<file_sep>/README.md
# Case backend developer for Backbase

**<NAME>**

<EMAIL>

+31 6 44 11 68 35


### Coding Challenge

We are asking you to program a Java web application that runs a game of 6-stone Kalah.

This web application should enable to let 2 human players play the game; there is no AI required. It doesn't need a fancy web interface or front end, it can also be a service endpoint.
 

#### About the game

Each of the two players has six pits in front of him/her. To the right of the six pits, each player has a larger pit, his Kalah or house. At the start of the game, six stones are put In each pit.
 
The player who begins picks up all the stones in any of their own pits, and sows the stones on to the right, one in each of the following pits, including his own Kalah. No stones are put in the opponent's' Kalah. If the players last stone lands in his own Kalah, he gets another turn. This can be repeated any number of times before it's the other player's turn.
 
when the last stone lands in an own empty pit, the player captures this stone and all stones in the opposite pit (the other players' pit) and puts them in his own Kalah.

The game is over as soon as one of the sides run out of stones. The player who still has stones in his/her pits keeps them and puts them in his/hers Kalah. The winner of the game is the player who has the most stones in his Kalah.


### Starting the application

Assuming maven is installed, from the root folder of the project enter the following command:

```
mvn spring-boot:run
```

Then open your web browser and navigate to <http://localhost:8080>
<file_sep>/src/main/java/it/jdev/kalah/domain/model/Game.java
package it.jdev.kalah.domain.model;

import java.util.UUID;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;

@Data
public class Game {

	@JsonProperty(value = "gameId")
	private UUID id;

	private Player player1;
	private Player player2;
	
	private Player currentPlayer;
	
	private boolean gameOver = false;
	private Player winner;

	@JsonIgnore
	private Board board;
	
	public void start() {
		this.id = UUID.randomUUID();
		this.board = new Board();
		this.board.initialize();
		this.currentPlayer = player1;
	}

	public void move(int pit, Player player) {
		checkPlayersTurn(player);
		checkPlayersPit(pit, player);
		
		Pit lastPit = board.moveStones(pit);
		if (!(lastPit instanceof KalahPit)) {
			// switch to other player but not if last stone ended in his kalah pit...
			currentPlayer = (player.equals(player1) ? player2 : player1);
		}
		
		if (gameOver()) {
			this.gameOver = true;
			this.board.moveRemainingStonesToKalahPits();
			andTheWinnerIs();
		}
	}

	private void andTheWinnerIs() {
		int stonesPlayer1 = board.getPits()[6].getNumberOfStones();
		int stonesPlayer2 = board.getPits()[13].getNumberOfStones();
		if (stonesPlayer1 > stonesPlayer2) {
			winner = player1;
		} else {
			winner = player2;
		}
	}

	private void checkPlayersTurn(Player player) {
		if (! currentPlayer.equals(player)) {
			throw new IllegalMoveException("It is not this player's turn.");
		}
	}

	private void checkPlayersPit(int pit, Player player) {
		if ( (player.equals(player1) && pit > 6 ) || 
			 (player.equals(player2) && pit < 7)) {
			throw new IllegalMoveException("Player is not allowed to use other player's pit.");
		}
	}
	
	private boolean gameOver() {
		Pit[] pits = board.getPits();
		int count = 0;
		for (int i=0; i< 6; i++) {
			count += pits[i].getNumberOfStones();
		}
		if (count == 0) {
			return true;
		}
		count = 0;
		for (int i=7; i< 13; i++) {
			count += pits[i].getNumberOfStones();
		}
		if (count == 0) {
			return true;
		}
		return false;
	}

}
<file_sep>/src/main/java/it/jdev/kalah/domain/model/RegularPit.java
package it.jdev.kalah.domain.model;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class RegularPit extends Pit {
	
	public RegularPit() {}
	
	public RegularPit(int stones) {
		super.numberOfStones = stones;
	}

}
<file_sep>/src/main/resources/static/js/kalah.js
angular.module('kalahApp', []).controller('GameController', ['$http', function($http) {

	var game = this;

	game.status = '';
    game.players = [ {id:1, name:'player 1'}, {id:1, name:'player 2'} ];
    game.board = {};
    game.board.pits = [];
 
    game.start = function() {
    	$http.post('/kalah', { 'player1':game.players[0], 'player2':game.players[1]})
    		.then(function successCallback(response) {
    			game.gameId = response.data.gameId;
    			game.status = 'STARTED';
    			game.currentPlayer = response.data.currentPlayer;
    			updateBoard();
    		}, function errorCallback(response) {
    			game.status = 'ERROR';
    		});
    };
    
    var updateBoard = function() {
    	$http.get('/kalah/'+game.gameId+"/board")
    		.then(function successCallback(response) {
    			game.board = response.data;
    			game.status = 'PLAYING';
    		},
    		function errorCallback(res) {
    			game.status = 'ERROR';
    		});
    }
    
    game.move = function(index) {
		$http.post("/kalah/"+game.gameId+"/board/"+index, game.currentPlayer)
		.then(function successCallback(response) {
    	    game.currentPlayer = response.data.currentPlayer;
    	    if (response.data.gameOver === true) {
    	    	game.status = 'AND THE WINNER IS ' + response.data.winner.name + '!!!';
    	    	alert('We have a winner!\nCongratulations ' + response.data.winner.name);
    	    } else {
    	    	updateBoard();
    	    }
		}, function errorCallback(response) {
			game.status = 'ERROR';
		});
    }
 
  }]);
<file_sep>/src/test/java/it/jdev/kalah/GameSetupTest.java
package it.jdev.kalah;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import it.jdev.kalah.api.GameController;
import it.jdev.kalah.domain.model.Board;
import it.jdev.kalah.domain.model.Game;
import it.jdev.kalah.domain.model.KalahPit;
import it.jdev.kalah.domain.model.Pit;
import it.jdev.kalah.domain.model.Player;
import it.jdev.kalah.domain.model.RegularPit;

@RunWith(SpringRunner.class)
@WebMvcTest(GameController.class)
public class GameSetupTest {
	
	@Autowired
	private MockMvc mockMvc;
	
	@Test
	public void newGame() throws Exception {
		Game game = startNewGame();
		assertNotNull(game.getId());
	}

	private Game startNewGame() throws JsonProcessingException, Exception, UnsupportedEncodingException, IOException,
			JsonParseException, JsonMappingException {
		Game game = new Game();
		game.setPlayer1(new Player(1, "David"));
		game.setPlayer2(new Player(2, "Neal"));
		
		ObjectMapper objectMapper = new ObjectMapper();
		String gameJson = objectMapper.writeValueAsString(game);
		MvcResult mvcResult = this.mockMvc
				.perform(post("/kalah").contentType(MediaType.APPLICATION_JSON_UTF8).content(gameJson))
				.andDo(print())
				.andExpect(status().isCreated())
				.andReturn();

		String response = mvcResult.getResponse().getContentAsString();
		Game result = objectMapper.readValue(response, Game.class);
		return result;
	}
	
	@Test
	public void getBoard() throws Exception {
		Game game = startNewGame();
		Board board = getBoard(game.getId());
		assertNotNull(board);
		Pit[] pits = board.getPits();
		assertEquals(14, pits.length);
		for (int i=0; i<14; i++) {
			Pit p = pits[i];
			if (i == 6 || i == 13) {
				assertTrue(p instanceof KalahPit);
				assertEquals(0, p.getNumberOfStones());				
			} else {
				assertTrue(p instanceof RegularPit);
				assertEquals(6, p.getNumberOfStones());
			}
		}
	}

	private Board getBoard(UUID gameId) throws Exception {
		MvcResult mvcResult = this.mockMvc.perform(get("/kalah/" + gameId + "/board")
				.accept(MediaType.APPLICATION_JSON_UTF8))
				.andExpect(status().isOk())
				.andDo(print())
				.andReturn();
		String response = mvcResult.getResponse().getContentAsString();
		ObjectMapper objectMapper = new ObjectMapper();
		Board board = objectMapper.readValue(response, Board.class);
		return board;
	}

}
<file_sep>/src/main/java/it/jdev/kalah/domain/model/KalahPit.java
package it.jdev.kalah.domain.model;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class KalahPit extends Pit {
	
	public KalahPit() {}

}
