backend

package module
v0.0.0-...-57c1e83 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2019 License: MIT Imports: 12 Imported by: 0

README

hakkero-project backend

Package hakkero implements the Hakkero Project's API server.

For more information on usage, see docs.

Contribute

For now, I don't really prefer contributions (yet). Open contributions will happen when basic development is complete.

Still, code reviews are welcomed.

Documentation

Overview

Package backend implements the Hakkero Project's API server. The server will handle all connections from the Hakkero Project's front-end interface, providing needed data through JSON responses and websocket calls. The server consists of 2 parts, the Room Provider and the Match Provider.

Index

Constants

View Source
const Version = "v1.0"

Version returns the version of Hakkero Project.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	PlayerLimit int
	Timeout     time.Duration
}

Config saves important game configurations.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default config.

type Conn

type Conn struct {
	*websocket.Conn
	Recv chan Message // The channel for receiving messages.

	Error error // The error variable, if it is set then the connection no longer is valuable.
	// the dedicated error channel
	ErrChan chan error
}

Conn represents a client connection.

func (*Conn) Close

func (p *Conn) Close() error

Close closes the player connection.

func (*Conn) SendMessage

func (p *Conn) SendMessage(m Message)

SendMessage sends a message to the client, waiting for done.

type Message

type Message struct {
	Type    string   `json:"type"`
	Message Messager `json:"message"`
	// contains filtered or unexported fields
}

Message is the general message type we will use in sending-channels.

type MessageQueueResponse

type MessageQueueResponse struct {
	Accepted bool `json:"accepted"`
	Received time.Time
}

MessageQueueResponse represents an user's answer to the queuing request.

type MessageRequest

type MessageRequest struct {
	IsSkip   bool `json:"skip"` // Whether the player has skipped.
	Received time.Time
	Content  string `json:"content"`
}

MessageRequest is a player's response.

type Messager

type Messager interface {
	IsMessage()
}

Messager is an internal interface, to help type safety with general message-typing.

type OpenSentencer

type OpenSentencer interface {
	OpenSentence() (string, error)
}

OpenSentencer represents an interface where a fetch on an opeing sentence is made.

func StaticOP

func StaticOP() OpenSentencer

StaticOP returns an OpenSentencer that grabs static open sentences.

type PlayerConn

type PlayerConn struct {
	Conn
	Send chan MessageRequest // The channel for sending messages.
}

PlayerConn represents a Player Connection.

func Prepare

func Prepare(conn *websocket.Conn) *PlayerConn

Prepare fires up the PlayerConn for usage

type Queue

type Queue struct {
	Config Config
	Rooms  RoomManager
	OP     OpenSentencer

	Players []*QueueConn
	// contains filtered or unexported fields
}

Queue represents a queue handler.

func NewQueue

func NewQueue(r RoomManager, c Config, op OpenSentencer) *Queue

NewQueue returns a new queue.

func (*Queue) Broadcast

func (q *Queue) Broadcast(audience []*QueueConn, m Message)

Broadcast sends a message to all audiences.

func (*Queue) Enqueue

func (q *Queue) Enqueue(player *QueueConn)

Enqueue adds a player into the queue.

func (*Queue) Play

func (q *Queue) Play(players []*QueueConn) []*QueueConn

Play prompts the players for a game. It returns the players who accepted but not enough for a game.

func (*Queue) ServeHTTP

func (q *Queue) ServeHTTP(w http.ResponseWriter, r *http.Request)

type QueueConn

type QueueConn struct {
	Conn
	User
	Send chan MessageQueueResponse
}

QueueConn represents a connection to the queue.

func Enqueue

func Enqueue(conn *websocket.Conn, username string) *QueueConn

Enqueue fires up the QueueConn for usage

type Room

type Room struct {
	ID        int           `json:"id"`
	Members   []User        `json:"members"`           // The list of all members.
	Status    []Status      `json:"status"`            // The status of each member in the room.
	Sentences []Sentence    `json:"sentences"`         // The list of all sentences.
	Start     time.Time     `json:"start"`             // The time of the start of the game.
	Current   time.Time     `json:"current,omitempty"` // The time when the current turn started.
	Timeout   time.Duration `json:"timeout"`           // The time of each turn.
}

Room represents a playing Room.

func (Room) Ended

func (r Room) Ended() bool

Ended returns whether the game has ended.

func (Room) Index

func (r Room) Index(ID string) (int, error)

Index returns a player's index in the slice. Throws an error if it's not found.

func (Room) NextTurn

func (r Room) NextTurn(last int) (int, bool)

NextTurn returns the next turn and DOES NOT modifies the current status. Returns true if game ended.

func (Room) Winner

func (r Room) Winner() int

Winner returns the winner.

type RoomHandler

type RoomHandler struct {
	Room Room

	TurnTimer *time.Timer // The turn timer.
	// contains filtered or unexported fields
}

RoomHandler is a Handler that serves players' connections to Room server.

func NewRoom

func NewRoom(roomID int, players []User, timeout time.Duration, openSentence string) (h *RoomHandler)

NewRoom creates a new room.

func (*RoomHandler) Broadcast

func (h *RoomHandler) Broadcast(m Message)

Broadcast sends the message to all listening PlayerConns. It pauses until all messages are scheduled to send.

func (*RoomHandler) Play

func (h *RoomHandler) Play(cancel context.CancelFunc)

Play starts up the game.

func (*RoomHandler) ServeHTTP

func (h *RoomHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RoomManager

type RoomManager interface {
	http.Handler
	New(players []User, timeout time.Duration, openSentence string) (id int, err error)
	Get(id int) (*RoomHandler, error)
}

RoomManager is an interface for a RoomManager.

type Rooms

type Rooms struct {
	Rooms []*RoomHandler // As an array, for easy numbering and in-memory management.
	// contains filtered or unexported fields
}

Rooms implement a Room container.

func (*Rooms) Get

func (r *Rooms) Get(id int) (*RoomHandler, error)

Get returns the room with the specified ID.

func (*Rooms) New

func (r *Rooms) New(players []User, timeout time.Duration, openSentence string) (id int, err error)

New creates a new room(handler) and return its id.

func (*Rooms) ServeHTTP

func (r *Rooms) ServeHTTP(w http.ResponseWriter, rq *http.Request)

type Sentence

type Sentence struct {
	Content string `json:"content"`
	Owner   int    `json:"owner"`           // The user index (in the User slice) who wrote this sentence. In the case of a system announcement, this is left empty.
	System  bool   `json:"system,omitempy"` // Indicate that it's a system announcement.
}

Sentence is a sentence written is a room-wide paragraph. The sentence could be an user's sentence, or a system announcement (e.g. An user has left the game).

type Server

type Server struct {
	http.Server
	// contains filtered or unexported fields
}

Server represents a Server.

func NewServer

func NewServer(c Config, op OpenSentencer, r RoomManager) *Server

NewServer returns a new server.

func (*Server) Welcome

func (s *Server) Welcome(w http.ResponseWriter, r *http.Request)

Welcome returns a welcome message.

type Status

type Status int

Status represents a player's status in a room.

const (
	StatusActive Status = iota
	StatusOut
	StatusDc
	StatusTurn
)

Status constants.

func (Status) MarshalJSON

func (s Status) MarshalJSON() ([]byte, error)

MarshalJSON returns the status of the player in JSON. Numbers are not the pretty thing, we send status strings instead.

type User

type User struct {
	ID       string
	Username string
}

User represents an active user. The user can be in a room, or in the placement queue. In this implementation we will NOT save user information into the database, as we allow register-less entrances. Therefore, we would like User to be as simple as possible.

func NewUser

func NewUser(username string) User

NewUser creates a new unique user.

func (*User) MarshalJSON

func (u *User) MarshalJSON() ([]byte, error)

MarshalJSON turns an user into a JSON string. As the user struct should not expose an user's ID, only the Username should be sent.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL