SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
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 

Mais conteúdo relacionado

Mais procurados

Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
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 84Mahmoud Samir Fayed
 
Nosql hands on handout 04
Nosql hands on handout 04Nosql hands on handout 04
Nosql hands on handout 04Krishna Sankar
 
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 196Mahmoud Samir Fayed
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video gamedandylion13
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Remy Sharp
 
Bangun datar dan bangun ruang
Bangun datar dan bangun ruangBangun datar dan bangun ruang
Bangun datar dan bangun ruangSanSan Yagyoo
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShellDale Lane
 
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 210Mahmoud Samir Fayed
 
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 WebRobin Hawkes
 
Esoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in RubyEsoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in Rubymametter
 
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
 
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 SederhanaMuhammad Yusuf
 
如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test名辰 洪
 

Mais procurados (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
 

Semelhante a Game dev 101 part 3

Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScriptSam Cartwright
 
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 codeLaurence Svekis ✔
 
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 ProgrammingRichard Jones
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
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
 
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 WillVincenzo Barone
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Testing a 2D Platformer with Spock
Testing a 2D Platformer with SpockTesting a 2D Platformer with Spock
Testing a 2D Platformer with SpockAlexander Tarlinder
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02PL dream
 
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.pdfproloyankur01
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
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 todaygerbille
 
C++ game development with oxygine
C++ game development with oxygineC++ game development with oxygine
C++ game development with oxyginecorehard_by
 

Semelhante a 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
 

Mais 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
 

Último

Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfisabel213075
 
Forming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).pptForming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).pptNoman khan
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSsandhya757531
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxStephen Sitton
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHSneha Padhiar
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESkarthi keyan
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionSneha Padhiar
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
priority interrupt computer organization
priority interrupt computer organizationpriority interrupt computer organization
priority interrupt computer organizationchnrketan
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfDrew Moseley
 
Javier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier Fernández Muñoz
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Sumanth A
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labsamber724300
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 

Último (20)

Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
Stork Webinar | APM Transformational planning, Tool Selection & Performance T...
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdf
 
Forming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).pptForming section troubleshooting checklist for improving wire life (1).ppt
Forming section troubleshooting checklist for improving wire life (1).ppt
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptx
 
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACHTEST CASE GENERATION GENERATION BLOCK BOX APPROACH
TEST CASE GENERATION GENERATION BLOCK BOX APPROACH
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
 
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptxCurve setting (Basic Mine Surveying)_MI10412MI.pptx
Curve setting (Basic Mine Surveying)_MI10412MI.pptx
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based question
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
priority interrupt computer organization
priority interrupt computer organizationpriority interrupt computer organization
priority interrupt computer organization
 
Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdf
 
Javier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptxJavier_Fernandez_CARS_workshop_presentation.pptx
Javier_Fernandez_CARS_workshop_presentation.pptx
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
 
Secure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech LabsSecure Key Crypto - Tech Paper JET Tech Labs
Secure Key Crypto - Tech Paper JET Tech Labs
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.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 

Notas do Editor

  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