23
Learning to Program with Learning to Program with C# - 9 C# - 9 1 Unit 9 Unit 9 Completed a whistle-stop tour Completed a whistle-stop tour of programming language and of programming language and C# basics C# basics Now we will write a program Now we will write a program or two from scratch or two from scratch

Learning to Program with C# - 91 Unit 9 Completed a whistle-stop tour of programming language and C# basicsCompleted a whistle-stop tour of programming

Embed Size (px)

Citation preview

Learning to Program with C# Learning to Program with C# - 9- 9

11

Unit 9Unit 9

• Completed a whistle-stop tour of Completed a whistle-stop tour of programming language and C# programming language and C# basicsbasics

• Now we will write a program or two Now we will write a program or two from scratchfrom scratch

Learning to Program with C# Learning to Program with C# - 9- 9

22

A word on program stylesA word on program styles• Rocketry is an animation, or simulationRocketry is an animation, or simulation

• Animation: drawing and redrawing graphical shapes to Animation: drawing and redrawing graphical shapes to give the appearance of movementgive the appearance of movement

• Simulation: modelling the behaviour of a real world Simulation: modelling the behaviour of a real world systemsystem

• Many other program stylesMany other program styles• Data processingData processing

– read data in, process it, output it againread data in, process it, output it again• Search programsSearch programs

– look for a solution to a problem by creating and assessing look for a solution to a problem by creating and assessing multiple different possibilities along the waymultiple different possibilities along the way

• Windows-based application – you're used to seeing themWindows-based application – you're used to seeing them

• Takes time to learn about a new styleTakes time to learn about a new style• so here, we will stick with the animation/simulation styleso here, we will stick with the animation/simulation style

Learning to Program with C# Learning to Program with C# - 9- 9

33

ProblemProblem

• Draw a spoked wheel rolling across Draw a spoked wheel rolling across the screenthe screen

• Great. Now what?Great. Now what?• Problem solvers apply a huge number of Problem solvers apply a huge number of

heuristicsheuristics in the problem solving process. in the problem solving process. You will learn these over time You will learn these over time

• We'll apply some of them hereWe'll apply some of them here

Learning to Program with C# Learning to Program with C# - 9- 9

44

Heuristic 1: Can I solve a Heuristic 1: Can I solve a simpler, related, problem first?simpler, related, problem first?

• Version 2Version 2– Draw a rotating spoked wheel, not movingDraw a rotating spoked wheel, not moving

• Version 3Version 3– Draw a single rotating spoke, like a second Draw a single rotating spoke, like a second

hand on a watchhand on a watch

• Version 4Version 4– Draw a dot rotating about a fixed point – the Draw a dot rotating about a fixed point – the

end of the spoke/second handend of the spoke/second hand

• If I can solve each one of these in turnIf I can solve each one of these in turn– it is a relatively simple step to get to the next it is a relatively simple step to get to the next

oneone

Learning to Program with C# Learning to Program with C# - 9- 9

55

Heuristic 2: Play with the Heuristic 2: Play with the problemproblem

– Often, take pen & paper, and mess around until Often, take pen & paper, and mess around until the light dawns – until you make connections with the light dawns – until you make connections with things you do know aboutthings you do know about

– e.g. I might get:e.g. I might get:– Realisations come fromRealisations come from

this playing:this playing:• position of moving point isposition of moving point is

dependent on thedependent on theangle, and the radiusangle, and the radiusof the point from the of the point from the centre of rotationcentre of rotation

• using trigonometry, theusing trigonometry, thedistances x and y can bedistances x and y can becalculatedcalculated

• if we know the central pointif we know the central pointwe can calculate the outerwe can calculate the outerpointpoint

RadiusRadius

AngleAngleRoute ofRoute ofpointpoint

xx

yy

Learning to Program with C# Learning to Program with C# - 9- 9

66

Heuristic 3: What kind of Heuristic 3: What kind of behaviour am I behaviour am I considering?considering?• Primarily, is itPrimarily, is it

– a sequence of steps?a sequence of steps?– a repetitive activity?a repetitive activity?– a conditional activity?a conditional activity?

• It's repetitiveIt's repetitive– repeatedlyrepeatedly

• erase previous drawing of ballerase previous drawing of ball• recalculate the position of the ballrecalculate the position of the ball• draw in new version of balldraw in new version of ball• delay a moment, so we can see itdelay a moment, so we can see it

• Notice that primarily it's repetitive, but that on Notice that primarily it's repetitive, but that on each repeat, we're performing a sequence of each repeat, we're performing a sequence of instructionsinstructions

Learning to Program with C# Learning to Program with C# - 9- 9

77

Heuristic 4: What tools do I Heuristic 4: What tools do I have available, and will they have available, and will they

help?help?• Trigonometric functionsTrigonometric functions

– available in Math class, in System namespaceavailable in Math class, in System namespace– good, because sine and cosine are needed to good, because sine and cosine are needed to

calculate the point's positioncalculate the point's position

• Animation classAnimation class– this contains a graphics canvas object that has this contains a graphics canvas object that has

drawing functions defined on itdrawing functions defined on it– good, because we need to go drawinggood, because we need to go drawing

• Repetition and sequence instructions Repetition and sequence instructions availableavailable– good, because we're doing that kind of activitygood, because we're doing that kind of activity

Learning to Program with C# Learning to Program with C# - 9- 9

88

Heuristic 5: What objects Heuristic 5: What objects needed?needed?

• A A RotatingPointRotatingPoint object object– it can draw itselfit can draw itself– it knows where it is and how to work out where to go it knows where it is and how to work out where to go

nextnext

• An An AnimationAnimation object object– for the Point to draw onfor the Point to draw on– this has already been written, we simply reuse itthis has already been written, we simply reuse it

• An An AnimateAnimate class to set it off class to set it off– it will run a timer, repeatedly telling the point to it will run a timer, repeatedly telling the point to

redraw itselfredraw itself– later, it could handle many objectslater, it could handle many objects– a driver or startup class (like ExecuteMission)a driver or startup class (like ExecuteMission)

Learning to Program with C# Learning to Program with C# - 9- 9

99

So, how to get started on So, how to get started on a new project…a new project…

• Open up AnimateObjects.slnOpen up AnimateObjects.sln– found in AnimateObjects folderfound in AnimateObjects folder

• This is a bare minimum starting pointThis is a bare minimum starting point– contains a skeleton version of the Animate classcontains a skeleton version of the Animate class

• We need a new classWe need a new class– RotatingPointRotatingPoint– Press mouse button 2 in the class viewer, then Press mouse button 2 in the class viewer, then

choose Add/Add Classchoose Add/Add Class– In the Add Class wizardIn the Add Class wizard

• type in RotatingPoint for the name of the classtype in RotatingPoint for the name of the class• and a description – manages a point rotating round a and a description – manages a point rotating round a

fixed centre – or somethingfixed centre – or something

Learning to Program with C# Learning to Program with C# - 9- 9

1010

Add a method to Add a method to RotatingPointRotatingPoint

• In Class View, select RotatingPointIn Class View, select RotatingPoint– press button 2, then Add/AddMethodpress button 2, then Add/AddMethod

• In the wizardIn the wizard– method name is Redrawmethod name is Redraw– give a description – something like give a description – something like redraw the redraw the

point assuming a time interval has passedpoint assuming a time interval has passed– ignore the rest, there will be no parameters and ignore the rest, there will be no parameters and

we are not returning anythingwe are not returning anything

• See what the wizard producesSee what the wizard produces– you could have typed this yourself – once you you could have typed this yourself – once you

have become proficient, you may find it easier!have become proficient, you may find it easier!

Learning to Program with C# Learning to Program with C# - 9- 9

1111

Add a field member to the classAdd a field member to the class• In Class View, with RotatingPoint selectedIn Class View, with RotatingPoint selected

– button 2/Add/Add Fieldbutton 2/Add/Add Field– Field Access – choose Field Access – choose privateprivate

• we don't want external classes to see this valuewe don't want external classes to see this value

– Field Type – choose Field Type – choose int int • for integer or whole numbersfor integer or whole numbers

– Field Name – type XField Name – type X• this is going to represent the X position of the pointthis is going to represent the X position of the point• type in a description explaining thistype in a description explaining this

• Once Finished, see the addition to the Once Finished, see the addition to the code in the class's windowcode in the class's window

Learning to Program with C# Learning to Program with C# - 9- 9

1212

Add more field membersAdd more field members• One for the point's Y positionOne for the point's Y position

– Could do this using copy and paste in the RotatingPoint Could do this using copy and paste in the RotatingPoint windowwindow

– then change occurrences of X to Ythen change occurrences of X to Y

• and some for centre position, angle & radiusand some for centre position, angle & radius– CentreX and CentreY and Angle and RadiusCentreX and CentreY and Angle and Radius– note that Angle will need to be note that Angle will need to be doubledouble not not intint

• And finally another for the Canvas to draw onAnd finally another for the Canvas to draw on– this is of type Graphics, call it Canvasthis is of type Graphics, call it Canvas

• In order for the system to understand where In order for the system to understand where Graphics comes from,Graphics comes from,– add add using System.Drawing;using System.Drawing; after after using System;using System; at the at the

head of the class – see head of the class – see Animate.csAnimate.cs for comparison for comparison

Learning to Program with C# Learning to Program with C# - 9- 9

1313

Extending the constructor Extending the constructor methodmethod

• When we construct a rotating point, we need When we construct a rotating point, we need to knowto know– centre point (x,y), radius, and graphical canvas to centre point (x,y), radius, and graphical canvas to

draw ondraw on

• Extend constructor methodExtend constructor method– so these are supplied as parametersso these are supplied as parameters

• In method called RotatingPointIn method called RotatingPoint– (this is the constructor)(this is the constructor)– add the following inside the () after the nameadd the following inside the () after the name

Graphics g, int centreX, int centreY, int radiusGraphics g, int centreX, int centreY, int radius

– each parameter is given a type then a name, and each parameter is given a type then a name, and they're all separated with commasthey're all separated with commas

Learning to Program with C# Learning to Program with C# - 9- 9

1414

The body of the constructorThe body of the constructor• We simply assign the parameter values passed We simply assign the parameter values passed

to the constructor to the corresponding internal to the constructor to the corresponding internal field of the object e.g.field of the object e.g.

CentreX = centrex;CentreX = centrex;

• Do this for all four parametersDo this for all four parameters• Also need to set starting values for X, Y and Also need to set starting values for X, Y and

AngleAngle– refer back to earlier picturerefer back to earlier picture– suggest Angle is zero, and so X is zero, Y is Radius suggest Angle is zero, and so X is zero, Y is Radius

relative to the centre pointrelative to the centre point• set Angle… set Angle… Angle = 0;Angle = 0; • set X… set X… X = CentreX;X = CentreX;• set Y… set Y… Y = CentreY + RadiusY = CentreY + Radius

Learning to Program with C# Learning to Program with C# - 9- 9

1515

Take a moment…Take a moment…

• to look at what you've createdto look at what you've created• Look in the class view, at this Look in the class view, at this

RotatingPoint class – neat row of RotatingPoint class – neat row of methods and fieldsmethods and fields

• Look in the object browserLook in the object browser– you can navigate around the various you can navigate around the various

componentscomponents

Learning to Program with C# Learning to Program with C# - 9- 9

1616

Now for action – Redraw Now for action – Redraw methodmethod

• Each time this is called we want toEach time this is called we want to– blank out the pointblank out the point

• can do this by drawing it in the background colourcan do this by drawing it in the background colour

– calculate its new positioncalculate its new position– draw it at this positiondraw it at this position

• Add these steps as Add these steps as commentscomments to the to the body of the method (in between the body of the method (in between the {}{} ) )– a comment is just some English text to help a comment is just some English text to help

us understand what is going onus understand what is going on– it it mustmust start with // start with //

• two forward facing slashestwo forward facing slashes

Learning to Program with C# Learning to Program with C# - 9- 9

1717

Code to blank out the pointCode to blank out the point• Under the comment about blanking outUnder the comment about blanking out

– we want to use one of the drawing methods available on our we want to use one of the drawing methods available on our CanvasCanvas

– So, type So, type CanvasCanvas and then a dot and then a dot– Visual Studio will show you a menu of all members available for Visual Studio will show you a menu of all members available for

a Graphics objecta Graphics object• choose choose FillEllipseFillEllipse by double clicking on it by double clicking on it

– Then type an open bracket, because we wish to call this methodThen type an open bracket, because we wish to call this method– VS shows you the parameters and their typesVS shows you the parameters and their types

• it may indicate there are different versions of the method tooit may indicate there are different versions of the method too

– Type in exactlyType in exactlyAnimate.Background, X-1, Y-1, 3, 3 );Animate.Background, X-1, Y-1, 3, 3 );

– See how VS assists you as you typeSee how VS assists you as you type

Learning to Program with C# Learning to Program with C# - 9- 9

1818

Add in the following codeAdd in the following code

• Under the update comment, addUnder the update comment, addAngle = Angle + (2.0 * Animate.OneDegree);Angle = Angle + (2.0 * Animate.OneDegree);

X = CentreX + (int)( (double)Radius * Math.Sin( Angle X = CentreX + (int)( (double)Radius * Math.Sin( Angle ) );) );

Y = CentreY + (int)( (double)Radius * Y = CentreY + (int)( (double)Radius * Math.Cos( Angle ) );Math.Cos( Angle ) );

• and then repeat the drawing code for and then repeat the drawing code for the final partthe final part– but replace but replace BackgroundBackground with with ForegroundForeground

Learning to Program with C# Learning to Program with C# - 9- 9

1919

Back in the Animate class…Back in the Animate class…• Add the following code into the Main method, between the Add the following code into the Main method, between the

{}{}AnimationForm AF = new AnimationForm( 400, 400 );AnimationForm AF = new AnimationForm( 400, 400 );RotatingPoint RP = new RotatingPoint( AF.Canvas, 200, 200, 100 );RotatingPoint RP = new RotatingPoint( AF.Canvas, 200, 200, 100 );

for( int i=0; i<1000; i++ )for( int i=0; i<1000; i++ ){{

RP.Redraw();RP.Redraw();AF.Delay( 0 );AF.Delay( 0 );

}}

AF.WaitForQuit();AF.WaitForQuit();

– The first two lines create The first two lines create local variableslocal variables, like temporary object , like temporary object fields, AF and RP to hold newly created AnimationForm and fields, AF and RP to hold newly created AnimationForm and RotatingPoint objectsRotatingPoint objects

– The The for for loop then cycles the animation 1000 timesloop then cycles the animation 1000 times

Learning to Program with C# Learning to Program with C# - 9- 9

2020

You're now ready to run…You're now ready to run…

• Attempt to Start the programAttempt to Start the program– you may find errors from typingyou may find errors from typing– if you are unable to see where the if you are unable to see where the

errors have crept inerrors have crept in• look at the solution in look at the solution in

AnimateObjectsCompleteAnimateObjectsComplete

Learning to Program with C# Learning to Program with C# - 9- 9

2121

Turn the point into a spokeTurn the point into a spoke

• How could you now turn your rotating How could you now turn your rotating point into a sweeping second hand – one point into a sweeping second hand – one of the spokes of the wheelof the spokes of the wheel– Think about it…Think about it…

– instead of drawing a small circle on each instead of drawing a small circle on each redrawredraw• draw a line from the centre outwardsdraw a line from the centre outwards• try it out – you'll see there's a draw line method in try it out – you'll see there's a draw line method in

Graphics. It takes a Pen, not a Brush – you can find Graphics. It takes a Pen, not a Brush – you can find Pens in Graphics.Pens – there's White and Black and Pens in Graphics.Pens – there's White and Black and many others – let Visual Studio guide youmany others – let Visual Studio guide you

Learning to Program with C# Learning to Program with C# - 9- 9

2222

And then…And then…

• 4 spokes – how could you do that?4 spokes – how could you do that?

• and a rotating wheeland a rotating wheel– easy, add a circleeasy, add a circle

• and a moving, rotating, wheeland a moving, rotating, wheel– that centre point needs to move on each that centre point needs to move on each

redraw also – everything'll move along fine!redraw also – everything'll move along fine!

Learning to Program with C# Learning to Program with C# - 9- 9

2323

SummarySummary

• Created first application largely Created first application largely from scratch!from scratch!

• Briefly started looking at the Briefly started looking at the problem solving processproblem solving process– much more work to do heremuch more work to do here– explore new program stylesexplore new program styles– become happy with using the kind of become happy with using the kind of

heuristics discussed hereheuristics discussed here