Programming games

Download Report

Transcript Programming games

Programming games
Drawing! Debugging. New coin toss. Dice
game rules. Storage (binary numbers)
Homework: New coin toss. [Start dice
game.]
Drawing
• EMAILed.
• Do exercises. Re-create and then modify.
• Recap:
– rectangles
– paths: arcs and lines
– Today: images and text
Debugging
• Make sure you are testing latest version
– you can make a small visible change
• Insert alert statements
alert("at start of toss function");
alert("xxx is "+xxx);
• NOTE: if a function is not well-formed (for
example, bracket problem), the browser does not
display a message—it just doesn't work!
• Firefox: Tools/Error console
Chrome: wench symbol/Tools/JavaScript Console
Debugging
• In TextWrangler (PC: TextPad) use Find
command
– Check if dthrow defined AND called
– Check on consistent spelling of names
– Can use for brackets, closing </a>, etc.
though you may need to print out and use
pencil. Also use opening and closing….
JavaScript if & if/else
if ( logicalexpression
statements
}
if ( logicalexpression
statements
}
else {
statements
}
) {
) {
Switch statement
switch (expression) {
case value1: statements
case value2: statements
default: statements
}
optional
• If you do NOT want execution to continue (flow
into) the next case, you need to insert a break
statement.
Notation
• { and } are used to group statements together
– function definition, if and else clauses, and other
statements we haven't done yet: switch, for, do while.
• ( and ) are used
– condition part of an if statement
• if (Math.random()>.5)
– set order of operations in a calculation
• total = total + (total*taxrate);
– specify arguments in a function definition and
parameters in a function call
• Math.random()
Goal: new coin toss
• Replace the player move of clicking a
button by clicking directly on the canvas.
• Place an image on the canvas at the place
clicked.
• Put directions on the canvas.
• http://faculty.purchase.edu/jeanine.meyer/
html5workshop/wkshopcoinflip.html
Remember: the context object
• ctx =
document.getElementById('canvas'),getCo
ntext('2d');
• You can have multiple canvas elements
and one of these for each one.
• This line must be executed after body
element is read in (loaded).
drawing image from file
• HTML supports Image objects using code.
• Find and download new images or re-use
what you used before for the coin toss:
var head = new Image();
head.src = "head.gif";
…
drawImage(head, 10,20,100,100);
draws this image at 10,20, with width of 100
and height of 100.
drawing text
• You can set color, that is the style
• Just to show one more way to specify a
color (previous ways are the set of names
and using the rgb function):
– you can specify an red-green-blue value using
hexadecimal (base 16) values.
– values go from 00 to FF
ctx.fillStyle = "#dd00ff";
drawing text, cont.
• You specify the font:
ctx.font = "bold 10px Arial";
• Open up Word on your computer and see what
fonts are available.
ctx.fillText("Hello", 100,200);
Add images and text to one of your drawings.
Experiment.
Mouse click on a canvas
Need to set up the event on/for the canvas object
canvas1=document.getElementById('canvas');
creates an object that JavaScript can use.
canvas1.addEventListener('click',flip,false);
sets up JavaScript to listen for the click event and
when it occurs, invoke the function named flip.
Mouse cursor position
• One more thing: we want the coin head or tail to
be placed on the canvas where the click is
made.
• Challenge: the browsers handle this differently.
The following code works for Firefox, Chrome,
Safari:
if ( ev.layerX || ev.layerX == 0) {
mx= ev.layerX;
my = ev.layerY;}
else if (ev.offsetX || ev.offsetX == 0) {
mx = ev.offsetX;
my = ev.offsetY;
}
Adjustment
• Images are drawn starting at the upper left
corner.
• We want the image to be centered at the
position where the player clicked on the
screen.
• Assuming the mouse coordinates are
mx,my, and the image 100 x 100, then we
place the image at
mx-50, my-50.
Summary
• <html><head><title> </title>
• <script>
– variables
– init function definition, including addEventListener to
set up call to flip
– flip function definition
• </head>
• <body onload="init();">
– canvas element
• </body>
<html>
<head>
<title>Coin flip</title>
<script>
var ctx;
var canvas1;
var head = new Image();
var tail = new Image();
head.src = "head.gif";
tail.src = "tail.gif";
var coinwidth = 100;
var coinheight = 100;
function init() {
ctx =
document.getElementById('canvas').getContext('
2d');
canvas1 = document.getElementById('canvas');
canvas1.addEventListener('click',flip,false);
ctx.font = "italic 20px Accent";
ctx.fillStyle = "#dd00ff";
ctx.strokeRect(0,0,600,400);
ctx.fillText("Click on canvas to flip a
coin.",10,20);
}
function flip(ev) {
var mx;
var my;
ctx.clearRect(0,0,600,400);
if ( ev.layerX || ev.layerX == 0) {
mx= ev.layerX;
my = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) {
mx = ev.offsetX;
my = ev.offsetY;
}
if (Math.random()>.5) {
ctx.drawImage(head,mx-50,my-50,coinwidth,coinheight); }
else {
ctx.drawImage(tail,mx-50,my-50,coinwidth,coinheight);}
ctx.strokeRect(0,0,600,400);
ctx.fillText("Click on canvas to flip a coin.",10,20); }
</script>
</head>
<body onLoad="init();">
<canvas id="canvas" width="600" height="400">
Your browser doesn't support the HTML5 element
canvas.
</canvas>
</body>
</html>
Your task
• Get this working. Change colors, fonts, positions.
• Add scoring keeping!
• You will need to add
var headcount = 0;
var tailcount = 0;
• Add code to increase each of these in the right places.
headcount++; or tailcount++
• Add code to write out:
ctx.fillText("Heads: "+String(headcount)+
" and tails: " + String(tailcount),10,100);
Dice game
• … aka craps.
• Rules: player rolls 2 dice. This is a first throw. In
all cases, the value is the sum of the faces. On a
first throw, 7 or 11 win and 2, 3, 12 lose. If it is
neither of those (4, 5, 6, 8, 9, 10), then the status
shifts to follow-up throw and the value just rolled
is 'the point'.
On follow throw, the point wins and 7 loses. If
neither happen, play continues as followup
throws. The game can keep going!
Dice game logic
In pseudo-code / English
• If it is a first throw, then we use these
rules, that is, work with these cases
• If it isn't (not a first throw, namely a
followup throw), then we use these other
rules, consider these cases.
Programming the Logic (game
rules) for craps
• Your code maintains a global variable that
is true if it is a first throw and false
otherwise. So it starts out as true. It is
global, meaning the var statement is
outside of any function, so the value stays
available.
• There is code that checks this value using
an if statement and then applies the
appropriate set of rules.
switch statement: mixture code and
pseudo-code
• switch(sum) {
case 7: case 11:
show a win
break:
case 2: case 3: case 12:
show a loss
break:
default: …
set up to be follow-up throw
}
Outline of logic: DO THIS
if (condition) {
switch () {
statements
}
}
else {
switch () {
statements
}
}
General programming concepts
Places to hold data
• Variables: Issue of scope and access
– Global variables
– Local variables
– Properties of objects (also have issues of
scope and access)
• Visible element on screen
JavaScript
• Global variables: defined outside of any
one function, within the script tag. Can be
accessed and modified by code within
functions.
<script>
var score = 0;
• Local variables: within a function. Only
lasts during invocation of function. Only
accessible within function.
Overview
• Representation of information. How is
everything/anything represented 'in' the
computer (in storage)?
– ANSWER: everything is represented using 1s and 0s.
What the 1s and 0s mean depends on what the
information is, for example, the datatype
• whole number, number with fraction, true/false value,
character string, other…
• Expressions and operators
Storage
• Everything (data and programs) is stored in the
circuitry of 'the computer'.
• The circuitry includes transistors that are
switches: on or off states, 0 or 1. Each switch is
called a bit.
• So….numbers are stored using the binary (base
2) system
• Symbols (characters, letters, etc.) are stored
using agreed upon systems of encoding
– ASCII: 8 bits per character
– UNICODE: 16 bits per character
Why?
• Why not use circuits that can more easily
represent numbers using the decimal
(base 10) system?
• Answer: Easier to make on/off switches
than something with 10 states. Easier to
build circuitry for calculations for the base
2 addition and base 2 times tables than
the ones you remember…
Recall base 10
• Recall 1s column, 10s column, 100s
column
• Recall borrowing (re-grouping) and
carrying
• Do problem(s)
Base 2
• Same principle
• 1s column, 2s column, 4s column, ????
• Do problem(s)
Joke
Explain joke on shirt
Base 16
• Hexadecimal: used for quick way to
describe bits, mostly commonly for color
coding
• Symbols used are 0, 1, 2, …, 9, A, B, C,
D, E, F
• You have seen color coding: RGB (red,
green blue) in hexadecimal
FF0000 is red
00FF00 is green
??
Numbers with fraction part
Aka numbers with a decimal point
• How to represent?
• ANSWER: floating point numbers
aka scientific notation
– 3.4521 * 102 is the same as 345.21 * 100
– Terminology: 3.4521 (or 345.21) is the mantissa or
significand and the 2 (or 0) is the exponent.
• Computer format: use 2 or 16 in place of 10
• Example using 32 bits:
– 1 bit for the sign (0 for +, 1 for -)
– 8 bits for the exponent
– 23 bits for the mantissa (width, i.e., 23, is the
precision)
Characters
• ASCII coding
The character A
The character a
The character 1
The character 2
….
is represented by 01000001
is represented by 01100001
is represented by 00110001
is represented by 00110010
• Unicode is a 16 bit format big enough
(hopefully) for all the world's languages
String of characters
…such as a name or a label or a piece of
text
• Fixed length: allocate 1 byte (8 bits) for
each character
– UNICODE 2 bytes
• Variable length: store string in two parts
– One part holds length as a number and
pointer (address) of the whole string
– String itself
Boolean
• Named after George Boole
• True / False
• Theoretically: 1 bit, 0 for false, 1 for true
but
• The addressability requirement means it
could be 1 byte or even bigger
• String of Booleans can be combined.
– A byte can represent the answer to 8
true/false questions.
Homework
• Catch up: favorite sites, first coin toss,
crooked coin toss, static drawings, coin
toss on canvas
• Work on dice game.
• Review charts
– Look up terms on-line and/or in my book.