Lecture: Repetition

advertisement
Practical Programming
COMP153-08S
Lecture: Repetition
Programming So Far
•
•
•
•
•
First: Controls, Properties, Events
Second: Types and Arithmetic
Third: Variables (Global/Local)
Fourth: Decisions If and Select
This week: Repetition
Repetition
• Making things happen more than
once
• This is what computers are good at
– Doing simple repeated tasks
• 1. The user can repeat commands
• 2. The computer can repeat
Computer Repeating
• Can use Timer controls
– Useful when you want things to repeat
slowly – eg: graphics, animation
• Can use looping statements
– When you simply want to get a task
done as quickly as possible
– Easier to program than timers
Timer Control – Digital Clock
Timer dissected
•
•
•
•
Set Timer controls first:
Timer1.enabled = True
Timer1.Interval = 1000 (1 second)
Label1.Text = TimeString( ) (code for timer)
– Get current time from system clock as a string.
• Can change the interval to see the timer
control more explicitly
An Aside - Graphics
•
•
•
•
Top left is (0,0)
x-axis increases left to right
y-axis increases top to bottom
(x,y) is a pixel position
Timer Examples
• Adding to a
counter
• Moving a control
Timer code
• Import picture set SizeMode
PictureBox1.Left = PictureBox1.Left + 2
If PictureBox1.Left > Me.Width PictureBox1.Width Then
PictureBox1.Left = 0
End If
Bouncing lily
Dim GoingRight As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
Timer1.Enabled = True
Timer1.Interval = 1
GoingRight = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Timer1.Tick
If GoingRight Then
PictureBox1.Left = PictureBox1.Left + 2
If PictureBox1.Left > ActiveForm.Width - PictureBox1.Width Then
GoingRight = False
End If
Else
PictureBox1.Left = PictureBox1.Left - 2
If PictureBox1.Left = 0 Then
GoingRight = True
End If
End If
End Sub
Repetition statements
• The For / Next statement
For x = 1 To 5
. . .
Next
• Note: the variable x must be
declared (Dim x as Integer).
Moving Image without timer
Dim x As Integer
For x = 1 To 5
PictureBox1.Left = PictureBox1.Left + 2
MessageBox.Show(x)
Next
Creating new forms
dynamically
• When you want to copy the form
you have designed as your program
runs
– Dim two As Form1
– two = new Form1()
• and
– two.Show()
Example
• Another example
Dim x as Integer
Dim f as Form1
For x = 100 To 200 Step 30
f = New Form1()
f.Width = x
f.Show()
Next
THE END
of the lecture
Download