Documentation
¶
Overview ¶
Author: Josh Hoak aka Kashomon
Author: Josh Hoak aka Kashomon
Author: Josh Hoak aka Kashomon
Index ¶
- Constants
- Variables
- func CheckDBConnection(path string) bool
- func CheckInGame(w http.ResponseWriter, r *http.Request)
- func CheckNullInTable(table string)
- func CheckUserName(w http.ResponseWriter, r *http.Request)
- func CheckUserNameInDb(username string) bool
- func Cleanup()
- func CompressDatabase()
- func ComputeRating(name string, gameID int, gameType string, result float64)
- func CreateDirIfNotExist(dir string)
- func DbSetup(backup string) bool
- func EngineSearchTimeRaw(fen string, engine *uci.Engine, t time.Duration) (bool, string)
- func EnterChess(ws *websocket.Conn)
- func EnterGuest(w http.ResponseWriter, r *http.Request)
- func EnterLobby(ws *websocket.Conn)
- func ExportDatabase(isTemplate bool)
- func FetchLogs(w http.ResponseWriter, r *http.Request)
- func GetAllClosedCommits()
- func GetCountry(username string) string
- func GetDb() *sql.DB
- func GetGameID(name string) (int, bool)
- func GetPlayerData(w http.ResponseWriter, r *http.Request)
- func GetRating(name string) (errMessage string, bullet, blitz, standard int16, correspondence int16)
- func GetRatingAndRD(name string) (errRate string, ...)
- func HasTimeElapsed(targetTime string, timeCompare int, timeFormat string, useHour bool) (bool, int)
- func InitForum()
- func InitGame(gameID int, name string, fighter string)
- func IsAdmin(username string) bool
- func IsDirectory(path string) bool
- func IsEnvironmentAppVeyor() bool
- func IsEnvironmentTravis() bool
- func IsFileExist(path string) bool
- func IsFloatEqual(a, b float64) bool
- func IsMod(username string) bool
- func OneTimeParseTemplates()
- func ParseTemplates(templateArgs interface{}, writer http.ResponseWriter, outputPath string, ...)
- func PrintMemoryStats()
- func ProcessLogin(w http.ResponseWriter, r *http.Request)
- func ProcessRegister(w http.ResponseWriter, r *http.Request)
- func Quit(engine *uci.Engine)
- func RandomString() string
- func ReadFile(path string) (string, string)
- func ReadOneLine(path string) string
- func RecurseDirectory(searchDir string, fp func(string), pattern string)
- func RemoveOldActivate(days string)
- func RemoveOldForgot(days string)
- func RemoveOldGames(days string)
- func ReplaceString(target, desired, source string) bool
- func ResizeImages()
- func ResumeGame(w http.ResponseWriter, r *http.Request)
- func Round(f float64) float64
- func RoundPlus(f float64, places int) float64
- func SetDb(dataDb *sql.DB)
- func SetupMySqlIni()
- func SetupSecretDir()
- func Show404Page(w http.ResponseWriter, r *http.Request)
- func StartCron()
- func StartEngine(args []string) *uci.Engine
- func StartStockfishBot()
- func TimeOutHttp(seconds time.Duration) http.Client
- func UpdateCaptcha(w http.ResponseWriter, r *http.Request)
- func UpdateHighScore()
- func ValidateCredentials(w http.ResponseWriter, r *http.Request) bool
- func ValidateJSONFiles()
- type AcceptMatch
- type ChatInfo
- type ChessGame
- type Connection
- type DatabaseInfo
- type GameMove
- type GoGame
- type IPLocation
- type MessageType
- type Nrating
- type Observers
- type Rating
- type RecentPlayer
- type ScoreBoard
- type SeekMatch
- type SpectateGame
- type TopRating
- type UserInfo
Constants ¶
const ( White = iota Black )
Variables ¶
var ( USER_CONFIG_PATH = "secret/config.txt" ROOT_CONFIG_PATH = "secret/root.txt" )
var ( // Constrains the volatility. Typically set between 0.3 and 1.2. Often // referred to as the 'system' constant. DefaultTau = 0.3 DefaultRat = 1500.0 // Default starting rating DefaultDev = 350.0 // Default starting deviation DefaultVol = 0.06 // Default starting volatility )
Overrideable Defaults
var Active = struct { sync.RWMutex Clients map[string]*websocket.Conn }{Clients: make(map[string]*websocket.Conn)}
active users connected to chess room socket
var All = struct { sync.RWMutex Games map[int]*ChessGame }{Games: make(map[int]*ChessGame)}
active and running games on the server
var Chat = struct { sync.RWMutex Lobby map[string]*websocket.Conn }{Lobby: make(map[string]*websocket.Conn)}
active users connected to lobby socket
var DeviceManager = make(map[string]string)
var LeaderBoard = struct { sync.RWMutex Scores ScoreBoard }{}
var Pending = struct { sync.RWMutex Matches map[int]*SeekMatch }{Matches: make(map[int]*SeekMatch)}
pending matches in the lobby waiting for someone to accept
var PrivateChat = make(map[string]string)
used for quick access to identify two people who are private chatting and playing a game against each other
var SessionManager = make(map[string]string)
global SessionManager["username"] = sessionID
Functions ¶
func CheckDBConnection ¶
checks if database connection is open, returns true if MySQL is running the parameter path is where the text file is located
func CheckInGame ¶
func CheckInGame(w http.ResponseWriter, r *http.Request)
checks if a player is in a game
func CheckNullInTable ¶
func CheckNullInTable(table string)
check if there are any null fields in a table
func CheckUserName ¶
func CheckUserName(w http.ResponseWriter, r *http.Request)
func CheckUserNameInDb ¶
returns true if username already exists, this function assumes database is already pinged
func ComputeRating ¶
computes the rating for one player and the other player and updates the database and notifies both players, result can be white, black or draw
func CreateDirIfNotExist ¶
func CreateDirIfNotExist(dir string)
func EngineSearchTimeRaw ¶
func EnterGuest ¶
func EnterGuest(w http.ResponseWriter, r *http.Request)
func ExportDatabase ¶
func ExportDatabase(isTemplate bool)
exports database(without Grandmaster games) to an .sql file as a hot backup @param isTemplate If true then export template database
func GetAllClosedCommits ¶
func GetAllClosedCommits()
func GetCountry ¶
Fetches country from database for a given player every time they login If country is null then it returns blank string which should be checked
func GetGameID ¶
gets the game ID that a player is currently playing the bool indicates whether the player is currently playing a game
func GetPlayerData ¶
func GetPlayerData(w http.ResponseWriter, r *http.Request)
displays player data when mouse hovers over
func GetRating ¶
func GetRating(name string) (errMessage string, bullet, blitz, standard int16, correspondence int16)
fetches players bullet, blitz and standard rating
func GetRatingAndRD ¶
func GetRatingAndRD(name string) (errRate string, bullet, blitz, standard, correspondence, bulletRD, blitzRD, standardRD float64, correspondenceRD float64)
fetches players bullet, blitz and standard rating and RD
func HasTimeElapsed ¶
func HasTimeElapsed(targetTime string, timeCompare int, timeFormat string, useHour bool) (bool, int)
Returns true if the number of seconds is greater then the difference of targetTime - (this moment) Also returns time difference of targetTime and now, returns zero could mean there was an error timeFormat is the time format targetTime is in useHour is true to get difference in hours for rating history and false for forum spam control timeCompare can be in hours or seconds depending on useHour
func InitForum ¶
func InitForum()
Checks forum to see if initial forum rows are missing, if they are then initialize them
func InitGame ¶
intitalize all pawns to false as they have not moved yet, and also initialize all en passent to false
func IsDirectory ¶
return trues if path is a directory, errors are explicitly not logged
func IsEnvironmentAppVeyor ¶
func IsEnvironmentAppVeyor() bool
Returns true if the environment is in App Veyor
func IsEnvironmentTravis ¶
func IsEnvironmentTravis() bool
Returns true if the environment is in Travis
func IsFileExist ¶
Returns true if a given file exist in the path
func IsFloatEqual ¶
Returns true if floats are equal withing the tolerance level set by EPSILON
func OneTimeParseTemplates ¶
func OneTimeParseTemplates()
Goes through all templates and parses then on startup
func ParseTemplates ¶
func ParseTemplates(templateArgs interface{}, writer http.ResponseWriter, outputPath string,
templatePaths ...string)
@templateArgs Template arguments that will be parsed @writer http.ResponseWriter or nil, if nil a file will be created and served @outputPath the output file of the parsed template @templatePath relative location to template that is to be parsed
func ProcessLogin ¶
func ProcessLogin(w http.ResponseWriter, r *http.Request)
process user input when signing in
func ProcessRegister ¶
func ProcessRegister(w http.ResponseWriter, r *http.Request)
processes the users input when signing up
func RandomString ¶
func RandomString() string
func ReadFile ¶
the parameter path is where the text file is located containing the database connection info if password is blank when encoded it will be blank when decoded
func ReadOneLine ¶
Reads one line in the file and returns its contents, usually used to get activiation tokens for services
func RecurseDirectory ¶
Recursives through directory and calls the function pointer fp on each file Pattern is the file pattern to apply the function to for example *json would apply the fp on all files recursively in the directory
func RemoveOldActivate ¶
func RemoveOldActivate(days string)
Remove old entries in activate table in database
func RemoveOldForgot ¶
func RemoveOldForgot(days string)
Remove old entries in the forgot table in the database If the entry is older then the days parameter then it will be deleted
func RemoveOldGames ¶
func RemoveOldGames(days string)
remove games older then 180 days to clean up profile page, activated only on server startup
func ReplaceString ¶
Replaces target string in file with desired string in the file path Returns false if there was an error in the operation
func ResizeImages ¶
func ResizeImages()
check if images need to be resized, if they do then resize them
func ResumeGame ¶
func ResumeGame(w http.ResponseWriter, r *http.Request)
func SetupSecretDir ¶
func SetupSecretDir()
For brand new installations this will setup credentials in the secret directory
func Show404Page ¶
func Show404Page(w http.ResponseWriter, r *http.Request)
func StartEngine ¶
Run starts an engine executable, with the given arguments. Returns the engine, make sure to call Quit() on the engine to clean up
func StartStockfishBot ¶
func StartStockfishBot()
func TimeOutHttp ¶
returns a http client to time out requests that take too long @seconds number of seconds for the request before it times out
func UpdateCaptcha ¶
func UpdateCaptcha(w http.ResponseWriter, r *http.Request)
func UpdateHighScore ¶
func UpdateHighScore()
fetches top ten bullet, blitz and standard ratings as well as the most recent 10 registered players
func ValidateCredentials ¶
func ValidateCredentials(w http.ResponseWriter, r *http.Request) bool
returns true if user is an registered user that is logged in
Types ¶
type AcceptMatch ¶
used to store two player's name for redirecting on the front end in JavaScript
type ChessGame ¶
type ChessGame struct {
Type string
ID int
WhitePlayer string
BlackPlayer string
WhiteRating int16
BlackRating int16
GameMoves []GameMove //stores chess move for games
Status string //white to move, black to move, white won, black won, or draw
Result int8 //0 means black won, 1 means white won and 2 means draw. 2 is used intead of 0.5 as database type is int
GameType string //bullet, blitz, standard, correspondence
TimeControl int
BlackMinutes int
BlackSeconds int
WhiteMinutes int
WhiteSeconds int
StartMinutes int // used to keep track of start time for correspondence
PendingDraw bool //used to keep track if a player has offered a draw
Rated string //Yes if the game is rated, No if the game is unrated
Spectate bool
CountryWhite string
CountryBlack string
Validator *chess.Game
// contains filtered or unexported fields
}
stores chess game information
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
used to identify who the socket connection is
func (*Connection) ChessConnect ¶
func (c *Connection) ChessConnect()
Manages web sockets for the game room
func (*Connection) LobbyConnect ¶
func (c *Connection) LobbyConnect()
type DatabaseInfo ¶
func (*DatabaseInfo) ReadFile ¶
func (databaseInfo *DatabaseInfo) ReadFile(path string)
type GameMove ¶
type GameMove struct {
Type string
ID int
S string // Source move
T string // Destination move
P string // Promotion piece
Fen string // FEN string of the board with the move played
}
source and destination of piece moves
type GoGame ¶
type GoGame struct {
ID int
White string
Black string
GameType string
WhiteRating int
BlackRating int
WhiteMinutes int
WhiteSeconds int
BlackMinutes int
BlackSeconds int
TimeControl int
Moves string //json this back to a struct of Moves
Total int
Result int //2 means draw
Status string
Date string
Time string
Rated string
CountryWhite string
CountryBlack string
}
an individual game
type IPLocation ¶
type MessageType ¶
stores information of players that are online used to identify what kind of message it for incoming socket messages for JSON and check authentication
type Rating ¶
type Rating struct {
Rating float64 // Player's rating. Usually starts off at 1500.
Deviation float64 // Confidence/uncertainty in a player's rating
Volatility float64 // Measures erratic performances
}
Represents a player's rating and the confidence in a player's rating.
func CalculateRating ¶
func DefaultRating ¶
func DefaultRating() *Rating
Creates a default Rating using:
Rating = DefaultRat Deviation = DefaultDev Volatility = DefaultVol
func (*Rating) FromGlicko2 ¶
Creates a new rating, converted from Glicko2 scaling to Glicko1 scaling. This assumes the starting rating value is 1500.
func (*Rating) MostlyEquals ¶
Ensure that some other Rating is equal to this rating, given some epsilon. In other words, find the error between this rating's values and the other rating's values and make sure it's less than epsilon in absolute value.
type RecentPlayer ¶
type ScoreBoard ¶
type ScoreBoard struct {
Bullet [total]TopRating
Blitz [total]TopRating
Standard [total]TopRating
Correspondence [total]TopRating
Recent [total]RecentPlayer //ten most recently registered players
}
type SeekMatch ¶
type SeekMatch struct {
Type string
Name string
Opponent string
Rating int16 //player own rating
GameType string //bullet, blitz, standard, correspondence
MatchID int
TimeControl int
MinRating int16
MaxRating int16
Rated string
IsBot bool
}
sends out seek matches real time in the lobby
type SpectateGame ¶
used to unmarshall game ID that is being observed by player(Name)