browser game strategy

browser game strategy, browser, game, strategy

Hi guys and welcome to this video Juriy is here. We will be building games today together with you. Not just games. We’ll bebuilding multiplayer games with the help of JavaScript, Node.js and of course HTML5.Multiplayer games can be vastly different they can be as simple as thislittle implementation of rock-paper-scissors. It doesn’t even havegraphics just the buttons and the text, still it is a playable game. And then thegames can go all the way to multiplayer massive multiplayer online RPGs orstrategies with persistent worlds with real-time action with player versusplayer rich graphics or even 3d. And you can go all the way to of thatscale of games but you have to start somewhere. And this particular video…couple of videos are built to make you confident that you can build a game. Thisis our little goal for a couple of videos I guess. Rock-paper-scissors andplayers can talk to each other say “hi” and as you see the other player willimmediately get back that “hi” they can play game this guy selects rock and thenthis guy selects paper. Obviously the guy that selected paper wins because paperwraps rock. And then they can go on and on andon this is our goal and right now we will start from almost empty project andtry to reach the first goal of just making our chat work. Making one playersend the message to the other player Alright now let’s go to our project Ihave a little folder here called /gamedev/rps… and I took a littlebit of freedom to set up the very basic skeleton for html5 applications. Guys Itruly believe that you can set up this kind of a markup. It’s not hard at all itjust have an unordered list for the events that are coming from the server.It’s called “events” and then it has three buttons: “rock”, “paper” “scissors”. Actually should be four: there should be a button called…let’s give it an ID called “say” to send a chat message. And finally there should bea text field somewhere. So here’s an input with ID…Good let’s go chat so now on the client side I have just three files calledindex.html client.js and main.css as you see client.js and main.css are totallyempty. On the server side, by the way server is in the separate folder and itis a good idea to keep your client and server totally separate and treat themas separate applications. That will save you loads of time loads of nerves onthe later phases or on the bigger projects. The server.js is alsototally empty – we will be writing it from the scratch. So here’s my little setupnow let’s start building our game. All right so the first thing that we will do:let’s have a brief look at how our application looks like. And it will lookquite ugly because we don’t have any CSS right now. Just plain HTML nothingelse and our first goal will be to serve this file from the server instead offrom the filesystem. Okay to do that we’ll need to go to our server side partof our project. And obviously here we just have server.js nothing else to makeit proper Node.js application we need to do “npm init”. Since I’m in a rush to showyou guys how to do things I just add “-y” flag here and NPM will initializemy package.json with default values. I will fix them later for now that will do.Now what we will need to do we will need to call NPM install and install twomodules Express which is the most popular HTTP framework. I’m pretty surethat you guys heard about it or worked with it and the second part will beSocket.IO. This is a library for real-time communications in web. Itwraps either WebSockets or XmlHttpRequest depending on what isavailable. It is providing a little bit higher level of abstractions overthe plain WebSockets and that will be quite handy, quite useful for ourapplication. So let’s install Express and Socket.IO notice that I’m not putting”save” here. Why? Because I’m using NPM 5 and Node.js version 8 – NPM inthis version is saving the modules by default. So you don’tneed to type “–save” it will be automatically added to package.json. Soin a second it will install Express and Socket IO. Done. One more little modulethat I want to install in this project is called “nodemon”. Usually when youchange something in the server-side code you need to restore the server and whatI hate doing is going back and forth from the console to IDE to restart theserver over and over again. So what I

browser game strategyfrom the console to IDE to restart theserver over and over again. So what I will do I will install “npm install nodemon” and I will tell it to save as development dependency. Here I need to tell NPMhere’s the development dependency not the actual production dependency. Again Ijust like to keep things organized and know which are the parts of the app thatI need for production which are the parts that I’m only using during thedevelopment time. All right this dependency is installed and I canjump back to my IDE. Alright so on server.js I need to start coding so let’s startfrom importing “http”. This is a standard module so it will be right here. And Iwill also need to have Express which is… “require express”… here it is. Now I need tocreate a server and this server needs a listener function right here so it needsto know what to do when the client is connecting. And whenever the client isconnecting Express will be handling the connection. So I’ll create an app fromExpress an app by the way it is an object and a function. Right so app is afunction and I can pass it here. Alrighty now this is a very basic serverobviously it needs to listen to something. “Server listen to port…” let’ssay 8080 just fine. Whenever it listens to 8080 I want to call this function toprint “RPS started on 8080”. Now I also want to know when the server crashed for some reason and couldn’t start. So I add an event listener called ‘error’ sowhenever there is an error – please call this function and the error object willbe passed right here. And here I will write “console.error(‘server error’, err)”. Sosomething like this if I did everything correctly I should be able to startserver. Right… so you can usually go to terminal and just type “node server.js”.But it’s not cool. The right way to do that would be to go first to our package.json and in package.jso to define a script to start the application. It is already defined. “node server.js” So see, NPM is being smart enough to define the script.Awesome so now in my console I can just type “npm start”. And server started lookslike it’s working. At least I don’t have any errors so far. Okay but it’s notdoing anything it’s not even trying to serve my static files let’s fix that Inorder to serve static files I will need to add a middleware to this littleapplication to this little Express app. “static” middleware that is responsiblefor serving static files is available in express out-of-the-box. Probably is justthe only single thing that is available out of the box but it is available. SoI’m writing “app.use(express.static())” and in order for static to work I need to tellit where to find files. All right so my files will be stored in this folderwhich is client’s path. And client path will be… What will it be? It will be”__dirname” – this is the variable that is available in node.jsand it points to the current folder of the current module. So this will be here – “server”, this part. So from __dirname I need to go one level up to “rps” becauseclient is on the same level as server it’s not a subfolder of server, it’s on the same level. So I need to go one level upper and I need to go to the “client”. So thispath will look ugly but it will work. console.log(…) let’s type “Serving staticfrom ${client}. That’s amazing and now since I changed something in the server sidepart I need to go and restart the server. I don’t like to do that each and everytime so I will make my life easier straightaway I’ll go to package.json andhere I will add one more script. By the way let’s put start over here… and after startI will put a script called… What shall we call it?let’s go “dev” for development. And here we call “nodemon server.js”. NPM is smartand knows that if you are calling the module that is available inside of node_modules, it doesn’t even have to be installed globally, it will execute itput all the paths right and it will run server.js inside of nodemon. So whatit will give us? Let me show you a really quick demo of how it works. If you’re notyet using nodemon you’re developing in node.js just trust me – you have to startusing it. It will save you so much time in the long run.Okay so “npm run dev” that’s my script rightey… Root pathrequired something… Something bad happened here. Serve static… So I probablydidn’t pass… Yes, I didn’t pass the variable clientPath here. I’ll fix thatand you see – I fixed the problem. I didn’t

browser game strategyvariable clientPath here. I’ll fix thatand you see – I fixed the problem. I didn’t touch anything after the applicationcrash and instantly nodemon picked up that I changed the file and it restarted the server. So the server is working right now. So if I did everythingcorrectly I’m serving the files from 8080… should be picked up. Let’s see if itworks. And it works. So right now my files are served from 8080. So now this is agood time to start talking to the server and to use Socket.IO. Let’s initializeSocket.IO on the server first. Setting up Socket.IO on the server is really really easy almost as easy as setting up expressapplication. So all you need to do is obviously you need that module so let’screate a variable called socketio and require this module. Now all you need todo is call this function, this is a function, and pass it an HTTP serverinstance and it will return your… well “server” that you can use to talk to yourclients. So let’s do that. const io. “io” is very typical name forSocket.IO servers. socketio(server). Now this point you might have a question:”will Socket.IO… like annihilate or destroy our listener that it’s alreadyregistered on the server”. So as you see here we register express.js as thelistener to the server. So will Socket.IO overwrite it? In reality Socket.IOis very smart: it will detect that there is already a listener and it will justtake care of its own requests which will not interfere in any way with express.jsapplication. Now Socket.IO is ready on the server. That’s literally it. Now inorder to do something with it you need to listen to events. Whenever there issomething happening with Socket.IO, it will emit an event like… well likeeverything in JavaScript. So whenever the user will be connected to the server youwill receive an event called ‘connection’. And in the event listeneryou will receive an object called ‘sock’. I usually call it “sock” – stands shortfor “socket” nothing to do with socks. Let’s send the message to the user rightaway as he connects. So it would be sock.emit(). Again we don’t care about thedetails how this message will be passed. We’ll emit something that is called a”message” – this is a string that will just identify the type of the thing thatyou’re sending. It can be anything “chat” “message”, “turn” etc. And then we’re passingthe data. Again data can be anything as well: you can pass a number, you can passthe object: it will all work. So “Hi, you are connected”. This will be themessage that I will send to each and every newly connected user. Okay nowlet’s go on the client side and we’ll try to receive this wonderful message onthe client. So we’re going to client.js which is so far totally empty. Now Idon’t want to write to console. I really want to append my messages to thislittle “#events” block that I have on the page so I’ll write a little helperfunction. Called… well let’s call it “log” it’s a good function. Or writeEvents,probably better name. And there’s gonna be another arrow function. As you see Ireally really like arrow functions and it will receive the text. What it will do?Firstly it will receive the parent. The

    element will call querySelector(). Andwhat’s the ID of our wrapper? It’s called #events. Okayso #events. Now to that parent I need to add another
  • . So let me add a littlebit of comments here let’s be nice. This is
      element and this is gonna be alist item:
    • element. So we’ll say document.createElement() because we’recreating new element to put there the text that we received from the server.And the type of that element is
    • , list item. Now inside of element we’ll putinnerHTML and that will be the text that we want to put in. Finally “parent”… weneed to call here appendChild() to add this newly created element to theparent. So now our “writeEvent()” is ready. Now let’s let’s just call itstraightaway to see that if it works. And here I had the “hello” message saying”hello” to RPS. Instead of putting it into HTML I will nowmove that to our javascript file to keep things organized. writeEvent(“Welcome to RPS”).Awesome so now if I refresh the page it still writes “Welcometo RPS” but now instead of coming from HTML this is coming from my JavaScriptwhich is good. Okay let’s now get that message from the server. The firstthing to do we need somehow to get the

      browser game strategy that message from the server. The firstthing to do we need somehow to get the

      browser game strategythat message from the server. The firstthing to do we need somehow to get the client-side code for Socket.IO. On theserver side we just “required” Socket.IO library and we’ve got everything that weneed on the server side. On the client side we need that library. We need thosedefinitions we need client to know how to connect to that server. So I’ll addanother