Many modern programs, like GUIs, window managers, spreadsheets, word processors, and games, use a programming model based on the handling of events. Hence, we are going to study them and talk about EDP – Event Driven Programming.
Class work
Let’s start building the game.
Topics for today
- Local and global variables
- Scope
- Event-driven programming:
- peripherals
- drivers
- interrupts
- events
- event handlers
Our goal: Simon Says (click on the image to play it)
Workfiles
Download in class: simon-says.zip
Individual files:
Initial templates
- template.html: Initial HTML template
12345678910111213<!DOCTYPE html><html lang="en-US"><head><meta charset="UTF-8" /><!-- <link rel="stylesheet" type="text/css" href="style.css" /> --><title>My first HTML page</title></head><body><p>Hello World!</p><script src="script.js"></script></body></html>
- template.js: Initial javascript page
12345var SS = {}; // Global object containerfunction P(i){console.log(i);}
- Our page so far: template.html
v0 – HTML content and the images of the lightbulbs
- simon_0.html: Main HTML content
1234567891011121314151617181920212223242526272829<!DOCTYPE html><html lang="en-US"><head><meta charset="UTF-8"><!-- <link rel="stylesheet" type="text/css" href="style.css" /> --><title>Simon Says</title></head><body><div id = "container"><div id = "header"><h1 id = "title">Images</h1></div><div id = "game"><img id="lb_0" onclick="lb_click(0)" src="images/lb_off.png" width="100" height="188"><img id="lb_1" onclick="lb_click(1)" src="images/lb_off.png" width="100" height="188"><img id="lb_2" onclick="lb_click(2)" src="images/lb_off.png" width="100" height="188"><img id="lb_3" onclick="lb_click(3)" src="images/lb_off.png" width="100" height="188"><img id="lb_4" onclick="lb_click(4)" src="images/lb_off.png" width="100" height="188"></div><div id = "footer"><button id="btn_0" type="button" onclick="play_game()">Play!</button></div></div><script type="text/javascript" src="lib0.js"></script></body></html>
- lib0.js: Image toggle, listening of mouse events
12345678910111213141516171819202122232425262728293031323334353637383940414243var SS = {}; // Global object containerfunction init_images() {SS.img_off = "images/lb_off.png";SS.img_on = [ "images/lb_yellow.png","images/lb_blue.png","images/lb_green.png","images/lb_red.png","images/lb_purple.png"];SS.n = SS.img_on.length;SS.img_delay = 800;}function turn_lb_on(i, image) {image.src = SS.img_on[i];}function turn_lb_off(image) {image.src = SS.img_off;}function lb_click(i) {var img_id = "lb_" + String(i);var image = document.getElementById(img_id);turn_lb_on(i, image);setTimeout( function(){turn_lb_off(image)}, SS.img_delay);}function play_game() {alert("play game");}window.onload = function() {init_images();}function P(i){console.log(i);}
- Our page so far: simon_0.html