Skip to content

Instantly share code, notes, and snippets.

@guybrush
Created April 20, 2015 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guybrush/c4bfc9e6261d515a049c to your computer and use it in GitHub Desktop.
Save guybrush/c4bfc9e6261d515a049c to your computer and use it in GitHub Desktop.
var SH = require('signalhub')
var sp = require('simple-peer')
var hat = require('hat')
var localGameId
var localPlayerId = 'player'+hat()
var games = {}
var elCreateGame = document.createElement('button')
document.body.appendChild(elCreateGame)
elCreateGame.innerHTML = 'create game'
var elGames = document.createElement('div')
document.body.appendChild(elGames)
elCreateGame.addEventListener('click',createGame)
var elLog = document.createElement('pre')
document.body.appendChild(elLog)
// function log(){elLog.innerHTML += [].slice.call(arguments)+'\n'}
var log = console.log
var sh = SH('http://signalhub.mafintosh.com','towewarz')
var shListgames = sh.subscribe('listgames')
var shGame = sh.subscribe('game')
var shPeer = sh.subscribe('peer')
shListgames.on('error',function(d){log('error:listgames->',d)})
shGame .on('error',function(d){log('error:game->',d)})
shPeer .on('error',function(d){log('error:peer->',d)})
shListgames.on('data',function(d){log('data:listgames->',d)})
shGame .on('data',function(d){log('data:game->',d)})
shPeer .on('data',function(d){log('data:peer->',d)})
shListgames.on('data',function(d){
if (localGameId) sh.broadcast('game',localGameId)
})
var shListGames = sh.subscribe('listgames')
var shPeer = sh.subscribe('peer')
var shGame = sh.subscribe('game')
log('starting')
sh.broadcast('list-games',name)
function createGame() {
var g = new Game()
inGame = g.id
g.addPlayer(name)
addGame(g)
sh.broadcast('game',games[inGame])
}
function addGame(g) {
games[g.id] = g
elGames.appendChild(g.el)
}
function Game(id) {
this.id = id || hat()
this.el = document.createElement('div')
this.el.className = 'game'
this.el.dataset.id = this.id
this.elId = document.createElement('div')
this.elId.className = 'id'
this.elId.innerHTML = this.id
this.elPlayers = document.createElement('div')
this.elPlayers.className = 'players'
this.el.appendChild(this.elId)
this.el.appendChild(this.elPlayers)
}
Game.prototype.addPlayer = function(name) {
var el = this.el.querySelector('.player[data-name="'+name+'"]')
if (el) return console.error('player already exists')
el = document.createElement('div')
el.className = 'player'
el.dataset.name = name
el.innerHTML = name
this.el.appendChild(el)
}
Game.prototype.removePlayer = function(name) {
}
Game.prototype.toJSON = function() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment