Mark Dixon 2
Questions: Conditional Execution
• What is the result of (txtFah.value is 50):(txtFah.value >= 40)
• What will txtTax be after the following code has executed (txtSalary.value is 4589): If txtSalary.value < 5035 Then txtTax.value = 0 Else txtTax.value = txtSalary.Value * 0.20 End If
true
0
Mark Dixon 3
Session Aims & Objectives• Aims
– Introduce you to (invisible) data storage concepts, i.e. variables
• Objectives,by end of this week’s sessions, you should be able to:
– declare a variable– assign a value to a variable,
• using combination of literal values, operators, functions, and identifiers
– Determine whether a variable is in or out of scope at a given point in a piece of code
– Select a variable’s scope in your own program
Mark Dixon 4
Example: GuessNum – AnalysisSPECIFICATION
• User Requirements – need to keep children occupied/entertained, while
learning about maths
• Software Requirements– Functional:
–computer picks a number between 0 and 10–user enters a number–compare numbers and display appropriate
message– Non-functional
should be easy and fun to use
Mark Dixon 5
Example: GuessNum - Code<script language="vbscript">
Sub window_onLoad() Randomize parNum.innerText = Int(Rnd() * 10)End Sub
Sub btnGuess_onClick() If CInt(txtGuessNum.Value) = CInt(parNum.innerText) Then parResult.InnerText = "Correct" Else parResult.InnerText = "Wrong, please try again" End IfEnd Sub</script>
GenerateRandomNumberbetween 0 and 9
Check user's answeragainst correct answer
Mark Dixon 6
Variables (why?)• Variables useful for:
– storing information you don't want user to see
– reducing memory use
– speed up execution
– storing intermediate results of calculations temporarily:
• makes code easier to understand, &
• prevents need to re-calculate
– making code easier to read (short variable name instead of long object.property names)
Mark Dixon 7
Variables (what)• Variables have
– Identifier (name) – you choose this, used to refer to (reference) variable
– Value – you set/change this
23xName/Identifier
Value Memory
Mark Dixon 8
Variable declaration (how)• Variables must be declared,
using the following syntax (grammar):
Dim identifier
e.g. Dim weight Dim x Dim s Dim year
represents the name of the variable
Mark Dixon 9
Questions: Variable declaration
• Write a line of code that:
– Declares a variable called a
– Declares a variable called y
– Declares a variable called surname
Dim a
Dim y
Dim surname
Mark Dixon 10
Variable assignment (how)• Variables are assigned values,
using the following syntax:
identifier = expression
e.g. x = 5 weight = 109.45name = "Bob" s = "Hello "
Note: the data flows backwards (from right to left) read the = as 'becomes equal to'
Mark Dixon 11
Questions: Variable assignment
• Write a line of code that:
– Assigns the value of 23 to the variable y
– Puts 14.6 into a variable called x
– Assigns the value of ‘John’ to the variable surname
y = 23
x = 14.6
surname = "John"
Mark Dixon 13
Variables: Dry running• list the values of variables as each line is run:
Dim num1
Dim num2
num1 = 8
num2 = num1
num1 = 3
num2 = 2 + num1
-8
88
83
53
--
--
num1 num2
Mark Dixon 15
Dim d
Dim f
f = 3
d = f + 2
d = d + 4
d f
Questions: Dry running• Produce a dry run table for the following code:
3-
35
39
--
--
Mark Dixon 16
Example: GuessNum - Code<script language="vbscript">Option ExplicitDim GuessNum
Sub window_onLoad() Randomize GuessNum = Int(Rnd() * 10)End Sub
Sub btnGuess_onClick() If CInt(txtGuessNum.value) = GuessNum Then parResult.innerText = "Correct" Else parResult.innerText = "Wrong, please try again" End IfEnd Sub</script>
Create variable
Put (Write)RandomNumberinto variable
Use (Read) variable
Mark Dixon 17
Example: Moon Orbit – AnalysisSPECIFICATION
• User Requirements – need to keep children occupied/entertained, while
learning about the moon's orbit
• Software Requirements– Functional:
–Orbit of moon around earth should be animated–Children should be able to control speed and
direction– Non-functional
should be easy and fun to use
Mark Dixon 18
Problem solving: Pseudo-code• To solve problem
– think about how you would solve it manually (without computer)
– think of steps you would take
• Moon position– increase angle– move moon
• horizontal position• vertical position
• Convert to code
1
2
3
Mark Dixon 19
Trigonometry: In general
angle (ang)
hypotenuse (H)
opposite (O) = Sin(ang) * H
adjacent (A) = Cos(ang) * H
Mark Dixon 21
Trigonometry: Radians• Radians used by computers instead of degrees:
180 deg (3.1 rad)
90 deg (1.55 rad)
0 or 360 deg (0 or 6.2 rad)
(4.65 rad) 270 deg
rad = (deg/180) * 3.1
π
π/2
Mark Dixon 22
Example: Moon Orbit v1.0<html> <head><title>Moon orbit</title><meta http-equiv="x-ua-compatible" content="IE=10" /></head> <body style="background-color: Black;"> Angle: <input id="txtAngle" type="text" /> <input id="btnCalc" type="button" value="Calc" /> <img id="imgE" style="position: absolute" src="Earth.gif" /> <img id="imgM" style="position: absolute" src="Moon.gif" /> </body></html>
<script language="vbscript"> Sub window_onLoad() txtAngle.value = 0 imgE.style.posLeft = document.body.clientwidth / 2 imgM.style.posLeft = imgE.style.posLeft End Sub
Sub btnCalc_onClick() imgM.style.posLeft = imgE.style.posLeft + (Sin(txtAngle.value) * 150) imgM.style.posTop = imgE.style.posTop + (Cos(txtAngle.value) * 150) End Sub</script>
1
23
Mark Dixon 23
Example: Moon Orbit v1.1• Use:
– setInterval• change angle• move moon’s horizontal• move moon’s vertical
Mark Dixon 24
Example: Moon Orbit v1.1<html> <head><title>Moon orbit</title><meta http-equiv="x-ua-compatible" content="IE=10" /></head> <body style="background-color: Black;"> <input id="txtAngle" type="text" /> <img id="imgE" src="Earth.gif" style="position: absolute;" /> <img id="imgM" src="Moon.gif" style="position: absolute;" /> </body></html>
<script language="vbscript"> Sub window_onLoad() txtAngle.value = 0 imgM.style.posLeft = imgE.style.posLeft imgM.style.posTop = imgE.style.posTop + 150 window.setInterval "MoonRotate()", 50 End Sub
Sub MoonRotate() txtAngle.value = txtAngle.value + 0.025 imgM.style.posLeft = imgE.style.posLeft + (Sin(txtAngle.value) * 150) imgM.style.posTop = imgE.style.posTop + (Cos(txtAngle.value) * 150) End Sub</script>
Mark Dixon 25
<html> <head><title>Moon orbit</title><meta http-equiv="x-ua-compatible" content="IE=10" /></head> <body style="background-color: Black;"> <input id="txtAngle" type="text" /> <img id="imgE" src="Earth.gif" style="position: absolute;" /> <img id="imgM" src="Moon.gif" style="position: absolute;" /> </body></html>
<script language="vbscript"> Sub window_onLoad() txtAngle.value = 0 imgM.style.posLeft = imgE.style.posLeft imgM.style.posTop = imgE.style.posTop + 150 window.setInterval "MoonRotate()", 50 End Sub
Sub MoonRotate() txtAngle.value = txtAngle.value + 0.025 imgM.style.posLeft = imgE.style.posLeft + (Sin(txtAngle.value) * 150) imgM.style.posTop = imgE.style.posTop + (Cos(txtAngle.value) * 150) End Sub</script>
Problem: Intermediate Results• Intermediate result
stored in object(txtAngle.value)
– slow
– verbose
– visible
– takes lot of memory
Mark Dixon 26
<html> <head><title>Moon orbit</title><meta http-equiv="x-ua-compatible" content="IE=10" /></head> <body style="background-color: Black;"> <img id="imgE" src="Earth.gif" style="position: absolute;" /> <img id="imgM" src="Moon.gif" style="position: absolute;" /> </body></html>
<script language="vbscript">Option ExplicitDim ang
Sub window_onLoad() ang = 0 imgM.style.posLeft = imgE.style.posLeft imgM.style.posTop = imgE.style.posTop + 150 window.setInterval "MoonRotate()", 50 End Sub
Sub MoonRotate() ang = ang + 0.025 imgM.style.posLeft = imgE.style.posLeft + (Sin(ang) * 150) imgM.style.posTop = imgE.style.posTop + (Cos(ang) * 150) End Sub</script>
Solution: Variables
Declarationof Variable
Use ofVariable
shorter code invisible to user memory efficient faster execution
initial value
change value
Mark Dixon 27
Option Explicit: Variable undefined
• Must be first line of script
• Useful to force explicit variable declaration:
• Undeclared variables produce error message:
<script language="vbscript">Option ExplicitDim length length = 6 age = 5</script>
Mark Dixon 28
Variables: Name redefined
<script language="vbscript">Option ExplicitDim xDim yDim x x = 23 y = 10 23 = x</script>
• can't use same name again
Mark Dixon 29
Variables: Expected statement
<script language="vbscript">Option ExplicitDim xDim y
x = 23 y = 10 23 = x</script>
• destination can't be literal
Mark Dixon 31
Questions: Variable assignment 2• Write a line of code that:
– Increases the value of x by 2.89
– Divides Km by 1.6 and puts the result in Miles
x = x + 2.89
Miles = Km / 1.6
Mark Dixon 32
Variables: ErrorsOption ExplicitDim z
Sub window_onClick()Dim sDim xDim x y = 5 z = 5End Sub
OK, explicit variable declarationOK
OKOKOK Duplicate definition error. Variable not defined error.OK, as z is page level
Mark Dixon 33
Variable Scope (what)• Scope – accessibility/visibility
– Local (declared within procedure)
– Page (general declarations)
Mark Dixon 34
Variable Scope (How)• Page variables
– general declarations (top)
• Local variables:– in procedures
Option ExplicitDim mv
Sub btnCalc_onClick()Dim lv1 ...End Sub
Sub btnAdd_onClick()Dim lv2 ...End Sub
Mark Dixon 36
Variable Scope (why)• In short – Robustness of code/software
– Protection from accidental outside interference
• One of many responses to code that is– Difficult to maintain, and– Unreliable– House of cards phenomenon
• Prevent:– Uncontrolled and ad hoc interactions between code
• Always define things at lowest level needed
Mark Dixon 37
Variable Scope Errors
• Spot the error in the following: Option Explicit
Sub btnCalc_onClick()
Dim x
x = 0
lblTotal.innerText = "£" + x
End Sub
Sub btnQuit_onClick()
x = 0
lblTotal.innerText = "£" + x
End Sub
Variable not defined error
Mark Dixon 38
Example: Ball Char (v2.5)<html> <head><title>Ball Char</title><meta http-equiv="x-ua-compatible" content="IE=10" /></head> <body style="background-color: Lime;"> <img id="picBall" src="BallChar.gif" style="position: absolute;" /> <input id="txtSpeed" type="text" value="5" /> </body></html>
<script language="vbscript">
Sub window_onLoad() window.setInterval "MoveBall()", 50 End Sub Sub MoveBall() If (picBall.style.posLeft + picBall.width + txtSpeed.value) <= document.body.clientwidth Then picBall.style.posLeft = picBall.style.posLeft + txtSpeed.value Else txtSpeed.value = -txtSpeed.value End If End Sub </script> previous solution:
Uses text box – slow, visible
Mark Dixon 39
Example: Ball Char (v3)<html> <head><title></title><meta http-equiv="x-ua-compatible" content="IE=10" /></head> <body style="margin-left: 0"> <img id="picBall" src="BALLCHAR.gif" style="position: absolute" />
</body></html>
<script language="vbscript">Dim xSpeed
Sub window_onLoad() window.setInterval "MoveBall()", 50 xSpeed = 5 End Sub Sub MoveBall() Dim nxt nxt = picBall.style.posLeft + xSpeed If nxt + picBall.width <= document.body.clientWidth Then picBall.style.posLeft = nxt Else xSpeed = -xSpeed End If End Sub</script>
Using variables: shorter code invisible to user less memory faster execution
page variable
local variable
Mark Dixon 40
Question: Variable Scope• Will this compile?
Option ExplicitDim vDim x … Sub window_onLoad() Dim z x = 23 y = "there" z = 12 end
Sub btnTest_onClick() Dim y y = "hello" x = 67 z = 53 End Sub
Is x in scope?Is y in scope?Is z in scope?
Is y in scope?Is x in scope?Is z in scope?
YesNoYes
YesYesNo
Mark Dixon 42
Tutorial Exercises: Guess Num• LEARNING OBJECTIVE:
use variables to simplify and make code more dynamic
• Task 1: Get GuessNum example working. You will need to create the html for the text box, button, and labels.
• Task 2: Modify GuessNum to tell the user whether their incorrect guess was higher of lower than the correct number.
• Task 3: Modify GuessNum to only allow 5 attempts before picking a new number.
Mark Dixon 43
Tutorial Exercises: Moon Orbit• LEARNING OBJECTIVE:
use variables to simplify and make code more dynamic
• Task 1: Get Moon Orbit examples working (v1 to v1.2). The code is provided on the slides.
• Task 2: Modify your page to allow the user to stop speed up and change the moon's direction (v1.3). Use the existing code as inspiration.
• Task 3: Modify your page so that it makes a water noise when the mouse moves over the Earth, and the ohh noise over the moon. Use code from previous lectures as inspiration.
Mark Dixon 44
Tutorial Exercises: Ball Char• LEARNING OBJECTIVE:
use variables to simplify and make code more dynamic
• Task 1: Get the Ball Char (v3) example working.• Task 2: Add sound to the Ball Char (v3) example.• Task 3: Get the Ball Char moving diagonally, bouncing off all
four sides of the window.• Task 4: Modify your page so that it allows the user to control
how fast the ball character moves.