diff --git a/cache/cache.go b/cache/cache.go index 0ef3e3d..f1016d6 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -1,28 +1,17 @@ package cache import ( - "fmt" "runtime" "time" - - uuid "github.com/satori/go.uuid" ) -// Expired returns true if the item has expired -func (item Item) Expired() bool { - if item.Expiration == 0 { - return false - } - return time.Now().UnixNano() > item.Expiration -} - // NewCache returns a simple in-memory cache func NewCache(defaultExp, cleanupInterval time.Duration) *Cache { - items := make(map[uuid.UUID]Item) + items := make(map[string]Item) return newCacheWithJanitor(defaultExp, cleanupInterval, items) } -func newCacheWithJanitor(defaultExp, cleanupInterval time.Duration, items map[uuid.UUID]Item) *Cache { +func newCacheWithJanitor(defaultExp, cleanupInterval time.Duration, items map[string]Item) *Cache { cache := newCache(defaultExp, items) Cache := &Cache{cache} if cleanupInterval > 0 { @@ -32,7 +21,7 @@ func newCacheWithJanitor(defaultExp, cleanupInterval time.Duration, items map[uu return Cache } -func newCache(de time.Duration, m map[uuid.UUID]Item) *cache { +func newCache(de time.Duration, m map[string]Item) *cache { if de == 0 { de = -1 } @@ -46,7 +35,7 @@ func newCache(de time.Duration, m map[uuid.UUID]Item) *cache { // Add an item to the cache, replacing any existing item. If the duration is 0 // (DefaultExpiration), the cache's default expiration time is used. If it is -1 // (NoExpiration), the item never expires. -func (c *cache) Set(k uuid.UUID, x interface{}, d time.Duration) { +func (c *cache) Set(k string, x Game, d time.Duration) { // "Inlining" of set var e int64 if d == DefaultExpiration { @@ -57,7 +46,7 @@ func (c *cache) Set(k uuid.UUID, x interface{}, d time.Duration) { } c.mu.Lock() c.items[k] = Item{ - Object: x, + Game: x, Expiration: e, } // TODO: Calls to mu.Unlock are currently not deferred because defer @@ -65,7 +54,7 @@ func (c *cache) Set(k uuid.UUID, x interface{}, d time.Duration) { c.mu.Unlock() } -func (c *cache) set(k uuid.UUID, x interface{}, d time.Duration) { +func (c *cache) set(k string, x Game, d time.Duration) { var e int64 if d == DefaultExpiration { d = c.defaultExpiration @@ -74,159 +63,53 @@ func (c *cache) set(k uuid.UUID, x interface{}, d time.Duration) { e = time.Now().Add(d).UnixNano() } c.items[k] = Item{ - Object: x, + Game: x, Expiration: e, } } // Add an item to the cache, replacing any existing item, using the default // expiration. -func (c *cache) SetDefault(k uuid.UUID, x interface{}) { +func (c *cache) SetDefault(k string, x Game) { c.Set(k, x, DefaultExpiration) } -// Add an item to the cache only if an item doesn't already exist for the given -// key, or if the existing item has expired. Returns an error otherwise. -func (c *cache) Add(k uuid.UUID, x interface{}, d time.Duration) error { - c.mu.Lock() - _, found := c.get(k) - if found { - c.mu.Unlock() - return fmt.Errorf("Item %s already exists", k) - } - c.set(k, x, d) - c.mu.Unlock() - return nil -} - -// Set a new value for the cache key only if it already exists, and the existing -// item hasn't expired. Returns an error otherwise. -func (c *cache) Replace(k uuid.UUID, x interface{}, d time.Duration) error { - c.mu.Lock() - _, found := c.get(k) - if !found { - c.mu.Unlock() - return fmt.Errorf("Item %s doesn't exist", k) - } - c.set(k, x, d) - c.mu.Unlock() - return nil -} - // Get an item from the cache. Returns the item or nil, and a bool indicating // whether the key was found. -func (c *cache) Get(k uuid.UUID) (interface{}, bool) { - c.mu.RLock() - // "Inlining" of get and Expired - item, found := c.items[k] - if !found { - c.mu.RUnlock() - return nil, false - } - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - c.mu.RUnlock() - return nil, false - } - } - c.mu.RUnlock() - return item.Object, true -} - -// GetWithExpiration returns an item and its expiration time from the cache. -// It returns the item or nil, the expiration time if one is set (if the item -// never expires a zero value for time.Time is returned), and a bool indicating -// whether the key was found. -func (c *cache) GetWithExpiration(k uuid.UUID) (interface{}, time.Time, bool) { +func (c *cache) Get(k string) (Game, bool) { c.mu.RLock() // "Inlining" of get and Expired item, found := c.items[k] if !found { c.mu.RUnlock() - return nil, time.Time{}, false + return item.Game, false } - if item.Expiration > 0 { if time.Now().UnixNano() > item.Expiration { c.mu.RUnlock() - return nil, time.Time{}, false + return item.Game, false } - - // Return the item and the expiration time - c.mu.RUnlock() - return item.Object, time.Unix(0, item.Expiration), true } - - // If expiration <= 0 (i.e. no expiration time set) then return the item - // and a zeroed time.Time c.mu.RUnlock() - return item.Object, time.Time{}, true -} - -func (c *cache) get(k uuid.UUID) (interface{}, bool) { - item, found := c.items[k] - if !found { - return nil, false - } - // "Inlining" of Expired - if item.Expiration > 0 { - if time.Now().UnixNano() > item.Expiration { - return nil, false - } - } - return item.Object, true -} - -func (c *cache) delete(k uuid.UUID) (interface{}, bool) { - if c.onEvicted != nil { - if v, found := c.items[k]; found { - delete(c.items, k) - return v.Object, true - } - } - delete(c.items, k) - return nil, false + return item.Game, true } type keyAndValue struct { - key uuid.UUID + key string value interface{} } // Delete all expired items from the cache. func (c *cache) DeleteExpired() { - var evictedItems []keyAndValue now := time.Now().UnixNano() c.mu.Lock() for k, v := range c.items { // "Inlining" of expired if v.Expiration > 0 && now > v.Expiration { - ov, evicted := c.delete(k) - if evicted { - evictedItems = append(evictedItems, keyAndValue{k, ov}) - } + delete(c.items, k) } } c.mu.Unlock() - for _, v := range evictedItems { - c.onEvicted(v.key, v.value) - } -} - -// Sets an (optional) function that is called with the key and value when an -// item is evicted from the cache. (Including when it is deleted manually, but -// not when it is overwritten.) Set to nil to disable. -func (c *cache) OnEvicted(f func(uuid.UUID, interface{})) { - c.mu.Lock() - c.onEvicted = f - c.mu.Unlock() -} - -// Delete all items from the cache. -func (c *cache) Flush() { - c.mu.Lock() - c.items = map[uuid.UUID]Item{} - c.mu.Unlock() } type janitor struct { diff --git a/cache/structs.go b/cache/structs.go index 2b693d9..565a307 100644 --- a/cache/structs.go +++ b/cache/structs.go @@ -9,10 +9,39 @@ import ( // Item for caching type Item struct { - Object interface{} + Game Game Expiration int64 } +// Game object for binding with JSON POST body +type Game struct { + ID string `json:"id"` + Player1 *Player `json:"player1"` + Player2 *Player `json:"player2"` + Turn *uuid.UUID `json:"turn,omitempty"` + Draw *bool `json:"draw,omitempty"` + Winner *uuid.UUID `json:"winner,omitempty"` + Matrix Matrix `json:"matrix"` + Tally []*Tally `json:"tally,omitempty"` + NextGame string `json:"next_game"` + PrevGame string `json:"previous_game"` +} + +// Tally is a log of games won +type Tally struct { + Player Player `json:"player"` + Matrix Matrix `json:"matrix"` +} + +// Matrix is the game board and player uuids +type Matrix [9]*uuid.UUID + +// Player object for binding with JSON POST body +type Player struct { + UUID uuid.UUID `json:"id"` + Name string `json:"name,omitempty"` +} + // Cache is a simple in-memory cache for storing things type Cache struct { *cache @@ -20,9 +49,9 @@ type Cache struct { type cache struct { defaultExpiration time.Duration - items map[uuid.UUID]Item + items map[string]Item mu sync.RWMutex - onEvicted func(uuid.UUID, interface{}) + onEvicted func(string, interface{}) janitor *janitor } diff --git a/dist/bundle.js b/dist/bundle.js index 8a664a1..c50e020 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -1329,6 +1329,17 @@ eval("/* WEBPACK VAR INJECTION */(function(Buffer) {var asn1 = __webpack_require /***/ }), +/***/ "./node_modules/path-browserify/index.js": +/*!***********************************************!*\ + !*** ./node_modules/path-browserify/index.js ***! + \***********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +eval("/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nvar splitPathRe =\n /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\nvar splitPath = function(filename) {\n return splitPathRe.exec(filename).slice(1);\n};\n\n// path.resolve([from ...], to)\n// posix version\nexports.resolve = function() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : process.cwd();\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n};\n\n// path.normalize(path)\n// posix version\nexports.normalize = function(path) {\n var isAbsolute = exports.isAbsolute(path),\n trailingSlash = substr(path, -1) === '/';\n\n // Normalize the path\n path = normalizeArray(filter(path.split('/'), function(p) {\n return !!p;\n }), !isAbsolute).join('/');\n\n if (!path && !isAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n\n return (isAbsolute ? '/' : '') + path;\n};\n\n// posix version\nexports.isAbsolute = function(path) {\n return path.charAt(0) === '/';\n};\n\n// posix version\nexports.join = function() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return exports.normalize(filter(paths, function(p, index) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }).join('/'));\n};\n\n\n// path.relative(from, to)\n// posix version\nexports.relative = function(from, to) {\n from = exports.resolve(from).substr(1);\n to = exports.resolve(to).substr(1);\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var fromParts = trim(from.split('/'));\n var toParts = trim(to.split('/'));\n\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n};\n\nexports.sep = '/';\nexports.delimiter = ':';\n\nexports.dirname = function(path) {\n var result = splitPath(path),\n root = result[0],\n dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.substr(0, dir.length - 1);\n }\n\n return root + dir;\n};\n\n\nexports.basename = function(path, ext) {\n var f = splitPath(path)[2];\n // TODO: make this comparison case-insensitive on windows?\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n};\n\n\nexports.extname = function(path) {\n return splitPath(path)[3];\n};\n\nfunction filter (xs, f) {\n if (xs.filter) return xs.filter(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n if (f(xs[i], i, xs)) res.push(xs[i]);\n }\n return res;\n}\n\n// String.prototype.substr - negative index don't work in IE8\nvar substr = 'ab'.substr(-1) === 'b'\n ? function (str, start, len) { return str.substr(start, len) }\n : function (str, start, len) {\n if (start < 0) start = str.length + start;\n return str.substr(start, len);\n }\n;\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack://ui/./node_modules/path-browserify/index.js?"); + +/***/ }), + /***/ "./node_modules/pbkdf2/browser.js": /*!****************************************!*\ !*** ./node_modules/pbkdf2/browser.js ***! @@ -1855,7 +1866,7 @@ eval("module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Player\", function() { return Player; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Game\", function() { return Game; });\n/* harmony import */ var _services_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./services.js */ \"./src/services.js\");\n/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! crypto */ \"./node_modules/crypto-browserify/index.js\");\n/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_1__);\n\n\n\n\n\nclass BaseUtils {\n constructor() {\n this.id = this.getUUID()\n }\n getUUID () {\n function s4 () {\n return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)\n }\n return (s4() + s4() + '-' + s4() + '-4' + s4().slice(1) + '-8' + s4().slice(1) + '-' + s4() + s4() + s4()).toUpperCase()\n }\n setId (id) {\n this.id = id\n return this\n }\n setCookie (cname, cvalue) {\n document.cookie = cname + \"=\" + cvalue + \";path=/\"\n return this\n }\n getCookie (cname) {\n let name = cname + \"=\"\n let decodedCookie = decodeURIComponent(document.cookie)\n let ca = decodedCookie.split(';')\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i]\n while (c.charAt(0) == ' ') {\n c = c.substring(1)\n }\n if (c.indexOf(name) == 0) {\n return c.substring(name.length, c.length)\n }\n }\n return \"\"\n }\n}\nclass Player extends BaseUtils {\n constructor(id, name) {\n super()\n if (id)\n this.id = id\n if (name)\n this.name = name\n return this\n }\n setId (id) {\n this.id = id\n return this\n }\n getId () {\n return this.id\n }\n setName (name) {\n this.name = name\n return this\n }\n getName () {\n return this.name\n }\n loadFromCookies() {\n this.setId(this.getCookie(\"player_id\") || this.getId())\n this.setName(this.getCookie(\"player_name\"))\n return this\n }\n setCookies() {\n this.setCookie(\"player_id\", this.id)\n this.setCookie(\"player_name\", this.name)\n return this\n }\n}\nclass Game extends BaseUtils {\n constructor(player) {\n super()\n this.setId(this.getGameIdFromUrl() || this.id)\n this.players = [player]\n this.turn = player.uuid\n this.winner = undefined\n this.draw = undefined\n this.matrix = [\n null, null, null,\n null, null, null,\n null, null, null\n ]\n this.blocked = false\n return this\n }\n getId () {\n return this.id\n }\n getGameIdFromUrl() {\n console.debug(\"getGameIdFromUrl\")\n let path = document.location.pathname.split(\"/\")\n console.debug(path)\n if (path && path.length > 1) {\n let uuid = path[path.length - 1] || \"\"\n console.debug(uuid)\n let matches = uuid.match(\"^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$\")\n return matches && matches.length ? path[path.length - 1] : undefined\n }\n return undefined\n }\n getOpponentsName(myId) {\n let opponent = this.players.filter(x => x.id !== myId)[0]\n console.debug(\"getOpponentsName()\", opponent.name)\n return opponent.name\n }\n setOpponentsTurn(myId) {\n let opponent = this.players.filter(x => x.id !== myId)[0]\n console.debug(\"setOpponentsTurn()\", opponent.id)\n this.turn = opponent.id\n return this\n }\n}\n\n//# sourceURL=webpack://ui/./src/classes.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Player\", function() { return Player; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Game\", function() { return Game; });\n/* harmony import */ var _services_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./services.js */ \"./src/services.js\");\n/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! crypto */ \"./node_modules/crypto-browserify/index.js\");\n/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(crypto__WEBPACK_IMPORTED_MODULE_1__);\n\n\n\n\n\nclass BaseUtils {\n constructor() {}\n getUUID () {\n function s4 () {\n return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)\n }\n return (s4() + s4() + '-' + s4() + '-4' + s4().slice(1) + '-8' + s4().slice(1) + '-' + s4() + s4() + s4())\n }\n setId (id) {\n this.id = id\n return this\n }\n setCookie (cname, cvalue) {\n document.cookie = cname + \"=\" + cvalue + \";path=/\"\n return this\n }\n getCookie (cname) {\n let name = cname + \"=\"\n let decodedCookie = decodeURIComponent(document.cookie)\n let ca = decodedCookie.split(';')\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i]\n while (c.charAt(0) == ' ') {\n c = c.substring(1)\n }\n if (c.indexOf(name) == 0) {\n return c.substring(name.length, c.length)\n }\n }\n return \"\"\n }\n}\nclass Player extends BaseUtils {\n constructor(id, name) {\n super()\n // if `id` and `name` are passed in, we don't want to set cookies\n if (id) {\n this.id = id\n } else {\n this.setId(id || this.getCookie(\"player_id\") || this.getUUID())\n }\n if (name) {\n this.name = name\n } else {\n this.setName(name || this.getCookie(\"player_name\"))\n }\n return this\n }\n getId () {\n return this.id.toLowerCase()\n }\n setId (id) {\n this.id = id\n this.setCookie(\"player_id\", id)\n return this\n }\n getName () {\n return this.name\n }\n setName (name) {\n this.name = name\n this.setCookie(\"player_name\", name)\n return this\n }\n}\nclass Game extends BaseUtils {\n constructor() {\n super()\n this.setId((new URLSearchParams(window.location.search)).get('id'))\n this.player1 = undefined // person who started the game\n this.player2 = undefined // person who joined the game\n this.winner = undefined // player.id\n this.draw = undefined // true/false\n this.matrix = [\n null, null, null, // player.id\n null, null, null,\n null, null, null\n ]\n this.next_game = undefined\n return this\n }\n getId() {\n return this.id\n }\n setId(id) {\n console.debug(\"Set Game ID\", id)\n if (id)\n history.replaceState(null, \"\", \"?id=\" + id)\n this.id = id\n return this\n }\n setTurn (player_id) {\n console.debug(\"Set Game Turn\", player_id)\n this.turn = player_id\n return this\n }\n getOpponent() {\n let player_id = this.getCookie(\"player_id\")\n return this.player1.id == player_id ? this.player2 : this.player1\n }\n setOpponentsTurn() {\n let opponent = this.getOpponent()\n this.setTurn(opponent.id)\n return this\n }\n logResult(winnersName) {\n this.winners.push(winnersName)\n }\n}\n\n//# sourceURL=webpack://ui/./src/classes.js?"); /***/ }), @@ -1867,7 +1878,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) * /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Copy\", function() { return Copy; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"TooltipBlur\", function() { return TooltipBlur; });\n/* harmony import */ var _classes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./classes.js */ \"./src/classes.js\");\n/* harmony import */ var _services_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./services.js */ \"./src/services.js\");\n/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./style.scss */ \"./src/style.scss\");\n/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_style_scss__WEBPACK_IMPORTED_MODULE_2__);\n\n\n\n\n\n\nlet conn\nlet gameOver = false\nlet player = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"]()\nplayer.loadFromCookies()\nplayer.setCookies()\nlet game = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Game\"](player)\n\nconsole.debug(player)\nconsole.debug(game)\n\n/**\n * Initialize DOM variables\n */\nlet name = document.getElementById('name')\nlet nameLabel = document.getElementById('nameLabel')\nlet playerH1 = document.getElementById('player')\nlet status = document.getElementById('status')\nlet waiting = document.getElementById('waiting')\nlet turn = document.getElementById('turn')\nlet winner = document.getElementById('winner')\nlet draw = document.getElementById('draw')\nlet gameTable = document.getElementById('gameTable')\nlet instructions = document.getElementById('instructions')\nlet input = document.getElementById('shareLink')\nlet tooltip = document.getElementById(\"tooltip\")\nlet startGameForm = document.getElementById('startGameForm')\nlet joinGameForm = document.getElementById('joinGameForm')\nlet opponentTileColor = \"#992222\"\nlet tileColor = \"#229922\"\n\n/**\n * Setup\n */\nfunction _setup() {\n if (player.getName()) {\n name.value = player.getName()\n name.classList.add(\"hide\")\n nameLabel.classList.add(\"hide\")\n playerH1.innerText = \"Hi \" + player.getName()\n playerH1.classList.remove(\"hide\")\n }\n}\n_setup()\n\n\nfunction Copy (context) {\n console.debug(context.innerText)\n context.select()\n document.execCommand(\"Copy\")\n tooltip.innerHTML = \"Copied!\"\n}\nfunction TooltipBlur () {\n tooltip.innerHTML = \"Copy\"\n}\n\n\nif (window.WebSocket) {\n conn = new WebSocket(\"wss://\" + document.location.host + \"/ws\")\n conn.onclose = function (evt) {\n console.debug(\"Websocket Closed\")\n }\n conn.onmessage = function (evt) {\n let messages = evt.data.split('\\n')\n for (var i = 0; i < messages.length; i++) {\n let data = messages[i]\n try {\n data = JSON.parse(data)\n } catch (e) {\n console.error(\"Error parsing\", data)\n }\n console.debug(\"Message\", data)\n if (data.sender === player.getId()) {\n console.debug(\"My own message received and ignored\")\n return\n }\n switch(data.event) {\n case \"joining\":\n console.debug(\"Event: joining\")\n instructions.classList.add(\"hide\")\n game.players.push(data.player)\n console.debug(game)\n _yourTurn()\n _showGame()\n break\n case \"move\":\n console.debug(\"Event: move\")\n game.matrix[data.index] = data.player\n _updateTiles(data.index)\n _yourTurn()\n console.debug(game.matrix)\n break\n case \"winner\":\n console.debug(\"Event: winner\")\n game.matrix[data.index] = data.player\n _updateTiles(data.index)\n gameOver = true\n status.classList.add(\"hide\")\n turn.classList.add(\"hide\")\n winner.innerText = \"You lose... \" + game.getOpponentsName(player.getId()) + \" Wins!\"\n winner.classList.remove(\"hide\")\n _highlightBoard(data.positions)\n _dimBoard()\n if (startGameForm)\n startGameForm.classList.remove(\"hide\")\n break\n case \"draw\":\n console.debug(\"Event: draw\")\n game.matrix[data.index] = data.player\n _updateTiles(data.index)\n gameOver = true\n status.classList.add(\"hide\")\n turn.classList.add(\"hide\")\n winner.innerText = \"Its a draw!\"\n winner.classList.remove(\"hide\")\n _dimBoard()\n if (startGameForm)\n startGameForm.classList.remove(\"hide\")\n break\n }\n }\n }\n} else {\n console.error(\"TicTacToe can only be played in a browser that supports a WebSocket connection.\")\n}\n\n/**\n * BEGIN Document Listeners\n */\nif (startGameForm) {\n startGameForm.addEventListener('submit', event => {\n event.preventDefault()\n if (!_validateForm()) {\n return false\n }\n _createGame().then(resp => {\n name.classList.add(\"hide\")\n nameLabel.classList.add(\"hide\")\n startGameForm.classList.add(\"hide\")\n console.debug(\"_createGame() success\", resp)\n game.turn = resp.turn\n game.matrix = resp.matrix\n console.debug(\"Game:\", game)\n input.value = _getUrl() + \"/join/\" + game.getId()\n instructions.classList.remove(\"hide\")\n _waiting()\n // _yourTurn()\n // _showGame()\n }).catch(err => {\n console.debug(\"_createGame() error\", err)\n status.innerText = err.message.error\n status.classList.remove(\"hide\")\n })\n })\n}\nif (joinGameForm) {\n joinGameForm.addEventListener('submit', event => {\n event.preventDefault()\n if (!_validateForm()) {\n return false\n }\n _addPlayer().then(resp => {\n name.classList.add(\"hide\")\n nameLabel.classList.add(\"hide\")\n joinGameForm.classList.add(\"hide\")\n console.debug(\"_addPlayer() success\", resp)\n conn.send(JSON.stringify({\n sender: player.getId(),\n game_id: game.getId(),\n event: \"joining\",\n player: {\n id: player.getId(),\n name: player.getName()\n }\n }))\n game.players.push(new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.players[0].id, resp.players[0].name))\n _theirTurn()\n _showGame()\n }).catch(err => {\n console.debug(\"_addPlayer() error\", err)\n status.innerText = err.message.error\n status.classList.remove(\"hide\")\n })\n })\n}\nif (gameTable) {\n document.querySelectorAll('.tile').forEach(element => {\n element.addEventListener('click', event => {\n if (gameOver) {\n console.debug(\"Game over\")\n event.preventDefault()\n return\n }\n let pos = event.target.id.split('_')[1]\n // validate its my turn\n if (game.turn !== player.getId()) {\n console.debug(\"Not my turn\")\n event.preventDefault()\n return\n }\n // validate position available\n if (game.matrix[pos]) {\n console.debug(\"Tile not free\")\n event.preventDefault()\n return\n }\n // set move\n game.matrix[pos] = player.getId()\n\n // show tile selected\n event.target.style.backgroundColor = tileColor\n\n // calculate if 3 tiles in a row\n let three = _threeInARow()\n if (three) {\n console.debug(\"You win!\")\n _highlightBoard(three)\n _dimBoard()\n gameOver = true\n winner.innerText = \"You Win!!!\"\n winner.classList.remove(\"hide\")\n status.classList.add(\"hide\")\n turn.classList.add(\"hide\")\n conn.send(JSON.stringify({\n sender: player.getId(),\n game_id: game.getId(),\n event: \"winner\",\n index: pos,\n player: player.getId(),\n winner: player.getId(),\n positions: three\n }))\n if (startGameForm)\n startGameForm.classList.remove(\"hide\")\n event.preventDefault()\n return\n }\n\n if (_draw()) {\n console.debug(\"Draw!\")\n _dimBoard()\n gameOver = true\n winner.innerText = \"Its a draw!\"\n winner.classList.remove(\"hide\")\n status.classList.add(\"hide\")\n turn.classList.add(\"hide\")\n conn.send(JSON.stringify({\n sender: player.getId(),\n game_id: game.getId(),\n event: \"draw\",\n index: pos,\n player: player.getId(),\n winner: player.getId()\n }))\n if (startGameForm)\n startGameForm.classList.remove(\"hide\")\n event.preventDefault()\n return\n }\n\n // send move via socket\n conn.send(JSON.stringify({\n sender: player.getId(),\n game_id: game.getId(),\n event: \"move\",\n index: pos,\n player: player.getId()\n }))\n\n _theirTurn()\n })\n })\n}\n/**\n * END Document Listeners\n */\n\nfunction _validateForm() {\n if (!name.value) {\n status.innerText = \"Name is required.\"\n status.classList.remove(\"hide\")\n return false\n }\n player.setName(name.value)\n player.setCookies()\n status.classList.add(\"hide\")\n _greeting()\n return true\n}\nfunction _getUrl() {\n return document.location.protocol + '//' + document.location.host\n}\nfunction _greeting() {\n if (player.getName()) {\n playerH1.innerText = \"Hi \" + player.getName()\n playerH1.classList.remove(\"hide\")\n }\n}\nfunction _createGame() {\n let url = _getUrl()\n return _services_js__WEBPACK_IMPORTED_MODULE_1__[\"POST\"](`${url}/game`, JSON.stringify(game))\n}\nfunction _addPlayer() {\n let url = _getUrl()\n let gid = game.getId()\n let pid = player.getId()\n return _services_js__WEBPACK_IMPORTED_MODULE_1__[\"POST\"](`${url}/game/${gid}/player/${pid}`, JSON.stringify({ name: document.getElementById('name').value }))\n}\nfunction _showGame() {\n gameTable.classList.remove(\"hide\")\n}\nfunction _waiting() {\n waiting.innerText = \"Waiting for opponent\"\n waiting.classList.remove(\"hide\")\n}\nfunction _yourTurn () {\n if (waiting)\n waiting.classList.add(\"hide\")\n turn.innerText = \"Your Turn\"\n turn.classList.remove(\"hide\")\n game.turn = player.getId()\n}\nfunction _theirTurn () {\n game.setOpponentsTurn(player.getId())\n turn.innerText = _possessivizer(game.getOpponentsName(player.getId())) + \" Turn\"\n turn.classList.remove(\"hide\")\n}\nfunction _possessivizer(name) {\n if (name.charAt(name.length - 1) === \"s\") {\n return name + \"'\"\n } else {\n return name + \"'s\"\n }\n}\nfunction _updateTiles(index) {\n document.getElementById('pos_' + index).style.backgroundColor = opponentTileColor\n}\nfunction _threeInARow() {\n for (let i = 0; i <= 8; i) {\n if (game.matrix[i] && (game.matrix[i] === game.matrix[i + 1] && game.matrix[i] === game.matrix[i + 2]) ) {\n return [i, i + 1, i + 2]\n }\n i = i + 3\n }\n for (let i = 0; i <= 2; i++) {\n if (game.matrix[i] && (game.matrix[i] === game.matrix[i + 3] && game.matrix[i] === game.matrix[i + 6]) ) {\n return [i, i + 3, i + 6]\n }\n }\n if (game.matrix[0] && (game.matrix[0] === game.matrix[4] && game.matrix[0] === game.matrix[8])) {\n return [0, 4, 8]\n }\n if (game.matrix[2] && (game.matrix[2] === game.matrix[4] && game.matrix[2] === game.matrix[6])) {\n return [2, 4, 6]\n }\n return false\n}\nfunction _draw() {\n for (let i = 0; i < game.matrix.length; i++) {\n if (!game.matrix[i]) {\n return false\n }\n }\n return true\n}\nfunction _dimBoard() {\n document.querySelectorAll('td').forEach(el => el.classList.add(\"dim\"))\n}\n\nfunction _highlightBoard (positions) {\n for (let pos of positions) {\n document.querySelector('#pos_' + pos).classList.add(\"highlight\")\n }\n}\n\n//# sourceURL=webpack://ui/./src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Copy\", function() { return Copy; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"TooltipBlur\", function() { return TooltipBlur; });\n/* harmony import */ var _classes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./classes.js */ \"./src/classes.js\");\n/* harmony import */ var _services_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./services.js */ \"./src/services.js\");\n/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./style.scss */ \"./src/style.scss\");\n/* harmony import */ var _style_scss__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_style_scss__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! path */ \"./node_modules/path-browserify/index.js\");\n/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);\n\n\n\n\n\n\n\n/**\n * Initialize DOM variables\n */\nlet name = document.getElementById('name')\nlet nameLabel = document.getElementById('nameLabel')\nlet playerH1 = document.getElementById('player')\nlet status = document.getElementById('status')\nlet gameTable = document.getElementById('gameTable')\nlet instructions = document.getElementById('instructions')\nlet shareLink = document.getElementById('shareLink')\nlet tooltip = document.getElementById(\"tooltip\")\nlet startGameForm = document.getElementById('startGameForm')\nlet joinGameForm = document.getElementById('joinGameForm')\nlet opponentTileColor = \"#992222\"\nlet tileColor = \"#229922\"\nlet gameOver = false\nlet firstgame = true\n\nlet conn\nlet player = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"]()\nconsole.debug(player)\nif (player.getName()) {\n name.value = player.getName()\n _hideConfig()\n _showGreeting()\n}\n\nlet game = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Game\"]()\nconsole.debug(game)\nif (game.getId()) {\n firstgame = false\n // we need to fetch the game data and resume the game\n _retrieveGameFromServer().then(resp => {\n console.debug(\"_retrieveGameFromServer() success\", resp)\n game.player1 = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.player1.id, resp.player1.name)\n game.turn = resp.turn\n game.matrix = resp.matrix\n if (!resp.player2 || typeof resp.player2 === \"undefined\") {\n _updateGameOnServer({\n player2: player\n }).then(resp => {\n console.debug(\"_updateGame() success\", resp)\n console.debug(game)\n }).catch(err => {\n console.debug(\"_updateGame() err\", err)\n })\n } else {\n game.player2 = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.player2.id, resp.player2.name)\n }\n if (document.location.pathname != \"/join\") {\n _renderGame()\n _showGame()\n }\n console.debug(game)\n }).catch(err => {\n console.debug(\"_retrieveGameFromServer() error\", err)\n })\n}\n\n\nfunction Copy (context) {\n console.debug(context.innerText)\n context.select()\n document.execCommand(\"Copy\")\n tooltip.innerHTML = \"Copied!\"\n}\nfunction TooltipBlur () {\n tooltip.innerHTML = \"Copy\"\n}\n\n\nif (window.WebSocket) {\n conn = new WebSocket(\"ws://\" + document.location.host + \"/ws\")\n conn.onclose = function (evt) {\n console.debug(\"Websocket Closed\")\n }\n conn.onmessage = function (evt) {\n let messages = evt.data.split('\\n')\n for (var i = 0; i < messages.length; i++) {\n let data = messages[i]\n try {\n data = JSON.parse(data)\n } catch (e) {\n console.error(\"Error parsing\", data)\n }\n console.debug(\"Message\", data)\n if (data.sender.toUpperCase() === player.getId().toUpperCase()) {\n // console.debug(\"My own message received and ignored\")\n return\n }\n if (data.game_id.toUpperCase() !== game.getId().toUpperCase()) {\n // console.debug(\"Not my game\")\n return\n }\n switch(data.event) {\n case \"joining\":\n console.debug(\"Event: joining\")\n instructions.classList.add(\"hide\")\n _safeRetrieve()\n _showGame()\n break\n case \"new\":\n console.debug(\"Event: new\")\n let newGame = confirm(\"Would you like to play again?\")\n if (newGame) {\n history.replaceState(null, \"\", \"?id=\" + data.new_game_id)\n game.setId(data.new_game_id)\n _retrieveGameFromServer().then(resp => {\n console.debug(\"_retrieveGameFromServer() success\", resp)\n game.player1 = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.player1.id, resp.player1.name)\n game.player2 = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.player2.id, resp.player2.name)\n game.matrix = resp.matrix\n game.turn = resp.turn\n console.debug(game)\n gameOver = false\n _renderGame()\n }).catch(err => {\n console.debug(\"_retrieveGameFromServer() error\", err)\n })\n }\n break\n case \"move\":\n console.debug(\"Event: move\")\n _safeRetrieve()\n break\n case \"winner\":\n console.debug(\"Event: winner\")\n game.winner = data.sender\n _safeRetrieve()\n break\n }\n }\n }\n} else {\n console.error(\"TicTacToe can only be played in a browser that supports a WebSocket connection.\")\n}\n\n/**\n * BEGIN Document Listeners\n */\nif (startGameForm) {\n startGameForm.addEventListener('submit', event => {\n event.preventDefault()\n if (!_validateForm()) {\n return false\n }\n if (firstgame) {\n _safeCreate()\n firstgame = false\n } else {\n _createGame().then(resp => {\n console.debug(\"_createGame() success\", resp)\n history.replaceState(null, \"\", \"?id=\" + resp.id)\n let old_game_id = game.getId()\n game.setId(resp.id)\n _updateGameOnServer({\n player2: game.player2,\n turn: game.player1.id == game.winner ? game.player2.id : game.player1.id,\n previous_game: old_game_id\n }).then(resp => {\n console.debug(\"_updateGameOnServer() success\", resp)\n gameOver = false\n game.turn = resp.turn\n game.matrix = resp.matrix\n conn.send(JSON.stringify({\n sender: player.getId(),\n game_id: old_game_id,\n event: \"new\",\n new_game_id: resp.id\n }))\n _renderGame()\n }).catch(err => {\n console.debug(\"_updateGameOnServer() err\", err)\n })\n }).catch(err => {\n console.debug(\"_createGame() err\", err)\n })\n }\n })\n}\nif (joinGameForm) {\n joinGameForm.addEventListener('submit', event => {\n event.preventDefault()\n if (!_validateForm()) {\n return false\n }\n conn.send(JSON.stringify({\n sender: player.getId(),\n game_id: game.getId(),\n event: \"joining\"\n }))\n joinGameForm.classList.add(\"hide\")\n _theirTurn()\n _showGame()\n })\n}\nfunction tileListener (event) {\n if (gameOver) {\n event.preventDefault()\n return false\n }\n let pos = event.target.id.split('_')[1]\n // validate its my turn\n if (game.turn !== player.getId()) {\n console.debug(\"Not my turn\")\n event.preventDefault()\n return\n }\n // validate position available\n if (game.matrix[pos]) {\n console.debug(\"Tile not free\")\n event.preventDefault()\n return\n }\n // set move\n game.matrix[pos] = player.getId()\n\n // calculate if 3 tiles in a row\n let [done, winner, positions] = _threeInARow()\n\n _updateGameOnServer({\n id: game.getId(),\n player1: game.player1,\n player2: game.player2,\n turn: game.player1.id == game.turn ? game.player2.id : game.player1.id,\n winner: winner,\n matrix: game.matrix\n }).then(resp => {\n console.debug(\"_updateGameOnServer() success\", resp)\n conn.send(JSON.stringify({\n sender: player.getId(),\n game_id: game.getId(),\n event: done ? \"winner\" : \"move\"\n }))\n game.turn = resp.turn\n _renderGame()\n }).catch(err => {\n console.debug(\"_updateGameOnServer() error\", err)\n })\n}\nif (gameTable) {\n document.querySelectorAll('.tile').forEach(element => {\n element.addEventListener('click', tileListener)\n })\n}\n/**\n * END Document Listeners\n */\nfunction _validateForm() {\n if (!name.value) {\n status.innerText = \"Name is required.\"\n status.style.color = \"#FF0000\"\n return false\n }\n status.style.color = \"#000000\"\n player.setName(name.value)\n _hideConfig()\n _showGreeting()\n return true\n}\n\nfunction _showInstructions() {\n shareLink.value = _getUrl() + \"/join?id=\" + game.getId()\n instructions.classList.remove(\"hide\")\n}\nfunction _hideInstructions () {\n instructions.classList.add(\"hide\")\n}\nfunction _showGreeting() {\n if (player.getName()) {\n playerH1.innerText = \"Hi \" + player.getName()\n playerH1.classList.remove(\"hide\")\n }\n}\nfunction _showGame () {\n gameTable.classList.remove(\"hide\")\n}\nfunction _resumeGame () {\n startGameForm.classList.add(\"hide\")\n _showGame()\n}\nfunction _hideConfig () {\n name.classList.add(\"hide\")\n nameLabel.classList.add(\"hide\")\n}\n\nfunction _renderGame() {\n console.debug(\"Render Game Board\")\n _dimBoard(true)\n for (let i = 0; i < game.matrix.length; i++) {\n let playerAt = game.matrix\n if (playerAt[i] === player.getId()) {\n document.getElementById('pos_' + i).style.backgroundColor = tileColor\n } else if (playerAt[i] === game.getOpponent().getId()) {\n document.getElementById('pos_' + i).style.backgroundColor = opponentTileColor\n } else { \n document.getElementById('pos_' + i).style.backgroundColor = \"unset\"\n }\n }\n if (game.turn == player.getId()) {\n _yourTurn()\n } else {\n _theirTurn()\n }\n let [done, winner, positions] = _threeInARow()\n if (done) {\n gameOver = true\n game.winner = winner\n _dimBoard()\n _highlightBoard(positions)\n if (winner == player.getId()) {\n status.innerText = \"You Win!!!\"\n } else {\n status.innerText = \"You lose... \" + game.getOpponent().getName() + \" Wins!\"\n }\n }\n if (_draw()) {\n gameOver = true\n _dimBoard()\n status.innerText = \"Its a draw!\"\n }\n}\n\nfunction _getUrl () {\n return document.location.protocol + '//' + document.location.host\n}\nfunction _safeCreate() {\n _createGame().then(resp => {\n console.debug(\"_createGame() success\", resp)\n game.setId(resp.id)\n game.player1 = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.player1.id, resp.player1.name)\n console.debug(game)\n _showInstructions()\n }).catch(err => {\n console.debug(\"_createGame() err\", err)\n })\n}\nfunction _createGame () {\n let url = _getUrl()\n return _services_js__WEBPACK_IMPORTED_MODULE_1__[\"POST\"](`${url}/game`, JSON.stringify({ player1: player }))\n}\nfunction _updateGameOnServer(updatePayload) {\n let url = _getUrl() + \"/game/\" + game.getId()\n return _services_js__WEBPACK_IMPORTED_MODULE_1__[\"POST\"](url, JSON.stringify(updatePayload))\n}\nfunction _safeRetrieve() {\n _retrieveGameFromServer().then(resp => {\n console.debug(\"_retrieveGameFromServer() success\", resp)\n game.player1 = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.player1.id, resp.player1.name)\n game.player2 = new _classes_js__WEBPACK_IMPORTED_MODULE_0__[\"Player\"](resp.player2.id, resp.player2.name)\n game.matrix = resp.matrix || [null, null, null, null, null, null, null, null, null]\n game.turn = resp.turn\n _renderGame()\n console.debug(game)\n }).catch(err => {\n console.debug(\"_retrieveGameFromServer() error\", err)\n })\n}\nfunction _retrieveGameFromServer() {\n let url = _getUrl() + \"/game/\" + game.getId()\n return _services_js__WEBPACK_IMPORTED_MODULE_1__[\"GET\"](url)\n}\nfunction _yourTurn () {\n status.innerText = \"Your Turn\"\n game.turn = player.getId()\n}\nfunction _theirTurn () {\n status.innerText = _possessivizer(game.getOpponent().getName()) + \" Turn\"\n}\nfunction _possessivizer(name) {\n if (name.charAt(name.length - 1) === \"s\") {\n return name + \"'\"\n } else {\n return name + \"'s\"\n }\n}\nfunction _threeInARow() {\n for (let i = 0; i <= 8; i) {\n if (game.matrix[i] && (game.matrix[i] === game.matrix[i + 1] && game.matrix[i] === game.matrix[i + 2]) ) {\n return [true, game.matrix[i], [i, i + 1, i + 2]]\n }\n i = i + 3\n }\n for (let i = 0; i <= 2; i++) {\n if (game.matrix[i] && (game.matrix[i] === game.matrix[i + 3] && game.matrix[i] === game.matrix[i + 6]) ) {\n return [true, game.matrix[i], [i, i + 3, i + 6]]\n }\n }\n if (game.matrix[0] && (game.matrix[0] === game.matrix[4] && game.matrix[0] === game.matrix[8])) {\n return [true, game.matrix[0], [0, 4, 8]]\n }\n if (game.matrix[2] && (game.matrix[2] === game.matrix[4] && game.matrix[2] === game.matrix[6])) {\n return [true, game.matrix[2], [2, 4, 6]]\n }\n return [false, null, null]\n}\nfunction _draw() {\n for (let i = 0; i < game.matrix.length; i++) {\n if (!game.matrix[i]) {\n return false\n }\n }\n return true\n}\nfunction _dimBoard(reverse) {\n if (reverse) {\n document.querySelectorAll('td').forEach(el => el.classList.remove(\"dim\"))\n document.querySelectorAll('td').forEach(el => el.classList.remove(\"highlight\"))\n } else {\n document.querySelectorAll('td').forEach(el => el.classList.add(\"dim\"))\n }\n}\nfunction _highlightBoard (positions) {\n for (let pos of positions) {\n document.querySelector('#pos_' + pos).classList.add(\"highlight\")\n }\n}\n\n//# sourceURL=webpack://ui/./src/index.js?"); /***/ }), @@ -1879,7 +1890,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) * /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"GET\", function() { return GET; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"POST\", function() { return POST; });\n\n\n// GET HTTP call\nfunction GET (theUrl, callback) {\n var req = new XMLHttpRequest()\n req.onreadystatechange = function () {\n if (req.readyState == 4 && req.status == 200)\n callback(req.responseText)\n }\n req.open(\"GET\", theUrl, true)\n req.send(null)\n}\n\n// POST HTTP call\nfunction POST (theUrl, data) {\n return new Promise((resolve, reject) => {\n let req = new XMLHttpRequest()\n req.onreadystatechange = function () {\n if (req.readyState == 4 && req.status == 200) {\n resolve(_parseOrNot(req.responseText))\n } else if (req.readyState == 4) {\n reject({ status: req.status, message: _parseOrNot(req.responseText) })\n }\n }\n req.open(\"POST\", theUrl, true)\n if (data) {\n req.setRequestHeader(\"Content-Type\", \"application/json\")\n }\n req.send(data)\n })\n}\n\nfunction _parseOrNot(str) {\n let data = str\n try {\n data = JSON.parse(str)\n } catch (e) {\n console.debug(\"Error Parsing Response JSON:\", str)\n }\n return data\n}\n\n//# sourceURL=webpack://ui/./src/services.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"GET\", function() { return GET; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"POST\", function() { return POST; });\n\n\n// GET HTTP call\nfunction GET (theUrl) {\n return new Promise((resolve, reject) => {\n var req = new XMLHttpRequest()\n req.onreadystatechange = function () {\n if (req.readyState == 4 && req.status == 200) {\n resolve(_parseOrNot(req.responseText))\n } else if (req.readyState == 4) {\n reject({ status: req.status, message: _parseOrNot(req.responseText) })\n }\n }\n req.open(\"GET\", theUrl, true)\n req.send(null)\n })\n}\n\n// POST HTTP call\nfunction POST (theUrl, data) {\n return new Promise((resolve, reject) => {\n let req = new XMLHttpRequest()\n req.onreadystatechange = function () {\n if (req.readyState == 4 && req.status == 200) {\n resolve(_parseOrNot(req.responseText))\n } else if (req.readyState == 4) {\n reject({ status: req.status, message: _parseOrNot(req.responseText) })\n }\n }\n req.open(\"POST\", theUrl, true)\n if (data) {\n req.setRequestHeader(\"Content-Type\", \"application/json\")\n }\n req.send(data)\n })\n}\n\nfunction _parseOrNot(str) {\n let data = str\n try {\n data = JSON.parse(str)\n } catch (e) {\n console.debug(\"Error Parsing Response JSON:\", str)\n }\n return data\n}\n\n//# sourceURL=webpack://ui/./src/services.js?"); /***/ }), diff --git a/dist/index.html b/dist/index.html index 86a6c6a..f65ae41 100644 --- a/dist/index.html +++ b/dist/index.html @@ -11,6 +11,26 @@

TicTacToe

+
+
+ + + + + + + + + + + + + + + + +
TIC
TAC
TOE
+
@@ -25,31 +45,8 @@
-
-
Waiting for opponent
-
Your Turn
-
You WIN!!!
-
- - - - - - - - - - - - - - - - -
TIC
TAC
TOE
-
diff --git a/dist/join.html b/dist/join.html index f377bf9..45c2fe7 100644 --- a/dist/join.html +++ b/dist/join.html @@ -11,33 +11,31 @@

TicTacToe

+
+
+ + + + + + + + + + + + + + + + +
TIC
TAC
TOE
+
-
-
-
You WIN!!!
-
-
- - - - - - - - - - - - - - - - -
TIC
TAC
TOE
diff --git a/dist/main.css b/dist/main.css index ba9d379..35fa94e 100644 --- a/dist/main.css +++ b/dist/main.css @@ -1,28 +1,43 @@ @import url(https://fonts.googleapis.com/css?family=Lato); +body { + font-family: 'Lato', sans-serif; } + +h1 { + font: normal normal normal 32px/40px 'Lato', sans-serif; } + +h2 { + font: normal normal normal 24px/30px 'Lato', sans-serif; } + +.record { + font: normal normal normal 16px/30px 'Lato', sans-serif; } + .record #log, .record #inprogress { + font-size: 10px; } + +form { + padding-top: 20px; } + form input#name { + font: normal normal normal 14px/30px 'Lato', sans-serif; + height: 30px; + display: block; } + form button#start, form button#join { + font: normal normal normal 14px/30px 'Lato', sans-serif; + margin: 20px 0; + height: 30px; + background: #4d16e4; + border: none; + border-radius: 2px; + color: white; } + input#shareLink { font-family: monospace; cursor: pointer; width: 400px; } -span#copySuccess { - display: none; - color: green; - font-weight: bold; } - -span#copyError { - display: none; - color: red; - font-weight: bold; } - .link { color: blue; } #status { - font: normal normal normal 16px/20px 'Lato', sans-serif; - color: red; } - -#turn, #waiting { - font: normal normal normal 16px/20px 'Lato', sans-serif; } + font: normal normal bold 16px/20px 'Lato', sans-serif; } #gameTable tr td { border-bottom: 1px solid #333; @@ -43,7 +58,7 @@ span#copyError { border-bottom: none; } .hide { - display: none; } + display: none !important; } .tooltip { position: relative; diff --git a/main.go b/main.go index 6d1f523..5226d7a 100644 --- a/main.go +++ b/main.go @@ -1,17 +1,17 @@ package main import ( + "errors" "log" + "math/rand" "net/http" "os" + Cache "tictactoe-api/cache" "time" - cache "tictactoe-api/cache" - "github.com/gin-contrib/multitemplate" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" - uuid "github.com/satori/go.uuid" ) func setupRender() multitemplate.Renderer { @@ -21,10 +21,20 @@ func setupRender() multitemplate.Renderer { return r } +const charBytes = "abcdefghijkmnopqrstuvwxyz023456789" + +func generateRandom(n int) string { + b := make([]byte, n) + for i := range b { + b[i] = charBytes[rand.Int63()%int64(len(charBytes))] + } + return string(b) +} + func main() { hub := newHub() go hub.run() - cache := cache.NewCache(time.Minute*10, time.Minute) + cache := Cache.NewCache(time.Minute*10, time.Minute) router := gin.Default() router.HTMLRender = setupRender() router.Static("/static", "dist") @@ -44,7 +54,7 @@ func main() { // // - router.GET("/join/:gameUUID", func(c *gin.Context) { + router.GET("/join", func(c *gin.Context) { c.HTML(http.StatusOK, "join", gin.H{ "title": "Play Game", }) @@ -57,23 +67,38 @@ func main() { }) router.POST("/game", func(c *gin.Context) { - var game Game + var game Cache.Game err := c.BindJSON(&game) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return + log.Printf("Error Binding Request %s\n", err.Error()) + } + count := 0 + generate: + game.ID = generateRandom(6) + _, found := cache.Get(game.ID) + if found { + count = count + 1 + log.Printf("GAME FOUND, trying again: %s\n", game.ID) + if count >= 3 { + err = errors.New("Could not generate a new game (too many games in progress)") + } else { + goto generate + } } - game.Turn = game.Players[0].UUID - cache.Set(game.UUID, game, 0) - c.JSON(http.StatusOK, game) - }) - - router.GET("/game/:gameUUID", func(c *gin.Context) { - gameUUID, err := uuid.FromString(c.Params.ByName("gameUUID")) if err != nil { - log.Printf("UUID Parse Failed: %s\n", err) + c.JSON(http.StatusConflict, gin.H{ + "error": err.Error(), + }) + } else { + game.Turn = &game.Player1.UUID + cache.Set(game.ID, game, 0) + c.JSON(http.StatusOK, game) } - game, found := cache.Get(gameUUID) + }) + + router.GET("/game/:gameID", func(c *gin.Context) { + gameID := c.Params.ByName("gameID") + game, found := cache.Get(gameID) if !found { c.Status(http.StatusNotFound) return @@ -81,39 +106,46 @@ func main() { c.JSON(http.StatusOK, game) }) - router.POST("/game/:gameUUID/player/:playerUUID", func(c *gin.Context) { - gameUUID, err := uuid.FromString(c.Params.ByName("gameUUID")) - if err != nil { - log.Printf("UUID Game Parse Failed: %s\n", err) - } - playerUUID, err := uuid.FromString(c.Params.ByName("playerUUID")) - if err != nil { - log.Printf("UUID Player Parse Failed: %s\n", err) - } - game, found := cache.Get(gameUUID) + router.POST("/game/:gameID", func(c *gin.Context) { + gameID := c.Params.ByName("gameID") + game, found := cache.Get(gameID) if !found { c.Status(http.StatusNotFound) return } - _game := game.(Game) - var player Player - err = c.BindJSON(&player) + var updateGame Cache.Game + err := c.BindJSON(&updateGame) if err != nil { log.Printf("Error: %s\n", err) } - if len(_game.Players) > 1 { - c.JSON(http.StatusBadRequest, gin.H{"error": "TicTacToe can only be played with two players."}) - return + if updateGame.ID != "" { + game.ID = updateGame.ID } - - _game.Players = append(_game.Players, &Player{ - UUID: &playerUUID, - Name: player.Name, - }) - cache.Set(gameUUID, _game, 0) - c.JSON(http.StatusOK, _game) + if updateGame.Player1 != nil { + game.Player1 = updateGame.Player1 + } + if updateGame.Player2 != nil { + game.Player2 = updateGame.Player2 + } + if updateGame.Turn != nil { + game.Turn = updateGame.Turn + } + if (Cache.Matrix{}) != updateGame.Matrix { + game.Matrix = updateGame.Matrix + } + // if updateGame.Draw != nil { + // game.Draw = updateGame.Draw + // } + // if updateGame.Winner != nil { + // game.Winner = updateGame.Winner + // } + // if updateGame.Tally != nil { + // game.Tally = append(game.Tally, updateGame.Tally[0]) + // } + cache.Set(gameID, game, 0) + c.JSON(http.StatusOK, game) }) // diff --git a/src/classes.js b/src/classes.js index dd0ee89..28b3454 100644 --- a/src/classes.js +++ b/src/classes.js @@ -4,14 +4,12 @@ import * as HTTP from './services.js' import { timingSafeEqual } from 'crypto'; class BaseUtils { - constructor() { - this.id = this.getUUID() - } + constructor() {} getUUID () { function s4 () { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) } - return (s4() + s4() + '-' + s4() + '-4' + s4().slice(1) + '-8' + s4().slice(1) + '-' + s4() + s4() + s4()).toUpperCase() + return (s4() + s4() + '-' + s4() + '-4' + s4().slice(1) + '-8' + s4().slice(1) + '-' + s4() + s4() + s4()) } setId (id) { this.id = id @@ -40,77 +38,77 @@ class BaseUtils { export class Player extends BaseUtils { constructor(id, name) { super() - if (id) + // if `id` and `name` are passed in, we don't want to set cookies + if (id) { this.id = id - if (name) + } else { + this.setId(id || this.getCookie("player_id") || this.getUUID()) + } + if (name) { this.name = name - return this - } - setId (id) { - this.id = id + } else { + this.setName(name || this.getCookie("player_name")) + } return this } getId () { - return this.id + return this.id.toLowerCase() } - setName (name) { - this.name = name + setId (id) { + this.id = id + this.setCookie("player_id", id) return this } getName () { return this.name } - loadFromCookies() { - this.setId(this.getCookie("player_id") || this.getId()) - this.setName(this.getCookie("player_name")) - return this - } - setCookies() { - this.setCookie("player_id", this.id) - this.setCookie("player_name", this.name) + setName (name) { + this.name = name + this.setCookie("player_name", name) return this } } export class Game extends BaseUtils { - constructor(player) { + constructor() { super() - this.setId(this.getGameIdFromUrl() || this.id) - this.players = [player] - this.turn = player.uuid - this.winner = undefined - this.draw = undefined + this.setId((new URLSearchParams(window.location.search)).get('id')) + this.player1 = undefined // person who started the game + this.player2 = undefined // person who joined the game + this.winner = undefined // player.id + this.draw = undefined // true/false this.matrix = [ - null, null, null, + null, null, null, // player.id null, null, null, null, null, null ] - this.blocked = false + this.next_game = undefined return this } - getId () { + getId() { return this.id } - getGameIdFromUrl() { - console.debug("getGameIdFromUrl") - let path = document.location.pathname.split("/") - console.debug(path) - if (path && path.length > 1) { - let uuid = path[path.length - 1] || "" - console.debug(uuid) - let matches = uuid.match("^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$") - return matches && matches.length ? path[path.length - 1] : undefined - } - return undefined + setId(id) { + console.debug("Set Game ID", id) + if (id) + history.replaceState(null, "", "?id=" + id) + this.id = id + return this } - getOpponentsName(myId) { - let opponent = this.players.filter(x => x.id !== myId)[0] - console.debug("getOpponentsName()", opponent.name) - return opponent.name + setTurn (player_id) { + console.debug("Set Game Turn", player_id) + this.turn = player_id + return this + } + getOpponent() { + let player_id = this.getCookie("player_id") + return this.player1.id == player_id ? this.player2 : this.player1 } - setOpponentsTurn(myId) { - let opponent = this.players.filter(x => x.id !== myId)[0] - console.debug("setOpponentsTurn()", opponent.id) - this.turn = opponent.id + setOpponentsTurn() { + let opponent = this.getOpponent() + this.setTurn(opponent.id) return this } + logResult(winnersName) { + this.winners.push(winnersName) + } } \ No newline at end of file diff --git a/src/index.js b/src/index.js index b6a14ab..af213d0 100644 --- a/src/index.js +++ b/src/index.js @@ -3,16 +3,7 @@ import {Player, Game} from "./classes.js" import * as HTTP from "./services.js" import style from './style.scss' - -let conn -let gameOver = false -let player = new Player() -player.loadFromCookies() -player.setCookies() -let game = new Game(player) - -console.debug(player) -console.debug(game) +import { join } from "path"; /** * Initialize DOM variables @@ -21,32 +12,57 @@ let name = document.getElementById('name') let nameLabel = document.getElementById('nameLabel') let playerH1 = document.getElementById('player') let status = document.getElementById('status') -let waiting = document.getElementById('waiting') -let turn = document.getElementById('turn') -let winner = document.getElementById('winner') -let draw = document.getElementById('draw') let gameTable = document.getElementById('gameTable') let instructions = document.getElementById('instructions') -let input = document.getElementById('shareLink') +let shareLink = document.getElementById('shareLink') let tooltip = document.getElementById("tooltip") let startGameForm = document.getElementById('startGameForm') let joinGameForm = document.getElementById('joinGameForm') let opponentTileColor = "#992222" let tileColor = "#229922" +let gameOver = false +let firstgame = true -/** - * Setup - */ -function _setup() { - if (player.getName()) { - name.value = player.getName() - name.classList.add("hide") - nameLabel.classList.add("hide") - playerH1.innerText = "Hi " + player.getName() - playerH1.classList.remove("hide") - } +let conn +let player = new Player() +console.debug(player) +if (player.getName()) { + name.value = player.getName() + _hideConfig() + _showGreeting() +} + +let game = new Game() +console.debug(game) +if (game.getId()) { + firstgame = false + // we need to fetch the game data and resume the game + _retrieveGameFromServer().then(resp => { + console.debug("_retrieveGameFromServer() success", resp) + game.player1 = new Player(resp.player1.id, resp.player1.name) + game.turn = resp.turn + game.matrix = resp.matrix + if (!resp.player2 || typeof resp.player2 === "undefined") { + _updateGameOnServer({ + player2: player + }).then(resp => { + console.debug("_updateGame() success", resp) + console.debug(game) + }).catch(err => { + console.debug("_updateGame() err", err) + }) + } else { + game.player2 = new Player(resp.player2.id, resp.player2.name) + } + if (document.location.pathname != "/join") { + _renderGame() + _showGame() + } + console.debug(game) + }).catch(err => { + console.debug("_retrieveGameFromServer() error", err) + }) } -_setup() export function Copy (context) { @@ -61,7 +77,7 @@ export function TooltipBlur () { if (window.WebSocket) { - conn = new WebSocket("wss://" + document.location.host + "/ws") + conn = new WebSocket("ws://" + document.location.host + "/ws") conn.onclose = function (evt) { console.debug("Websocket Closed") } @@ -75,52 +91,49 @@ if (window.WebSocket) { console.error("Error parsing", data) } console.debug("Message", data) - if (data.sender === player.getId()) { - console.debug("My own message received and ignored") + if (data.sender.toUpperCase() === player.getId().toUpperCase()) { + // console.debug("My own message received and ignored") + return + } + if (data.game_id.toUpperCase() !== game.getId().toUpperCase()) { + // console.debug("Not my game") return } switch(data.event) { case "joining": console.debug("Event: joining") instructions.classList.add("hide") - game.players.push(data.player) - console.debug(game) - _yourTurn() + _safeRetrieve() _showGame() break + case "new": + console.debug("Event: new") + let newGame = confirm("Would you like to play again?") + if (newGame) { + history.replaceState(null, "", "?id=" + data.new_game_id) + game.setId(data.new_game_id) + _retrieveGameFromServer().then(resp => { + console.debug("_retrieveGameFromServer() success", resp) + game.player1 = new Player(resp.player1.id, resp.player1.name) + game.player2 = new Player(resp.player2.id, resp.player2.name) + game.matrix = resp.matrix + game.turn = resp.turn + console.debug(game) + gameOver = false + _renderGame() + }).catch(err => { + console.debug("_retrieveGameFromServer() error", err) + }) + } + break case "move": console.debug("Event: move") - game.matrix[data.index] = data.player - _updateTiles(data.index) - _yourTurn() - console.debug(game.matrix) + _safeRetrieve() break case "winner": console.debug("Event: winner") - game.matrix[data.index] = data.player - _updateTiles(data.index) - gameOver = true - status.classList.add("hide") - turn.classList.add("hide") - winner.innerText = "You lose... " + game.getOpponentsName(player.getId()) + " Wins!" - winner.classList.remove("hide") - _highlightBoard(data.positions) - _dimBoard() - if (startGameForm) - startGameForm.classList.remove("hide") - break - case "draw": - console.debug("Event: draw") - game.matrix[data.index] = data.player - _updateTiles(data.index) - gameOver = true - status.classList.add("hide") - turn.classList.add("hide") - winner.innerText = "Its a draw!" - winner.classList.remove("hide") - _dimBoard() - if (startGameForm) - startGameForm.classList.remove("hide") + game.winner = data.sender + _safeRetrieve() break } } @@ -138,24 +151,38 @@ if (startGameForm) { if (!_validateForm()) { return false } - _createGame().then(resp => { - name.classList.add("hide") - nameLabel.classList.add("hide") - startGameForm.classList.add("hide") - console.debug("_createGame() success", resp) - game.turn = resp.turn - game.matrix = resp.matrix - console.debug("Game:", game) - input.value = _getUrl() + "/join/" + game.getId() - instructions.classList.remove("hide") - _waiting() - // _yourTurn() - // _showGame() - }).catch(err => { - console.debug("_createGame() error", err) - status.innerText = err.message.error - status.classList.remove("hide") - }) + if (firstgame) { + _safeCreate() + firstgame = false + } else { + _createGame().then(resp => { + console.debug("_createGame() success", resp) + history.replaceState(null, "", "?id=" + resp.id) + let old_game_id = game.getId() + game.setId(resp.id) + _updateGameOnServer({ + player2: game.player2, + turn: game.player1.id == game.winner ? game.player2.id : game.player1.id, + previous_game: old_game_id + }).then(resp => { + console.debug("_updateGameOnServer() success", resp) + gameOver = false + game.turn = resp.turn + game.matrix = resp.matrix + conn.send(JSON.stringify({ + sender: player.getId(), + game_id: old_game_id, + event: "new", + new_game_id: resp.id + })) + _renderGame() + }).catch(err => { + console.debug("_updateGameOnServer() err", err) + }) + }).catch(err => { + console.debug("_createGame() err", err) + }) + } }) } if (joinGameForm) { @@ -164,171 +191,188 @@ if (joinGameForm) { if (!_validateForm()) { return false } - _addPlayer().then(resp => { - name.classList.add("hide") - nameLabel.classList.add("hide") - joinGameForm.classList.add("hide") - console.debug("_addPlayer() success", resp) - conn.send(JSON.stringify({ - sender: player.getId(), - game_id: game.getId(), - event: "joining", - player: { - id: player.getId(), - name: player.getName() - } - })) - game.players.push(new Player(resp.players[0].id, resp.players[0].name)) - _theirTurn() - _showGame() - }).catch(err => { - console.debug("_addPlayer() error", err) - status.innerText = err.message.error - status.classList.remove("hide") - }) + conn.send(JSON.stringify({ + sender: player.getId(), + game_id: game.getId(), + event: "joining" + })) + joinGameForm.classList.add("hide") + _theirTurn() + _showGame() }) } -if (gameTable) { - document.querySelectorAll('.tile').forEach(element => { - element.addEventListener('click', event => { - if (gameOver) { - console.debug("Game over") - event.preventDefault() - return - } - let pos = event.target.id.split('_')[1] - // validate its my turn - if (game.turn !== player.getId()) { - console.debug("Not my turn") - event.preventDefault() - return - } - // validate position available - if (game.matrix[pos]) { - console.debug("Tile not free") - event.preventDefault() - return - } - // set move - game.matrix[pos] = player.getId() - - // show tile selected - event.target.style.backgroundColor = tileColor - - // calculate if 3 tiles in a row - let three = _threeInARow() - if (three) { - console.debug("You win!") - _highlightBoard(three) - _dimBoard() - gameOver = true - winner.innerText = "You Win!!!" - winner.classList.remove("hide") - status.classList.add("hide") - turn.classList.add("hide") - conn.send(JSON.stringify({ - sender: player.getId(), - game_id: game.getId(), - event: "winner", - index: pos, - player: player.getId(), - winner: player.getId(), - positions: three - })) - if (startGameForm) - startGameForm.classList.remove("hide") - event.preventDefault() - return - } - - if (_draw()) { - console.debug("Draw!") - _dimBoard() - gameOver = true - winner.innerText = "Its a draw!" - winner.classList.remove("hide") - status.classList.add("hide") - turn.classList.add("hide") - conn.send(JSON.stringify({ - sender: player.getId(), - game_id: game.getId(), - event: "draw", - index: pos, - player: player.getId(), - winner: player.getId() - })) - if (startGameForm) - startGameForm.classList.remove("hide") - event.preventDefault() - return - } +function tileListener (event) { + if (gameOver) { + event.preventDefault() + return false + } + let pos = event.target.id.split('_')[1] + // validate its my turn + if (game.turn !== player.getId()) { + console.debug("Not my turn") + event.preventDefault() + return + } + // validate position available + if (game.matrix[pos]) { + console.debug("Tile not free") + event.preventDefault() + return + } + // set move + game.matrix[pos] = player.getId() - // send move via socket - conn.send(JSON.stringify({ - sender: player.getId(), - game_id: game.getId(), - event: "move", - index: pos, - player: player.getId() - })) + // calculate if 3 tiles in a row + let [done, winner, positions] = _threeInARow() - _theirTurn() - }) + _updateGameOnServer({ + id: game.getId(), + player1: game.player1, + player2: game.player2, + turn: game.player1.id == game.turn ? game.player2.id : game.player1.id, + winner: winner, + matrix: game.matrix + }).then(resp => { + console.debug("_updateGameOnServer() success", resp) + conn.send(JSON.stringify({ + sender: player.getId(), + game_id: game.getId(), + event: done ? "winner" : "move" + })) + game.turn = resp.turn + _renderGame() + }).catch(err => { + console.debug("_updateGameOnServer() error", err) + }) +} +if (gameTable) { + document.querySelectorAll('.tile').forEach(element => { + element.addEventListener('click', tileListener) }) } /** * END Document Listeners */ - function _validateForm() { if (!name.value) { status.innerText = "Name is required." - status.classList.remove("hide") + status.style.color = "#FF0000" return false } + status.style.color = "#000000" player.setName(name.value) - player.setCookies() - status.classList.add("hide") - _greeting() + _hideConfig() + _showGreeting() return true } -function _getUrl() { - return document.location.protocol + '//' + document.location.host + +function _showInstructions() { + shareLink.value = _getUrl() + "/join?id=" + game.getId() + instructions.classList.remove("hide") +} +function _hideInstructions () { + instructions.classList.add("hide") } -function _greeting() { +function _showGreeting() { if (player.getName()) { playerH1.innerText = "Hi " + player.getName() playerH1.classList.remove("hide") } } -function _createGame() { - let url = _getUrl() - return HTTP.POST(`${url}/game`, JSON.stringify(game)) +function _showGame () { + gameTable.classList.remove("hide") +} +function _resumeGame () { + startGameForm.classList.add("hide") + _showGame() } -function _addPlayer() { +function _hideConfig () { + name.classList.add("hide") + nameLabel.classList.add("hide") +} + +function _renderGame() { + console.debug("Render Game Board") + _dimBoard(true) + for (let i = 0; i < game.matrix.length; i++) { + let playerAt = game.matrix + if (playerAt[i] === player.getId()) { + document.getElementById('pos_' + i).style.backgroundColor = tileColor + } else if (playerAt[i] === game.getOpponent().getId()) { + document.getElementById('pos_' + i).style.backgroundColor = opponentTileColor + } else { + document.getElementById('pos_' + i).style.backgroundColor = "unset" + } + } + if (game.turn == player.getId()) { + _yourTurn() + } else { + _theirTurn() + } + let [done, winner, positions] = _threeInARow() + if (done) { + gameOver = true + game.winner = winner + _dimBoard() + _highlightBoard(positions) + if (winner == player.getId()) { + status.innerText = "You Win!!!" + } else { + status.innerText = "You lose... " + game.getOpponent().getName() + " Wins!" + } + } + if (_draw()) { + gameOver = true + _dimBoard() + status.innerText = "Its a draw!" + } +} + +function _getUrl () { + return document.location.protocol + '//' + document.location.host +} +function _safeCreate() { + _createGame().then(resp => { + console.debug("_createGame() success", resp) + game.setId(resp.id) + game.player1 = new Player(resp.player1.id, resp.player1.name) + console.debug(game) + _showInstructions() + }).catch(err => { + console.debug("_createGame() err", err) + }) +} +function _createGame () { let url = _getUrl() - let gid = game.getId() - let pid = player.getId() - return HTTP.POST(`${url}/game/${gid}/player/${pid}`, JSON.stringify({ name: document.getElementById('name').value })) + return HTTP.POST(`${url}/game`, JSON.stringify({ player1: player })) } -function _showGame() { - gameTable.classList.remove("hide") +function _updateGameOnServer(updatePayload) { + let url = _getUrl() + "/game/" + game.getId() + return HTTP.POST(url, JSON.stringify(updatePayload)) +} +function _safeRetrieve() { + _retrieveGameFromServer().then(resp => { + console.debug("_retrieveGameFromServer() success", resp) + game.player1 = new Player(resp.player1.id, resp.player1.name) + game.player2 = new Player(resp.player2.id, resp.player2.name) + game.matrix = resp.matrix || [null, null, null, null, null, null, null, null, null] + game.turn = resp.turn + _renderGame() + console.debug(game) + }).catch(err => { + console.debug("_retrieveGameFromServer() error", err) + }) } -function _waiting() { - waiting.innerText = "Waiting for opponent" - waiting.classList.remove("hide") +function _retrieveGameFromServer() { + let url = _getUrl() + "/game/" + game.getId() + return HTTP.GET(url) } function _yourTurn () { - if (waiting) - waiting.classList.add("hide") - turn.innerText = "Your Turn" - turn.classList.remove("hide") + status.innerText = "Your Turn" game.turn = player.getId() } function _theirTurn () { - game.setOpponentsTurn(player.getId()) - turn.innerText = _possessivizer(game.getOpponentsName(player.getId())) + " Turn" - turn.classList.remove("hide") + status.innerText = _possessivizer(game.getOpponent().getName()) + " Turn" } function _possessivizer(name) { if (name.charAt(name.length - 1) === "s") { @@ -337,28 +381,25 @@ function _possessivizer(name) { return name + "'s" } } -function _updateTiles(index) { - document.getElementById('pos_' + index).style.backgroundColor = opponentTileColor -} function _threeInARow() { for (let i = 0; i <= 8; i) { if (game.matrix[i] && (game.matrix[i] === game.matrix[i + 1] && game.matrix[i] === game.matrix[i + 2]) ) { - return [i, i + 1, i + 2] + return [true, game.matrix[i], [i, i + 1, i + 2]] } i = i + 3 } for (let i = 0; i <= 2; i++) { if (game.matrix[i] && (game.matrix[i] === game.matrix[i + 3] && game.matrix[i] === game.matrix[i + 6]) ) { - return [i, i + 3, i + 6] + return [true, game.matrix[i], [i, i + 3, i + 6]] } } if (game.matrix[0] && (game.matrix[0] === game.matrix[4] && game.matrix[0] === game.matrix[8])) { - return [0, 4, 8] + return [true, game.matrix[0], [0, 4, 8]] } if (game.matrix[2] && (game.matrix[2] === game.matrix[4] && game.matrix[2] === game.matrix[6])) { - return [2, 4, 6] + return [true, game.matrix[2], [2, 4, 6]] } - return false + return [false, null, null] } function _draw() { for (let i = 0; i < game.matrix.length; i++) { @@ -368,10 +409,14 @@ function _draw() { } return true } -function _dimBoard() { - document.querySelectorAll('td').forEach(el => el.classList.add("dim")) +function _dimBoard(reverse) { + if (reverse) { + document.querySelectorAll('td').forEach(el => el.classList.remove("dim")) + document.querySelectorAll('td').forEach(el => el.classList.remove("highlight")) + } else { + document.querySelectorAll('td').forEach(el => el.classList.add("dim")) + } } - function _highlightBoard (positions) { for (let pos of positions) { document.querySelector('#pos_' + pos).classList.add("highlight") diff --git a/src/services.js b/src/services.js index baba0b5..4558475 100644 --- a/src/services.js +++ b/src/services.js @@ -1,14 +1,19 @@ 'use strict' // GET HTTP call -export function GET (theUrl, callback) { - var req = new XMLHttpRequest() - req.onreadystatechange = function () { - if (req.readyState == 4 && req.status == 200) - callback(req.responseText) - } - req.open("GET", theUrl, true) - req.send(null) +export function GET (theUrl) { + return new Promise((resolve, reject) => { + var req = new XMLHttpRequest() + req.onreadystatechange = function () { + if (req.readyState == 4 && req.status == 200) { + resolve(_parseOrNot(req.responseText)) + } else if (req.readyState == 4) { + reject({ status: req.status, message: _parseOrNot(req.responseText) }) + } + } + req.open("GET", theUrl, true) + req.send(null) + }) } // POST HTTP call diff --git a/src/style.scss b/src/style.scss index f0a9fdc..03d2176 100644 --- a/src/style.scss +++ b/src/style.scss @@ -1,31 +1,48 @@ @import url('https://fonts.googleapis.com/css?family=Lato'); +body { + font-family: 'Lato', sans-serif; +} + +h1 { + font: normal normal normal 32px/40px 'Lato', sans-serif; +} +h2 { + font: normal normal normal 24px/30px 'Lato', sans-serif; +} +.record { + font: normal normal normal 16px/30px 'Lato', sans-serif; + #log, #inprogress { + font-size: 10px; + } +} +form { + padding-top: 20px; + input#name { + font: normal normal normal 14px/30px 'Lato', sans-serif; + height: 30px; + display: block; + } + button#start, button#join { + font: normal normal normal 14px/30px 'Lato', sans-serif; + margin: 20px 0; + height: 30px; + background: rgb(77, 22, 228); + border: none; + border-radius: 2px; + color: white; + } +} input#shareLink { font-family: monospace; cursor: pointer; width: 400px; } -span { - &#copySuccess { - display: none; - color: green; - font-weight: bold; - } - &#copyError { - display: none; - color: red; - font-weight: bold; - } -} .link { color: blue; } #status { - font: normal normal normal 16px/20px 'Lato', sans-serif; - color: red; -} -#turn, #waiting { - font: normal normal normal 16px/20px 'Lato', sans-serif; + font: normal normal bold 16px/20px 'Lato', sans-serif; } #gameTable { tr { @@ -57,7 +74,7 @@ span { } .hide { - display: none; + display: none !important; } .tooltip { diff --git a/structs.go b/structs.go deleted file mode 100644 index 229ad50..0000000 --- a/structs.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - uuid "github.com/satori/go.uuid" -) - -// Game object for binding with JSON POST body -type Game struct { - UUID uuid.UUID `json:"id" binding:"required"` - Players []*Player `json:"players"` - Turn *uuid.UUID `json:"turn"` - Draw *bool `json:"draw,omitempty"` - Winner *uuid.UUID `json:"winner,omitempty"` - Matrix [9]*uuid.UUID `json:"matrix" binding:"min=9,max=9"` -} - -// Player object for binding with JSON POST body -type Player struct { - UUID *uuid.UUID `json:"id"` - Name string `json:"name,omitempty"` -} diff --git a/tictactoe-api b/tictactoe-api index 485e9e3..b7359cf 100755 Binary files a/tictactoe-api and b/tictactoe-api differ