SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Create online games with
node.js and socket.io
Disclaimer
Agenda
• Example 1: a simple MMOCPG
Massively Multiplayer Online Click-Playing Game
by Krasimir Tsonev
• Example 2: a Connect 4 game
Adaptations for a 2-Player Game
by Gérard Tyedmers
• Various
• Beer
History: From Word to Web
• Am Anfang war das Word
History: From Word to Web
• HTML5 WebApp
Online Game
with NodeJS and Socket.io
• by Krasimir Tsonev
• http://krasimirtsonev.com/blog/article/Real-
time-chat-with-NodeJS-Socketio-and-
ExpressJS
Install Node and Modules
• Get Node.js from nodejs.org
• node-v0.10.26-x64
• Socket.io for real time communication
• moniker to generate random names
Install Node and Modules
• Create File „package.json“:
{
"name": "SocketioExample",
"version": "0.0.1",
"description": "SocketioExample",
"dependencies": {
"socket.io": "0.9.16",
"moniker": "0.1.2"
},
"author": "dev"
}
• Run „npm install“ in the diretory of your file
Structure of the game
index.js - Server
page.html - Client
Structure of the game
index.js - Server
• connection
• disconnect
• click
page.html - Client
Structure of the game
index.js - Server
• connection cerate user, add user to users
• disconnect remove user from users
• click add 1 point, broadcast to users
page.html - Client
Structure of the game
index.js - Server
• connection cerate user, add user to users
• disconnect remove user from users
• click add 1 point, broadcast to users
page.html - Client
• HTML containers
• Script
Structure of the game
page.html
• HTML containers
– Welcome Message
– Progress Bar (clickable)
– Users List
• Script
– Connect to Server
– Get Welcome Message
– Get Users List
– Send Click
– Get Progress
Structure of the game
• Client: var socket = io.connect('http://localhost:3250');
• Server: io.sockets.on('connection', function (socket) {
• Client: progress.onclick = function() { socket.emit("click");
• Server: socket.on("click", function() {
• Server: io.sockets.emit("update", {currWidth: currWidth});
• Client: socket.on('update', function (data) {
page.html
<!DOCTYPE html>
<html>
<head>
<title>Real time game</title>
<style type="text/css"> ... styles here… </style>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
... game logic here …
</script>
</head>
page.html
<body class="main">
<div id="welcome"></div>
<hr />
<div id="progress"></div>
<div id="win">150</div>
<hr />
<div id="users"></div>
<hr />
<div id="results">
</div>
</body>
</html>
page.html
window.onload = function() {
var welcome = document.getElementById("welcome");
var allUsers = document.getElementById("users");
var progress = document.getElementById("progress");
var results = document.getElementById("results");
var socket = io.connect('http://localhost:3250');
page.html
socket.on('welcome', function (data) { console.log(data);
welcome.innerHTML = "Welcome to the game <strong>" +
data.name + "</strong>„; });
socket.on('users', function (data) { allUsers.innerHTML =
"<strong>Users:</strong> " + data.users; });
socket.on('update', function (data) { progress.innerHTML =
data.currentWidth; progress.style.width =
parseInt(data.currentWidth) + "px"; });
socket.on('win', function (data) { results.innerHTML =
data.message; });
progress.onclick = function() { socket.emit("click"); } }
index.js
var handler = function(req, res) {
fs.readFile('./page.html', function (err, data) {
if(err) throw err;
res.writeHead(200);
res.end(data);
});
}
index.js
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var Moniker = require('moniker');
var port = 3250;
app.listen(port);
index.js
io.sockets.on('connection', function (socket) {
var user = addUser();
updateWidth();
socket.emit("welcome", user);
socket.on('disconnect', function () {
removeUser(user);
});
socket.on("click", function() {
…
});
});
index.js
socket.on("click", function() {
currentWidth += 1;
user.clicks += 1;
if(currentWidth == winWidth) {
currentWidth = initialWidth;
io.sockets.emit("win", { message: "<strong>" +
user.name + "</strong> rocks!" });
}
updateWidth();
updateUsers();
});
});
index.js
var initialWidth = 20;
var currentWidth = initialWidth;
var winWidth = 150;
var users = [];
var addUser = function() {
var user = { name: Moniker.choose(), clicks: 0 }
users.push(user);
updateUsers();
return user;
}
index.js
var removeUser = function(user) {
for(var i=0; i<users.length; i++) {
if(user.name === users[i].name) { users.splice(i, 1);
updateUsers(); return; }
}
}
index.js
var updateUsers = function() {
var str = '';
for(var i=0; i<users.length; i++) {
var user = users[i];
str += user.name + ' <small>(' + user.clicks + '
clicks)</small> ';
}
io.sockets.emit("users", { users: str });
}
var updateWidth = function() {
io.sockets.emit("update", { currentWidth: currentWidth });
}
Online Connect 4
with NodeJS and Socket.io
• by Gérard Tyedmers
• grrd01.github.io/4inaRow/
Strucure of the game
HTML Click Result
• One server
• One game
• Same screen/result for all
• Broadcasting to all
Strucure of the game
HTML Click
HTML
Click
Result
Result
Result
WaitClick
Connecting
• <script src="/socket.io/socket.io.js"></script>
• var socket = io.connect('http://localhost:3250');
Connecting
• <script src="/socket.io/socket.io.js"></script>
• var socket = io.connect('http://localhost:3250');
• <script type="text/javascript"
src="http://grrds4inarow.nodejitsu.com:80/socket.io
/socket.io.js"></script>
• var socket =
io.connect('http://grrds4inarow.nodejitsu.com:80');
• socket.disconnect();
• socket.socket.reconnect();
Starting Games
var startgame = function(user) {
for(var i=0; i<users.length; i++) {
if (i == users.length-1) { // kein freier Gegner
io.sockets.socket(users[i].id).emit("connect", users[i]);
} else { // Gegner vorhanden
if (users[i].opponent == null) {
users[i].opponent = users[users.length-1].id;
users[i].role = "0";
io.sockets.socket(users[i].id).emit("startgame", users[i]);
users[users.length-1].opponent = users[i].id;
users[users.length-1].role = "1";
io.sockets.socket(users[users.length-1].id)
.emit("startgame",users[users.length-1]);
break;
} } } }
Playing
Sender
socket.emit('playsend', {to: user.opponent,col: spaltenr, round:
countround});
Server
socket.on("playsend", function (data) {
io.sockets.socket(data.to).emit("playget", data);
});
Reciever
socket.on('playget', function (data) {
if (countround == data.round && lastround != data.round) {
lastround = data.round;
spielzug(data.col);
}
});
Host your app
• http://localhost
• your own web-server
• node.js hoster
https://www.nodejitsu.com/

Weitere ähnliche Inhalte

Was ist angesagt?

PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
Cache is King - RubyHACK 2019
Cache is King - RubyHACK 2019Cache is King - RubyHACK 2019
Cache is King - RubyHACK 2019Molly Struve
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
HTML5 Games with CreateJS
HTML5 Games with CreateJSHTML5 Games with CreateJS
HTML5 Games with CreateJSDave Kelleher
 
watchOS 2でゲーム作ってみた話
watchOS 2でゲーム作ってみた話watchOS 2でゲーム作ってみた話
watchOS 2でゲーム作ってみた話Kohki Miki
 
20141011 mastering mysqlnd
20141011 mastering mysqlnd20141011 mastering mysqlnd
20141011 mastering mysqlnddo_aki
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the CloudJames Thomas
 
2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQLHung-yu Lin
 
smartdc by Ruby
smartdc by Rubysmartdc by Ruby
smartdc by Rubyogom_
 
Firebase not really_yohoho
Firebase not really_yohohoFirebase not really_yohoho
Firebase not really_yohohoDA-14
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessionsUdaAs PaNchi
 

Was ist angesagt? (20)

PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Cache is King - RubyHACK 2019
Cache is King - RubyHACK 2019Cache is King - RubyHACK 2019
Cache is King - RubyHACK 2019
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
Cookie and session
Cookie and sessionCookie and session
Cookie and session
 
Browser based games
Browser based gamesBrowser based games
Browser based games
 
Introduction to php web programming - sessions and cookies
Introduction to php   web programming - sessions and cookiesIntroduction to php   web programming - sessions and cookies
Introduction to php web programming - sessions and cookies
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
HTML5 Games with CreateJS
HTML5 Games with CreateJSHTML5 Games with CreateJS
HTML5 Games with CreateJS
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
watchOS 2でゲーム作ってみた話
watchOS 2でゲーム作ってみた話watchOS 2でゲーム作ってみた話
watchOS 2でゲーム作ってみた話
 
20141011 mastering mysqlnd
20141011 mastering mysqlnd20141011 mastering mysqlnd
20141011 mastering mysqlnd
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the Cloud
 
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
Sessions in php
Sessions in php Sessions in php
Sessions in php
 
java Cookies
java Cookiesjava Cookies
java Cookies
 
2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL2014 database - course 3 - PHP and MySQL
2014 database - course 3 - PHP and MySQL
 
smartdc by Ruby
smartdc by Rubysmartdc by Ruby
smartdc by Ruby
 
Firebase not really_yohoho
Firebase not really_yohohoFirebase not really_yohoho
Firebase not really_yohoho
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 

Ähnlich wie Create online games with node.js and socket.io

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Pushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTCPushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTCRich Waters
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioCaesar Chi
 
Every Click Counts (But All the Money Goes to Me)
Every Click Counts (But All the Money Goes to Me)Every Click Counts (But All the Money Goes to Me)
Every Click Counts (But All the Money Goes to Me)Avast
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Arduino and the real time web
Arduino and the real time webArduino and the real time web
Arduino and the real time webAndrew Fisher
 
Ember.js Tokyo event 2014/09/22 (English)
Ember.js Tokyo event 2014/09/22 (English)Ember.js Tokyo event 2014/09/22 (English)
Ember.js Tokyo event 2014/09/22 (English)Yuki Shimada
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensionserwanl
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wyciekówKonrad Kokosa
 
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJSAprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJSLoiane Groner
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websocketsWim Godden
 
Drive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerDrive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerVodqaBLR
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés RianchoCODE BLUE
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with WingsRemy Sharp
 

Ähnlich wie Create online games with node.js and socket.io (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Pushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTCPushing the Boundaries of Sencha and HTML5′s WebRTC
Pushing the Boundaries of Sencha and HTML5′s WebRTC
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
 
Node azure
Node azureNode azure
Node azure
 
Every Click Counts (But All the Money Goes to Me)
Every Click Counts (But All the Money Goes to Me)Every Click Counts (But All the Money Goes to Me)
Every Click Counts (But All the Money Goes to Me)
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Arduino and the real time web
Arduino and the real time webArduino and the real time web
Arduino and the real time web
 
Ember.js Tokyo event 2014/09/22 (English)
Ember.js Tokyo event 2014/09/22 (English)Ember.js Tokyo event 2014/09/22 (English)
Ember.js Tokyo event 2014/09/22 (English)
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 
A miało być tak... bez wycieków
A miało być tak... bez wyciekówA miało być tak... bez wycieków
A miało być tak... bez wycieków
 
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJSAprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
5.node js
5.node js5.node js
5.node js
 
Ext JS Introduction
Ext JS IntroductionExt JS Introduction
Ext JS Introduction
 
Drive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteerDrive chrome(headless) with puppeteer
Drive chrome(headless) with puppeteer
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 

Kürzlich hochgeladen

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 

Kürzlich hochgeladen (20)

AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 

Create online games with node.js and socket.io

  • 1. Create online games with node.js and socket.io
  • 3. Agenda • Example 1: a simple MMOCPG Massively Multiplayer Online Click-Playing Game by Krasimir Tsonev • Example 2: a Connect 4 game Adaptations for a 2-Player Game by Gérard Tyedmers • Various • Beer
  • 4. History: From Word to Web • Am Anfang war das Word
  • 5. History: From Word to Web • HTML5 WebApp
  • 6. Online Game with NodeJS and Socket.io • by Krasimir Tsonev • http://krasimirtsonev.com/blog/article/Real- time-chat-with-NodeJS-Socketio-and- ExpressJS
  • 7. Install Node and Modules • Get Node.js from nodejs.org • node-v0.10.26-x64 • Socket.io for real time communication • moniker to generate random names
  • 8. Install Node and Modules • Create File „package.json“: { "name": "SocketioExample", "version": "0.0.1", "description": "SocketioExample", "dependencies": { "socket.io": "0.9.16", "moniker": "0.1.2" }, "author": "dev" } • Run „npm install“ in the diretory of your file
  • 9. Structure of the game index.js - Server page.html - Client
  • 10. Structure of the game index.js - Server • connection • disconnect • click page.html - Client
  • 11. Structure of the game index.js - Server • connection cerate user, add user to users • disconnect remove user from users • click add 1 point, broadcast to users page.html - Client
  • 12. Structure of the game index.js - Server • connection cerate user, add user to users • disconnect remove user from users • click add 1 point, broadcast to users page.html - Client • HTML containers • Script
  • 13. Structure of the game page.html • HTML containers – Welcome Message – Progress Bar (clickable) – Users List • Script – Connect to Server – Get Welcome Message – Get Users List – Send Click – Get Progress
  • 14. Structure of the game • Client: var socket = io.connect('http://localhost:3250'); • Server: io.sockets.on('connection', function (socket) { • Client: progress.onclick = function() { socket.emit("click"); • Server: socket.on("click", function() { • Server: io.sockets.emit("update", {currWidth: currWidth}); • Client: socket.on('update', function (data) {
  • 15. page.html <!DOCTYPE html> <html> <head> <title>Real time game</title> <style type="text/css"> ... styles here… </style> <script src="/socket.io/socket.io.js"></script> <script type="text/javascript"> ... game logic here … </script> </head>
  • 16. page.html <body class="main"> <div id="welcome"></div> <hr /> <div id="progress"></div> <div id="win">150</div> <hr /> <div id="users"></div> <hr /> <div id="results"> </div> </body> </html>
  • 17. page.html window.onload = function() { var welcome = document.getElementById("welcome"); var allUsers = document.getElementById("users"); var progress = document.getElementById("progress"); var results = document.getElementById("results"); var socket = io.connect('http://localhost:3250');
  • 18. page.html socket.on('welcome', function (data) { console.log(data); welcome.innerHTML = "Welcome to the game <strong>" + data.name + "</strong>„; }); socket.on('users', function (data) { allUsers.innerHTML = "<strong>Users:</strong> " + data.users; }); socket.on('update', function (data) { progress.innerHTML = data.currentWidth; progress.style.width = parseInt(data.currentWidth) + "px"; }); socket.on('win', function (data) { results.innerHTML = data.message; }); progress.onclick = function() { socket.emit("click"); } }
  • 19. index.js var handler = function(req, res) { fs.readFile('./page.html', function (err, data) { if(err) throw err; res.writeHead(200); res.end(data); }); }
  • 20. index.js var app = require('http').createServer(handler); var io = require('socket.io').listen(app); var fs = require('fs'); var Moniker = require('moniker'); var port = 3250; app.listen(port);
  • 21. index.js io.sockets.on('connection', function (socket) { var user = addUser(); updateWidth(); socket.emit("welcome", user); socket.on('disconnect', function () { removeUser(user); }); socket.on("click", function() { … }); });
  • 22. index.js socket.on("click", function() { currentWidth += 1; user.clicks += 1; if(currentWidth == winWidth) { currentWidth = initialWidth; io.sockets.emit("win", { message: "<strong>" + user.name + "</strong> rocks!" }); } updateWidth(); updateUsers(); }); });
  • 23. index.js var initialWidth = 20; var currentWidth = initialWidth; var winWidth = 150; var users = []; var addUser = function() { var user = { name: Moniker.choose(), clicks: 0 } users.push(user); updateUsers(); return user; }
  • 24. index.js var removeUser = function(user) { for(var i=0; i<users.length; i++) { if(user.name === users[i].name) { users.splice(i, 1); updateUsers(); return; } } }
  • 25. index.js var updateUsers = function() { var str = ''; for(var i=0; i<users.length; i++) { var user = users[i]; str += user.name + ' <small>(' + user.clicks + ' clicks)</small> '; } io.sockets.emit("users", { users: str }); } var updateWidth = function() { io.sockets.emit("update", { currentWidth: currentWidth }); }
  • 26. Online Connect 4 with NodeJS and Socket.io • by Gérard Tyedmers • grrd01.github.io/4inaRow/
  • 27. Strucure of the game HTML Click Result • One server • One game • Same screen/result for all • Broadcasting to all
  • 28. Strucure of the game HTML Click HTML Click Result Result Result WaitClick
  • 29. Connecting • <script src="/socket.io/socket.io.js"></script> • var socket = io.connect('http://localhost:3250');
  • 30. Connecting • <script src="/socket.io/socket.io.js"></script> • var socket = io.connect('http://localhost:3250'); • <script type="text/javascript" src="http://grrds4inarow.nodejitsu.com:80/socket.io /socket.io.js"></script> • var socket = io.connect('http://grrds4inarow.nodejitsu.com:80'); • socket.disconnect(); • socket.socket.reconnect();
  • 31. Starting Games var startgame = function(user) { for(var i=0; i<users.length; i++) { if (i == users.length-1) { // kein freier Gegner io.sockets.socket(users[i].id).emit("connect", users[i]); } else { // Gegner vorhanden if (users[i].opponent == null) { users[i].opponent = users[users.length-1].id; users[i].role = "0"; io.sockets.socket(users[i].id).emit("startgame", users[i]); users[users.length-1].opponent = users[i].id; users[users.length-1].role = "1"; io.sockets.socket(users[users.length-1].id) .emit("startgame",users[users.length-1]); break; } } } }
  • 32. Playing Sender socket.emit('playsend', {to: user.opponent,col: spaltenr, round: countround}); Server socket.on("playsend", function (data) { io.sockets.socket(data.to).emit("playget", data); }); Reciever socket.on('playget', function (data) { if (countround == data.round && lastround != data.round) { lastround = data.round; spielzug(data.col); } });
  • 33. Host your app • http://localhost • your own web-server • node.js hoster https://www.nodejitsu.com/