SlideShare une entreprise Scribd logo
1  sur  22
Game dev 101 part 3
Chris Noring
@chris_noring
Did you add gravity? Let’s see
Recap, game dev
in your browser
// draws a red rectangle
//1. get the canvas reference
canvas = document.getElementById("myCanvas");
//2. set the context to 2D to draw basic shapes
ctx = canvas.getContext("2d");
//3. fill it with the color red
ctx.fillStyle = 'red’;
//4. and draw a rectangle with these parameters,
setting location and size
ctx.fillRect(0,0, 200, 200) // x,y,width, height
Draw on the web
• JavaScript, the programming language
• Canvas, we can paint things on it like:
• Images
• Primitives like rectangles
• Let’s paint someting:
index.html
app.js
<html>
<head></head>
<body>
<canvas id="myCanvas" width="200"
height="100">
</canvas>
<script src=”app.js”></script>
</body>
</html>
// draws a red rectangle
//1. get the canvas reference
canvas = document.getElementById("myCanvas")
//2. set the context to 2D to draw basic sha
ctx = canvas.getContext("2d");
//3. fill it with the color red
ctx.fillStyle = 'red’;
//4. and draw a rectangle with these paramet
setting location and size
ctx.fillRect(0,0, 200, 200) // x,y,width, he
Get started on the space game project
• https://github.com/microsoft/Web-Dev-For-Beginners
• Unzip
• Download VS Code, https://code.visualstudio.com/download
• Install Live Server Extension
Our project
• index.html
• app.js
• hero.png
<html>
<head></head>
<body>
<canvas id="myCanvas" width="200"
height="100">
</canvas>
<script src=”app.js”></script>
</body>
</html>
function loadAsset(path) {
return new Promise((resolve) => {
const img = new Image();
img.src = path;
img.onload = () => {
// image loaded and ready to be used
resolve(img);
}
})
}
async function run() {
const heroImg = await
loadAsset('hero.png’)
canvas =
document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.drawImage(heroImg,
canvas.width/2,canvas.height/2);
}
run();
Space game, set up
• Load asset (your ship)
• Let’s paint an image, your ship
function loadAsset(path) {
return new Promise((resolve) => {
const img = new Image();
img.src = path;
img.onload = () => {
// image loaded and ready to be used
resolve(img);
}
})
}
async function run() {
const heroImg = await loadAsset('hero.png’)
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.drawImage(heroImg,
canvas.width/2,canvas.height/2);
}
run();
Run our
project
• Install VS Code
• Install Live server
extension
• View > Command palette
• Live Server: Open with
Live Server
Drawing hero and enemies
window.onload = async() => {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
const heroImg = await loadTexture('assets/player.png’)
const enemyImg = await loadTexture('assets/enemyShip.png’)
ctx.fillStyle = 'black’;
ctx.fillRect(0,0, canvas.width, canvas.height);
ctx.drawImage(heroImg, canvas.width/2 - 45, canvas.height -
(canvas.height /4));
createEnemies(ctx, canvas, enemyImg);
};
function createEnemies(ctx, canvas, enemyImg) {
const MONSTER_TOTAL = 5;
const MONSTER_WIDTH = MONSTER_TOTAL * 98;
const START_X = (canvas.width - MONSTER_WIDTH) / 2;
const STOP_X = START_X + MONSTER_WIDTH;
for (let x = START_X; x < STOP_X; x += 98) {
for (let y = 0; y < 50 * 5; y += 50) {
ctx.drawImage(enemyImg, x, y);
}
}
}
function loadTexture(path) {
return new Promise((resolve) => {
const img = new Image();
img.src = path;
img.onload = () => {
resolve(img);
}})
}
Let’s make it move
• User key press
• Game moves enemies at
regular intervals
• Change position of ship and
enemies
• Redraw
Code structure
game objects & game loop
hero
enemy
enemy
enemy
enemy
enemy
Game objects
initGame()
window.onload = async () => {
canvas = document.getElementById('canvas’);
ctx = canvas.getContext('2d’);
heroImg = await loadTexture('assets/player.png’);
enemyImg = await loadTexture('assets/enemyShip.png’);
laserImg = await loadTexture('assets/laserRed.png');
initGame();
let gameLoopId = setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawGameObjects(ctx);
}, 100);
};
Event emitter – avoid messy code
Event
emitter
Pressing space
Enter
Arrow keys
Move hero
Shoot
Restart game
Capture keypress
Raise event
Event emitter, listen for events, send them
where they need to go
class EventEmitter {
constructor() {
this.listeners = {};
}
on(message, listener) {
if (!this.listeners[message]) {
this.listeners[message] = [];
}
this.listeners[message].push(listener);
}
emit(message, payload = null) {
if (this.listeners[message]) {
this.listeners[message].forEach((l) => l(message,
payload));
}
}
Capture keypress + raise event
(emit(“event”))
window.addEventListener('keyup', (evt) =>
{
if (evt.key === 'ArrowUp’) {
eventEmitter.emit(Messages.KEY_EVENT_UP);
} else if (evt.key === 'ArrowDown') {
eventEmitter.emit(Messages.KEY_EVENT_DOWN)
;
} else if (evt.key === 'ArrowLeft') {
eventEmitter.emit(Messages.KEY_EVENT_LEFT)
;
} else if (evt.key === 'ArrowRight') {
eventEmitter.emit(Messages.KEY_EVENT_RIGHT
);
Capture events – and make state changes to
the game
function initGame() {
gameObjects = [];
createEnemies();
createHero();
eventEmitter.on(Messages.KEY_EVENT_UP, () => {
hero.y -= 5;
});
eventEmitter.on(Messages.KEY_EVENT_DOWN, () => {
hero.y += 5;
});
eventEmitter.on(Messages.KEY_EVENT_LEFT, () => {
hero.x -= 5;
});
eventEmitter.on(Messages.KEY_EVENT_RIGHT, () => {
hero.x += 5;
});
}
window.onload = async () => {
canvas = document.getElementById('canvas’);
ctx = canvas.getContext('2d’);
heroImg = await loadTexture('assets/player.png’);
enemyImg = await loadTexture('assets/enemyShip.png
laserImg = await loadTexture('assets/laserRed.png'
initGame();
let gameLoopId = setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = 'black’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawGameObjects(ctx);
}, 100);
};
Every 100ms, drawGameObjects()
Demo –
moving
enemies and
hero
Add laser
• Listen for space keypress
• Raise event
eventEmitter.on(Messages.KEY_EVENT_SPACE, () => {
if (hero.canFire()) {
hero.fire();
}
// console.log('cant fire - cooling down')
});
window.addEventListener('keyup', (evt) => {
if (evt.key === 'ArrowUp') {
eventEmitter.emit(Messages.KEY_EVENT_UP);
} else if (evt.key === 'ArrowDown') {
eventEmitter.emit(Messages.KEY_EVENT_DOWN);
} else if (evt.key === 'ArrowLeft') {
eventEmitter.emit(Messages.KEY_EVENT_LEFT);
} else if (evt.key === 'ArrowRight') {
eventEmitter.emit(Messages.KEY_EVENT_RIGHT);
} else if (evt.keyCode === 32) {
eventEmitter.emit(Messages.KEY_EVENT_SPACE);
} else if (evt.key === 'Enter') {
eventEmitter.emit(Messages.KEY_EVENT_ENTER);
}
});
Add laser : fire the laser
• Define laser class
• Fire laser
class Laser extends GameObject {
constructor(x, y) {
super(x, y);
(this.width = 9), (this.height = 33);
this.type = 'Laser’;
this.img = laserImg;
let id = setInterval(() => {
if (this.y > 0) {
this.y -= 15;
} else {
this.dead = true;
clearInterval(id);
}
}, 100);
}
}
fire() {
gameObjects.push(new Laser(this.x + 45, this.y -
10));
this.cooldown = 500;
let id = setInterval(() => {
if (this.cooldown > 0) {
this.cooldown -= 100;
if(this.cooldown === 0) {
clearInterval(id);
}
}
}, 200);
}
Check for
collisions
• If laser, intersects with
enemy,
• Destroy laser
• Destroy enemy
• if enemy intersects with
hero
• Destroy hero
• Destroy enemy
function updateGameObjects() {
const enemies = gameObjects.filter((go) => go.type === 'Enemy’);
const lasers = gameObjects.filter((go) => go.type === 'Laser');
enemies.forEach((enemy) => {
const heroRect = hero.rectFromGameObject();
if (intersectRect(heroRect, enemy.rectFromGameObject())) {
eventEmitter.emit(Messages.COLLISION_ENEMY_HERO, { enemy });
}
});
lasers.forEach((l) => {
enemies.forEach((m) => {
if (intersectRect(l.rectFromGameObject(), m.rectFromGameObject(
eventEmitter.emit(Messages.COLLISION_ENEMY_LASER, {
first: l,
second: m,
});
}
});
});
gameObjects = gameObjects.filter((go) => !go.dead);
}
Add more game state
• Lives
• Points
eventEmitter.on(Messages.COLLISION_ENEMY_LASER, (_, {
first, second }) => {
first.dead = true;
second.dead = true;
hero.incrementPoints();
if (isEnemiesDead()) {
eventEmitter.emit(Messages.GAME_END_WIN);
}
});
eventEmitter.on(Messages.COLLISION_ENEMY_HERO, (_, {
enemy }) => {
enemy.dead = true;
hero.decrementLife();
if (isHeroDead()) {
eventEmitter.emit(Messages.GAME_END_LOSS);
return; // loss before victory
}
if (isEnemiesDead()) {
eventEmitter.emit(Messages.GAME_END_WIN);
}
});
DEMO
• Moving ship, firing lasers, see ships destroyed
Summary
• We’ve learned to make games in MakeCode, we saw how to add gravity
• You’ve been introduced to coding in JavaScript and for the Web
• What’s next? Keep building games, start with MakeCode, start looking at the code
tab (instead of the block), modify, that’s how I started
• Pick up programming, https://github.com/microsoft/Web-Dev-For-Beginners
• https://www.w3schools.com/
• Look at these https://github.com/leereilly/games learn to read code, modify
• Super Mario in JavaScript, https://github.com/robertkleffner/mariohtml5
• It takes months to get good at coding, years to be a game dev, don’t forget to
have fun 
• Here is the space game as MakeCode, https://makecode.com/_98TWHKJJ6Jt4 lot
simpler right, go and make it yours, modify, good luck out there 

Contenu connexe

Tendances

Nosql hands on handout 04
Nosql hands on handout 04Nosql hands on handout 04
Nosql hands on handout 04
Krishna Sankar
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
Remy Sharp
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 

Tendances (20)

Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
The Ring programming language version 1.2 book - Part 37 of 84
The Ring programming language version 1.2 book - Part 37 of 84The Ring programming language version 1.2 book - Part 37 of 84
The Ring programming language version 1.2 book - Part 37 of 84
 
Ricky Bobby's World
Ricky Bobby's WorldRicky Bobby's World
Ricky Bobby's World
 
Game age ppt
Game age pptGame age ppt
Game age ppt
 
Nosql hands on handout 04
Nosql hands on handout 04Nosql hands on handout 04
Nosql hands on handout 04
 
The Ring programming language version 1.7 book - Part 54 of 196
The Ring programming language version 1.7 book - Part 54 of 196The Ring programming language version 1.7 book - Part 54 of 196
The Ring programming language version 1.7 book - Part 54 of 196
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 
Bangun datar dan bangun ruang
Bangun datar dan bangun ruangBangun datar dan bangun ruang
Bangun datar dan bangun ruang
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShell
 
Unity3 d devfest-2014
Unity3 d devfest-2014Unity3 d devfest-2014
Unity3 d devfest-2014
 
The Ring programming language version 1.9 book - Part 71 of 210
The Ring programming language version 1.9 book - Part 71 of 210The Ring programming language version 1.9 book - Part 71 of 210
The Ring programming language version 1.9 book - Part 71 of 210
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the Web
 
Esoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in RubyEsoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in Ruby
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
Deploy in the Cloud
Deploy in the CloudDeploy in the Cloud
Deploy in the Cloud
 
Praktik Pengembangan Konten E-Learning HTML5 Sederhana
Praktik Pengembangan Konten E-Learning HTML5 SederhanaPraktik Pengembangan Konten E-Learning HTML5 Sederhana
Praktik Pengembangan Konten E-Learning HTML5 Sederhana
 
如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test
 

Similaire à Game dev 101 part 3

JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
Html5 game programming overview
Html5 game programming overviewHtml5 game programming overview
Html5 game programming overview
민태 김
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
Kevin Hoyt
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02
PL dream
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
gerbille
 

Similaire à Game dev 101 part 3 (20)

Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScript
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Html5 game programming overview
Html5 game programming overviewHtml5 game programming overview
Html5 game programming overview
 
Intro to Game Programming
Intro to Game ProgrammingIntro to Game Programming
Intro to Game Programming
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
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)
 
Css5 canvas
Css5 canvasCss5 canvas
Css5 canvas
 
Jeroen Vloothuis Bend Kss To Your Will
Jeroen Vloothuis   Bend Kss To Your WillJeroen Vloothuis   Bend Kss To Your Will
Jeroen Vloothuis Bend Kss To Your Will
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Intro to HTML5
Intro to HTML5Intro to HTML5
Intro to HTML5
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Shootting Game
Shootting GameShootting Game
Shootting Game
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with Spock
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02
 
create file name as board.javawrite below codeimport java.aw.pdf
create file name as board.javawrite below codeimport java.aw.pdfcreate file name as board.javawrite below codeimport java.aw.pdf
create file name as board.javawrite below codeimport java.aw.pdf
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Pengenalan blaast platform sdk
Pengenalan blaast platform sdkPengenalan blaast platform sdk
Pengenalan blaast platform sdk
 
C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxygine
 

Plus de Christoffer Noring

Plus de Christoffer Noring (20)

Azure signalR
Azure signalRAzure signalR
Azure signalR
 
Game dev workshop
Game dev workshopGame dev workshop
Game dev workshop
 
Deploying your static web app to the Cloud
Deploying your static web app to the CloudDeploying your static web app to the Cloud
Deploying your static web app to the Cloud
 
IaaS with ARM templates for Azure
IaaS with ARM templates for AzureIaaS with ARM templates for Azure
IaaS with ARM templates for Azure
 
Learning Svelte
Learning SvelteLearning Svelte
Learning Svelte
 
Ng spain
Ng spainNg spain
Ng spain
 
Angular Schematics
Angular SchematicsAngular Schematics
Angular Schematics
 
Design thinking
Design thinkingDesign thinking
Design thinking
 
Keynote ijs
Keynote ijsKeynote ijs
Keynote ijs
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and Vuex
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
Kendoui
KendouiKendoui
Kendoui
 
Angular mix chrisnoring
Angular mix chrisnoringAngular mix chrisnoring
Angular mix chrisnoring
 
Nativescript angular
Nativescript angularNativescript angular
Nativescript angular
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
React lecture
React lectureReact lecture
React lecture
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 

Dernier

Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 

Dernier (20)

Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 

Game dev 101 part 3

  • 1. Game dev 101 part 3 Chris Noring @chris_noring
  • 2. Did you add gravity? Let’s see
  • 3. Recap, game dev in your browser // draws a red rectangle //1. get the canvas reference canvas = document.getElementById("myCanvas"); //2. set the context to 2D to draw basic shapes ctx = canvas.getContext("2d"); //3. fill it with the color red ctx.fillStyle = 'red’; //4. and draw a rectangle with these parameters, setting location and size ctx.fillRect(0,0, 200, 200) // x,y,width, height
  • 4. Draw on the web • JavaScript, the programming language • Canvas, we can paint things on it like: • Images • Primitives like rectangles • Let’s paint someting: index.html app.js <html> <head></head> <body> <canvas id="myCanvas" width="200" height="100"> </canvas> <script src=”app.js”></script> </body> </html> // draws a red rectangle //1. get the canvas reference canvas = document.getElementById("myCanvas") //2. set the context to 2D to draw basic sha ctx = canvas.getContext("2d"); //3. fill it with the color red ctx.fillStyle = 'red’; //4. and draw a rectangle with these paramet setting location and size ctx.fillRect(0,0, 200, 200) // x,y,width, he
  • 5. Get started on the space game project • https://github.com/microsoft/Web-Dev-For-Beginners • Unzip • Download VS Code, https://code.visualstudio.com/download • Install Live Server Extension
  • 6. Our project • index.html • app.js • hero.png <html> <head></head> <body> <canvas id="myCanvas" width="200" height="100"> </canvas> <script src=”app.js”></script> </body> </html> function loadAsset(path) { return new Promise((resolve) => { const img = new Image(); img.src = path; img.onload = () => { // image loaded and ready to be used resolve(img); } }) } async function run() { const heroImg = await loadAsset('hero.png’) canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); ctx.drawImage(heroImg, canvas.width/2,canvas.height/2); } run();
  • 7. Space game, set up • Load asset (your ship) • Let’s paint an image, your ship function loadAsset(path) { return new Promise((resolve) => { const img = new Image(); img.src = path; img.onload = () => { // image loaded and ready to be used resolve(img); } }) } async function run() { const heroImg = await loadAsset('hero.png’) canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); ctx.drawImage(heroImg, canvas.width/2,canvas.height/2); } run();
  • 8. Run our project • Install VS Code • Install Live server extension • View > Command palette • Live Server: Open with Live Server
  • 9. Drawing hero and enemies window.onload = async() => { canvas = document.getElementById("canvas"); ctx = canvas.getContext("2d"); const heroImg = await loadTexture('assets/player.png’) const enemyImg = await loadTexture('assets/enemyShip.png’) ctx.fillStyle = 'black’; ctx.fillRect(0,0, canvas.width, canvas.height); ctx.drawImage(heroImg, canvas.width/2 - 45, canvas.height - (canvas.height /4)); createEnemies(ctx, canvas, enemyImg); }; function createEnemies(ctx, canvas, enemyImg) { const MONSTER_TOTAL = 5; const MONSTER_WIDTH = MONSTER_TOTAL * 98; const START_X = (canvas.width - MONSTER_WIDTH) / 2; const STOP_X = START_X + MONSTER_WIDTH; for (let x = START_X; x < STOP_X; x += 98) { for (let y = 0; y < 50 * 5; y += 50) { ctx.drawImage(enemyImg, x, y); } } } function loadTexture(path) { return new Promise((resolve) => { const img = new Image(); img.src = path; img.onload = () => { resolve(img); }}) }
  • 10. Let’s make it move • User key press • Game moves enemies at regular intervals • Change position of ship and enemies • Redraw
  • 11. Code structure game objects & game loop hero enemy enemy enemy enemy enemy Game objects initGame() window.onload = async () => { canvas = document.getElementById('canvas’); ctx = canvas.getContext('2d’); heroImg = await loadTexture('assets/player.png’); enemyImg = await loadTexture('assets/enemyShip.png’); laserImg = await loadTexture('assets/laserRed.png'); initGame(); let gameLoopId = setInterval(() => { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'black’; ctx.fillRect(0, 0, canvas.width, canvas.height); drawGameObjects(ctx); }, 100); };
  • 12. Event emitter – avoid messy code Event emitter Pressing space Enter Arrow keys Move hero Shoot Restart game Capture keypress Raise event
  • 13. Event emitter, listen for events, send them where they need to go class EventEmitter { constructor() { this.listeners = {}; } on(message, listener) { if (!this.listeners[message]) { this.listeners[message] = []; } this.listeners[message].push(listener); } emit(message, payload = null) { if (this.listeners[message]) { this.listeners[message].forEach((l) => l(message, payload)); } }
  • 14. Capture keypress + raise event (emit(“event”)) window.addEventListener('keyup', (evt) => { if (evt.key === 'ArrowUp’) { eventEmitter.emit(Messages.KEY_EVENT_UP); } else if (evt.key === 'ArrowDown') { eventEmitter.emit(Messages.KEY_EVENT_DOWN) ; } else if (evt.key === 'ArrowLeft') { eventEmitter.emit(Messages.KEY_EVENT_LEFT) ; } else if (evt.key === 'ArrowRight') { eventEmitter.emit(Messages.KEY_EVENT_RIGHT );
  • 15. Capture events – and make state changes to the game function initGame() { gameObjects = []; createEnemies(); createHero(); eventEmitter.on(Messages.KEY_EVENT_UP, () => { hero.y -= 5; }); eventEmitter.on(Messages.KEY_EVENT_DOWN, () => { hero.y += 5; }); eventEmitter.on(Messages.KEY_EVENT_LEFT, () => { hero.x -= 5; }); eventEmitter.on(Messages.KEY_EVENT_RIGHT, () => { hero.x += 5; }); } window.onload = async () => { canvas = document.getElementById('canvas’); ctx = canvas.getContext('2d’); heroImg = await loadTexture('assets/player.png’); enemyImg = await loadTexture('assets/enemyShip.png laserImg = await loadTexture('assets/laserRed.png' initGame(); let gameLoopId = setInterval(() => { ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.fillStyle = 'black’; ctx.fillRect(0, 0, canvas.width, canvas.height); drawGameObjects(ctx); }, 100); }; Every 100ms, drawGameObjects()
  • 17. Add laser • Listen for space keypress • Raise event eventEmitter.on(Messages.KEY_EVENT_SPACE, () => { if (hero.canFire()) { hero.fire(); } // console.log('cant fire - cooling down') }); window.addEventListener('keyup', (evt) => { if (evt.key === 'ArrowUp') { eventEmitter.emit(Messages.KEY_EVENT_UP); } else if (evt.key === 'ArrowDown') { eventEmitter.emit(Messages.KEY_EVENT_DOWN); } else if (evt.key === 'ArrowLeft') { eventEmitter.emit(Messages.KEY_EVENT_LEFT); } else if (evt.key === 'ArrowRight') { eventEmitter.emit(Messages.KEY_EVENT_RIGHT); } else if (evt.keyCode === 32) { eventEmitter.emit(Messages.KEY_EVENT_SPACE); } else if (evt.key === 'Enter') { eventEmitter.emit(Messages.KEY_EVENT_ENTER); } });
  • 18. Add laser : fire the laser • Define laser class • Fire laser class Laser extends GameObject { constructor(x, y) { super(x, y); (this.width = 9), (this.height = 33); this.type = 'Laser’; this.img = laserImg; let id = setInterval(() => { if (this.y > 0) { this.y -= 15; } else { this.dead = true; clearInterval(id); } }, 100); } } fire() { gameObjects.push(new Laser(this.x + 45, this.y - 10)); this.cooldown = 500; let id = setInterval(() => { if (this.cooldown > 0) { this.cooldown -= 100; if(this.cooldown === 0) { clearInterval(id); } } }, 200); }
  • 19. Check for collisions • If laser, intersects with enemy, • Destroy laser • Destroy enemy • if enemy intersects with hero • Destroy hero • Destroy enemy function updateGameObjects() { const enemies = gameObjects.filter((go) => go.type === 'Enemy’); const lasers = gameObjects.filter((go) => go.type === 'Laser'); enemies.forEach((enemy) => { const heroRect = hero.rectFromGameObject(); if (intersectRect(heroRect, enemy.rectFromGameObject())) { eventEmitter.emit(Messages.COLLISION_ENEMY_HERO, { enemy }); } }); lasers.forEach((l) => { enemies.forEach((m) => { if (intersectRect(l.rectFromGameObject(), m.rectFromGameObject( eventEmitter.emit(Messages.COLLISION_ENEMY_LASER, { first: l, second: m, }); } }); }); gameObjects = gameObjects.filter((go) => !go.dead); }
  • 20. Add more game state • Lives • Points eventEmitter.on(Messages.COLLISION_ENEMY_LASER, (_, { first, second }) => { first.dead = true; second.dead = true; hero.incrementPoints(); if (isEnemiesDead()) { eventEmitter.emit(Messages.GAME_END_WIN); } }); eventEmitter.on(Messages.COLLISION_ENEMY_HERO, (_, { enemy }) => { enemy.dead = true; hero.decrementLife(); if (isHeroDead()) { eventEmitter.emit(Messages.GAME_END_LOSS); return; // loss before victory } if (isEnemiesDead()) { eventEmitter.emit(Messages.GAME_END_WIN); } });
  • 21. DEMO • Moving ship, firing lasers, see ships destroyed
  • 22. Summary • We’ve learned to make games in MakeCode, we saw how to add gravity • You’ve been introduced to coding in JavaScript and for the Web • What’s next? Keep building games, start with MakeCode, start looking at the code tab (instead of the block), modify, that’s how I started • Pick up programming, https://github.com/microsoft/Web-Dev-For-Beginners • https://www.w3schools.com/ • Look at these https://github.com/leereilly/games learn to read code, modify • Super Mario in JavaScript, https://github.com/robertkleffner/mariohtml5 • It takes months to get good at coding, years to be a game dev, don’t forget to have fun  • Here is the space game as MakeCode, https://makecode.com/_98TWHKJJ6Jt4 lot simpler right, go and make it yours, modify, good luck out there 

Notes de l'éditeur

  1. DOM tree, what a page is, a list of hierarchical nodes, that we can change Canvas, what we can point on, also a Node A canvas a has a contexr, what we actually interact with when we paint something