Esempio n. 1
0
func forfeit(w http.ResponseWriter, r *http.Request) {
	if r.Body == nil {
		w.WriteHeader(400)
		results := game.Results{Error: "Game ID and Player ID is required."}
		jsonResults, err := json.Marshal(results)
		if err != nil {
			handleError(w, err.Error())
			return
		}
		w.Write(jsonResults)
		return
	}

	body, err := ioutil.ReadAll(r.Body)

	if err != nil {
		handleError(w, err.Error())
		return
	}

	defer r.Body.Close()

	var forfeiter game.Turn
	json.Unmarshal(body, &forfeiter)

	game.Log("Player " + string(forfeiter.PlayerId) + " forfeited.")

	delete(gameMap, forfeiter.GameId)
}
Esempio n. 2
0
func generateGameId() string {
	u4, err := uuid.NewV4()
	if err != nil {
		log.Println("error:", err.Error())
		return ""
	}
	uuid := u4.String()
	game.Log("Generating game ID: " + uuid)
	return uuid
}
Esempio n. 3
0
func turnReceived(w http.ResponseWriter, r *http.Request) {
	if r.Body == nil {
		return
	}

	body, err := ioutil.ReadAll(r.Body)

	if err != nil {
		handleError(w, err.Error())
		return
	}

	defer r.Body.Close()

	var currentTurn game.Turn
	err = json.Unmarshal(body, &currentTurn)

	if err != nil {
		handleError(w, err.Error())
		return
	}

	currentGame, ok := gameMap[currentTurn.GameId]

	var results game.Results
	if ok == false {
		results = game.Results{Error: "Game does not exist"}
	} else {
		game.Log(currentTurn)
		results = currentGame.HandleTurn(currentTurn)
		if results.Winner > 0 {
			delete(gameMap, currentTurn.GameId)
		} else {
			gameMap[currentTurn.GameId] = currentGame
		}
	}

	jsonResults, err := json.Marshal(results)

	if err != nil {
		handleError(w, err.Error())
		return
	}

	w.Write(jsonResults)
}
Esempio n. 4
0
func main() {
	initLogging()

	newGame := game.NewGame()
	newGame.GameId = generateGameId()
	newGame.PlayerX = 10000
	newGame.TurnId = newGame.PlayerX

	gameMap[newGame.GameId] = newGame
	waitingGames <- newGame.GameId

	game.Log("Starting the server on port 80")

	http.Handle("/", httpgzip.NewHandler(http.FileServer(http.Dir("./static/"))))
	http.HandleFunc("/tictactoe", index)
	http.HandleFunc("/tictactoe/register", newRegistration)
	http.HandleFunc("/tictactoe/forfeit", forfeit)
	http.HandleFunc("/tictactoe/turn", turnReceived)
	http.ListenAndServe(":80", nil)
}