Esempio n. 1
0
func (handler *RequestHandler) HandleRequest(request []byte) []byte {
	command, requestJson := splitOnce(request)
	logger.Infof("Got command %s and request json %s", string(command), string(requestJson))
	if handler.sessionGameWrapper == nil {
		if string(command) == api.COMMAND_NEW {
			response, game := newRequest(requestJson)
			handler.sessionGameWrapper = game
			logger.Infof("After new game request, game is now %t nil", (handler.sessionGameWrapper == nil))
			return buildResponse(command, response)
		} else {
			return buildResponse(command, respondUnknownRequest("Need new game request"))
		}
	} else {
		fun, ok := handler.gameRequest[string(command)]
		if ok {
			playerId, requestJsonNoPlayerId := splitOnce(requestJson)
			playerIdInt, err := strconv.Atoi(string(playerId))
			if err != nil {
				logger.Warnf("Not a playerId %s (%s)", playerId, err.Error())
				return buildResponse(command, respondMalformed("playerId not an int"))
			}
			logger.Infof("request for playerId %d", playerIdInt)
			response := fun(requestJsonNoPlayerId, playerIdInt, handler.sessionGameWrapper)
			return buildResponse(command, response)
		} else {
			logger.Warnf("Unknown Command %s", string(command))
			return buildResponse(command, respondUnknownRequest("Unknown command"))
		}
	}
}
Esempio n. 2
0
func (unit *Unit) changeHealth(newHealth int) bool {
	logger.Infof("Unit %s is being attacked with %d health", unit.name, unit.health)
	unit.health = newHealth
	if unit.health > unit.maxHealth {
		logger.Infof("Unit %s cannot go above max health, capping from %d", unit.name, unit.health)
		unit.health = unit.maxHealth
	}
	if unit.health <= 0 {
		logger.Infof("Unit %s cannot go below 0 health, raising from from %d (unit is dead)", unit.name, unit.health)
		unit.health = 0
		return false
	}
	logger.Infof("Unit %s is now at %d health", unit.name, unit.health)
	return true
}
Esempio n. 3
0
func (unit *Unit) receiveDamage(delta int) (bool, error) {
	logger.Debug("%s taking damage", unit.name)
	if delta < 0 {
		message := "Cannot receive a negative amount of damage"
		logger.Infof(message+" (got %d)", delta)
		return true, errors.New(message)
	}
	return unit.changeHealth(unit.health - delta), nil
}
Esempio n. 4
0
func generateResponse(payload interface{}, status int) []byte {
	response, err := json.Marshal(api.ResponseType{Status: status, Payload: payload})
	if err != nil {
		logger.Warnf("Could not generate response: %s", err.Error())
		backupResponse, err := json.Marshal(api.ResponseType{
			Status:  api.STATUS_UNSERIALIZEABLE_RESPONSE,
			Payload: "problem"})
		if err != nil {
			return []byte("Really bad")
		}
		logger.Infof("Generating response with status %d", status)
		logger.Debugf("Full message %s", string(response))
		return backupResponse
	}
	logger.Infof("Generating response with status %d", status)
	logger.Debugf("Full message %s", string(response))
	return response
}
Esempio n. 5
0
func (gh *game_hub) handleNewGame(message string, cconn *clientConnection) {
	ng := newGame{}
	err := json.Unmarshal([]byte(message), &ng)
	if err != nil {
		logger.Warnf("Error unmarshalling json: %s", err)
		return
	}
	ng.cconn = cconn
	logger.Infof("Got new game %s", ng)
	gh.gameRequests <- &ng
}
Esempio n. 6
0
func (p *proxy) sendInitialGameInfo() {
	// I'll send basically this once the server can accept it
	uids := make([]int, len(p.proxyConns))
	for i, v := range p.proxyConns {
		uids[i] = v.info.id
	}
	gi := initialGameInfo{uids, 0}
	message := CommandMarshal("new", gi)
	logger.Infof("%s", message)
	p.server.conn.Write([]byte(message))
}
Esempio n. 7
0
func (world *World) AddUnit(
	location Location, name string, nation nation,
	health int, attacks []*attack, armor *armor, movement *Movement) error {
	logger.Infof("Adding unit at (x: %d, y: %d)", location.x, location.y)
	unitId := world.nextUnitId
	_, okUnitLocation := world.unitMap[location]
	_, okUnitId := world.units[unitId]
	if !(okUnitLocation && okUnitId) {
		newUnit := NewUnit(
			name, unitId, nation, health, attacks, armor, movement)
		world.unitMap[location] = newUnit
		world.units[unitId] = newUnit
		world.nextUnitId += 1
		logger.Infof("Added unit with id %d at (x: %d, y: %d)", unitId, location.x, location.y)
		return nil
	} else {
		logger.Warnf("Failed to add unit with id %d at (x: %d, y: %d)", unitId, location.x, location.y)
		return errors.New("location already occupied")
	}
}
Esempio n. 8
0
func ValidMove(moves int, movementType *Movement, tiles []Terrain, locations []Location) error {
	if len(locations) < 2 {
		message := "Need at least two tiles, a start and an end"
		logger.Infof(message+" (got %d)", len(locations))
		return errors.New(message)
	}
	err := assertAllTilesTouch(locations)
	if err != nil {
		return err
	}
	for _, tile := range tiles {
		moves -= int(movementType.costs[tile])
	}
	logger.Debugf("Had this many moves left %d", moves)
	if moves >= 0 {
		return nil
	} else {
		message := fmt.Sprintf("Too much distance to cover, need %d less", moves)
		logger.Infof(message)
		return errors.New(message)
	}
}
Esempio n. 9
0
func assertAllTilesTouch(locations []Location) error {
	oldLoc := locations[0]
	for _, loc := range locations[1:] {
		distance := (getDistance(loc.x, oldLoc.x) + getDistance(loc.y, oldLoc.y))
		if distance != 1 {
			locations := fmt.Sprintf(
				"(%d, %d) (%d, %d)", loc.x, oldLoc.x, loc.y, oldLoc.y)
			logger.Infof("Two units too far away, distance %d (locations %s)", distance, locations)
			return errors.New(fmt.Sprintf("Two units too far away %s", locations))
		}
		oldLoc = loc
	}
	return nil
}
Esempio n. 10
0
func (p *proxy) handleWebsocket(message []byte, cconn *clientConnection) {
	splitMsg := strings.SplitN(string(message), ":", 2)
	command := splitMsg[0]
	data := splitMsg[1]
	localHandler, ok := p.localHandlers[command]
	if ok {
		localHandler([]byte(data), cconn, p)
		return
	}
	logger.Infof("Proxying message from client: %s", message)
	message = appendClientInfo(command, data, cconn.info)
	err := p.server.conn.Write(message)
	if err != nil {
		logger.Errorf("Error while writing to socket: %s", err)
	}
}
Esempio n. 11
0
func (gh *game_hub) handleDisconnection(message string, cconn *clientConnection) {
	// Find the connection and kill it, cleaning up its game if necessary
	logger.Info("Client Disconnected. Cleaning up...")
	for np, game := range gh.uncommittedGames {
		for i := 0; i < game.currentPlayers; i++ {
			if game.proxy.proxyConns[i].info.id == cconn.info.id {
				game.proxy.removeClientConnection(i)
				game.currentPlayers -= 1
				if game.currentPlayers == 0 {
					logger.Infof("%d player uncommitted game empty. Dropping", np)
					delete(gh.uncommittedGames, np)
				}
				break
			}
		}
	}
}
Esempio n. 12
0
func Main() {
	var port = flag.Int("port", 5269, "path to write the generated json")
	var write_template = flag.Bool("write_templates", false, "whether to write the template response json")
	var template_out_dir = flag.String("template_out_dir", ".", "path to write the generated template json")
	var logpath = flag.String("logpath", "/dev/stdout", "Logging location")
	flag.Parse()

	logger.SetupLoggerHelper(*logpath)

	if *write_template {
		generateTemplates(*template_out_dir)
		os.Exit(0)
	} else {
		logger.Infof("Starting Tactique on port %d!", *port)
		panic(listenForever(*port))
	}
}
Esempio n. 13
0
func loadNations(db *sql.DB) ([]nation, error) {
	query := "select nationType from team;"
	nations := make([]nation, 0)
	rows, err := db.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var nation nation
		err := rows.Scan(&nation)
		if err != nil {
			return nil, err
		}
		nations = append(nations, nation)
	}
	logger.Infof("Nations %s", nations)
	return nations, nil
}
Esempio n. 14
0
func loadTerrains(db *sql.DB) ([]Terrain, error) {
	query := "select cellType from cell;"
	terrains := make([]Terrain, 0)
	rows, err := db.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var terrain Terrain
		err := rows.Scan(&terrain)
		if err != nil {
			return nil, err
		}
		terrains = append(terrains, terrain)
	}
	logger.Infof("Terrain %s", terrains)
	return terrains, nil
}
Esempio n. 15
0
func handleConnection(netConn net.Conn) error {
	conn := connection.NewSocketConn(netConn)
	handler := request_handler.NewRequestHandler()
	for {
		logger.Infof("Handling a connection")
		request, err := conn.Read()
		if err != nil {
			logger.Warnf("Error reading request (%s)", err.Error())
			conn.Close()
			return err
		}
		logger.Debugf("Got request %s", string(request))
		response := handler.HandleRequest(request)
		logger.Debugf("Sent response %s", string(response))
		err = conn.Write(response)
		if err != nil {
			logger.Warnf("Error writing response (%s)", err.Error())
			conn.Close()
			return err
		}
	}
}