Tải bản đầy đủ - 0 (trang)
6 (Optional) Solving Problems with C#: The Tangram Puzzle

6 (Optional) Solving Problems with C#: The Tangram Puzzle

Tải bản đầy đủ - 0trang

Figure8.20:TheCat

Tosolvetangrampuzzlesonthecomputerweneedtodragpolygonsto

newlocationsandrotatethem.Weusethemousetodragpolygonsand

keypressestorotatethem.WeusetheBkey(forback)torotatea

polygoncounterclockwiseandusetheFkey(forforward)torotatethe

polygonclockwise.Withthesetranslationandrotationoperationswecan

movethepuzzlepiecestoformotherdesigns.Weleavetotheexercises

theimplementationofanoperationtoreflecttheparallelogram,ineffect

flippingitover,toallowtheusertoformevenmoreshapes.



CompletingtheC#Code

AswedidinExample8.5,wecreateaGraphicsPathandaRegion

foreachpolygon.Buttheboundingrectangleisnotacloseenough

approximationtoeachpolygonwhenwehaveseveralpolygonsthatmay

beclosetogether.Togetabetterapproximationweusethe

GetRegionScansmethodtoreturnanarrayofrectanglesthatasa

groupapproximatethepolygon.





Figure8.21:Thetangrampuzzle

AsinExample8.5,westorethecurrentlocationofthepolygonwhenthe

userpressesthemouseinit,butherewehavetoloopthroughtheseven

polygonstofindinwhichone,ifany,theuserpressedthemouse.

Iftheuserdragsoneofthepolygons,wetranslateittothenewposition.

PressingtheBkeywillrotatethatpolygoncounterclockwise(back)by

threedegrees.PressingBwillrotatecounterclockwiseby30º.For

forwardrotations,weusetheFandFkeys.Figure8.21showstheinitial

tangramintheformofasquare.Figure8.22showsthepiecesmovedto



formacat.





Figure8.22:Makingacat

Example8.7:TangramSolver.cs



/*Startwiththesevenpolygonsforming

*asquare.Dragthemwiththemouseandrotate

*themwiththeFandBkeystoformothershapes.

*/



usingSystem;

usingSystem.Drawing;

usingSystem.Drawing.Drawing2D;

usingSystem.Windows.Forms;

publicclassTangramSolver:Form{

privatePointF[][]vertices=newPointF[7][];//Note

privateBrush[]color={Brushes.Red,Brushes.Blue,//Note

Brushes.Yellow,Brushes.Magenta,Brushes.Cyan,

Brushes.Pink,Brushes.Orange};

privateGraphicsPath[]polygon=newGraphicsPath[7];

privateRegion[]region=newRegion[7];

privatefloat[]oldX=newfloat[7];

privatefloat[]oldY=newfloat[7];

privateintindex;//polygontotranslateorrotate





publicTangramSolver(){

Size=newSize(500,500);

Text="TangramSolver";

BackColor=Color.White;

vertices[0]=newPointF[3]{newPointF(0,200),

newPointF(100,100),newPointF(200,200)};//Note

vertices[1]=newPointF[3]{newPointF(100,100),

newPointF(200,0),newPointF(200,200)};

vertices[2]=newPointF[3]{newPointF(0,0),

newPointF(100,0),newPoint(0,100)};

vertices[3]=newPointF[3]{newPointF(0,100),

newPointF(50,150),newPointF(0,200)};

vertices[4]=newPointF[3]{newPointF(50,50),

newPointF(150,50),newPointF(100,100)};

vertices[5]=newPointF[4]{newPointF(0,100),

newPointF(50,50),

newPointF(100,100),newPointF(50,150)};

vertices[6]=newPointF[4]{newPointF(100,0),

newPointF(200,0),

newPointF(150,50),newPointF(50,50)};

for(inti=0;i
polygon[i]=newGraphicsPath();

polygon[i].AddPolygon(vertices[i]);

region[i]=newRegion(polygon[i]);

}

}

protectedoverridevoidOnMouseDown(MouseEventArgse){

boolfound=false;

inti=0;

while(!found&&i
RectangleF[]scans=

region[i].GetRegionScans(newMatrix());//Note

intj=0;

while(!found&&j
if(scans[j].Contains(e.X,e.Y)){

oldX[i]=e.X;

oldY[i]=e.Y;



index=i;

found=true;

}

j++;

}

i++;

}

base.OnMouseDown(e);

}

protectedoverridevoidOnMouseUp(MouseEventArgse){//Note

region[index].Translate(e.X-oldX[index],e.Y-oldY[index]);

oldX[index]=e.X;

oldY[index]=e.Y;

Invalidate();

base.OnMouseUp(e);

}

protectedoverridevoidOnPaint(PaintEventArgse){

Graphicsg=e.Graphics;

for(inti=0;i
g.FillRegion(color[i],region[i]);//Note

base.OnPaint(e);

}

protectedoverridevoidOnKeyPress(KeyPressEventArgse){

floatangle=0;

switch(e.KeyChar){

case'b':angle=-3;//Note

break;

case'B':angle=-30;

break;

case'f':angle=3;

break;

case'F':angle=30;

break;

}

Matrixm=newMatrix();//Note

m.RotateAt(angle,

newPointF(oldX[index],oldY[index]));//Note1



region[index].Transform(m);//Note1

Invalidate();

base.OnKeyPress(e);

}

publicstaticvoidMain(){

Application.Run(newTangramSolver());

}

}



Note



1. privatePointF[][]vertices=newPointF[7]

[];

Wecreateanarrayofarrays,withonearrayforthe

verticesofeachpolygon.

2. privateBrush[]color={Brushes.Red,

Brushes.Blue,

Wepickadifferentcolorforeachpolygon.

3. vertices[0]=newPointF[3]{new

PointF(0,200),

newPointF(100,100),new

PointF(200,200)};

Wecreateeachpolygonusingthecoordinatesshownin

Figure8.19.

4. RectangleF[]scans=

region[i].GetRegionScans(new

Matrix());

Whentheuserpressesthemouse,wecheckeach

polygontofindiftheuserpressedthemouseinit.The

GetRegionScansmethodreturnsaRectangleFarray

ofrectanglesthattogetherapproximatethepolygon.We

useanidentitymatrixfortheargument,becauseweare

nottransformingthepolygonnow.



5. while(!found&&j
Wecheckifthemousewaspressedinthepolygonby

checkingwhetheritwaspressedinoneoftherectangles

ofthescan.Ifitwas,wesavethecoordinatesandthe

indextousefortranslatingandrotating.

6. protectedoverridevoid

OnMouseUp(MouseEventArgse)

Whentheuserreleasesthemouse,wetranslatethe

polygonselectedwiththemousedownandsavethe

coordinatesforthenextoperation.

7. g.FillRegion(color[i],region[i]);

Wedraweachpolygoninadifferentcolor.

8. case'b':angle=-3;

Pressingthebkeycausesarotationof3º

counterclockwise.

9. Matrixm=newMatrix();

AMatrixrepresentsatransformation.Wedonotneedto

knowthedetailsofthisrepresentationbecausethe

Matrixclassprovidesoperationsthatencapsulatethem.

Thisistheidentitymatrixwewilltransformbyrotation.

10. m.RotateAt(angle,

new

PointF(oldX[index],oldY[index]));

Weadjustthematrixtorepresentarotationbythe

specifiedanglearoundthepointwherethemousewas

released.

11. region[index].Transform(m);

Weapplytherotationtotheselectedpolygon.



TestingtheCode

Figure8.22showsthepolygonsdraggedandrotatedintotheshapeofa

cat.TestYourUnderstandingquestions23and24provideothertestsof

thetangramsolver.

TheBIGPicture

Weusethemousetodragpolygonsandthekeyboardtorotatethem.

Withtheseoperations,wecansolvetangrampuzzles.



TestYourUnderstanding

22. InExample8.7,intheOnMouseUpmethod,savethecoordinates

(e.X,e.Y)beforetranslatingthepolygon.Runthemodifiedprogram

toseewhathappens.

23. RunthetangramsolverofExample8.7totransformtheseven

polygonsintotheduckshowninFigure8.23.





Figure8.23:Theduck

24. RunthetangramsolverofExample8.7totransformtheseven

polygonsintotheboatshowninFigure8.24.





Figure8.24:Theboat



Summary

IntheOnPaintmethodweincludestatementsdescribingwhat

textandshapeswewanttodraw,butourprogramdoesnotcall

thepaintmethod.The.NETsystemcallsourOnPaintmethod

wheneventscauseourwindowtoneedrepainting.Forexample,

iftheuserminimizesandrestoresthewindow,itneedstobe

redrawn.Theoperatingsystemhandlestheeventsfromtheuser,

passingthemto.NET,whichcallsourOnPaintmethodto

redrawourwindow.BecauseweuseonlyaFormandnoother

controls,wecanhandlethepainteventdirectly.Inthenext

chapterwewilllearntorespondtobuttonclicks,checkbox

selections,andotheruser-interface-generatedevents.

TheGraphicsclasshasmethodstodrawlines,rectangles,

ellipses,arcs,pieshapes,andpolygons,andtofillanyofthem

(exceptthelineandarc).Wespecify

Alinewiththecoordinatesofitsendpoints

Arectanglewithitsupperleftcorner,width,andheight

Anellipsewiththeargumentsforitsboundingrectangle

Anarcwiththeargumentsforanoval,astartangle,andasweep

angle

Apolygonwithanarrayofvertexpoints

Weuseapenfordrawingandabrushforfillingshapes.

TheDrawStringmethodoftheGraphicsclasshasfive

parameters:thestringtodraw,thefont,abrush,andthexandy

positionsatwhichtodrawit.Wecanconstructafont,specifying

afontname,pointsize,andstyle.C#usesseveralgenericfont

namesandanyinstalledfont.Thestylecanbecombinationsof

regular,bold,italic,underline,orstrikeout.

TheColorclassprovidesmanypredefinedcolorsandallowsus



toconstructothercolorsspecifyingtheirred,green,andblue

componentsasintegersfrom0to255.

WehandletheMouseDowneventintheOnMouseDownmethod

andtheMouseUpeventintheOnMouseUpmethod.The

MouseEventArgsprovidestheXandYvaluesatwhichthe

mousewaspressedorreleased.WehandletheKeyDown,

KeyUp,andKeyPresseventsintheOnKeyDown,OnKeyUp,and

OnKeyPressmethods.TheKeysenumerationprovidesavalue

foreachkey.TheKeyCodepropertyofKeyEventArgsprovides

thekeythatwasdownorup.TheKeyCharpropertyof

KeyPressEventArgsprovidesthelogicalcharacterdenoted,

perhapsbymorethanonephysicalkeypress.Thetangram

puzzledemonstratestheuseofkeysandthemouse.



SkillBuilderExercises

1. Thefollowingcode,showingthekeyeventsgeneratedwhentheuser

typesanuppercaseT,doesnotlisttheseeventsintheorderinwhich

theyoccur.Rearrangethelisttoreflecttheorderinwhichtheyare

generated.

KeyPress,KeyDown,KeyUp,KeyDown,KeyUp

2. Describewhatthefollowingprogramwilldisplay.

usingSystem.Drawing;

usingSystem.Windows.Forms;

publicclassSkill:Form{

publicoverridevoidOnPaint(PaintEventArgse){

inth=DisplayRectangle.Height;

intw=DisplayRectangle.Width;

Graphicsg=e.Graphics;

g.DrawRectangle(Pens.Blue,w/4,h/4,w/2,h/2);

}

}



3. IdentifyanyerrorsinthefollowingFontconstructor.

newFont("FontFamily.GenericSansSerif",

Font.Italic);

Answers

1. KeyDown,KeyDown,KeyPress,KeyUp,KeyUp

2. Acenteredrectanglewhosedimensionsarehalfthoseoftheform

3. newFont(FontFamily.GenericSansSerif,24,

FontStyle.Italic);



CriticalThinkingExercises

4.



Whichofthefollowingwilldrawthearcshownabovewithcenter

at(40,40)andradius40?

a. g.DrawArc(Pens.blue,0,0,40,40,0,90);

b. g.DrawArc(Pens.blue,40,40,0,0,0,90);

c. g.DrawArc(Pens.blue,0,0,80,80,90,90);

d. g.DrawArc(Pens.blue,0,0,80,80,90,180);



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

6 (Optional) Solving Problems with C#: The Tangram Puzzle

Tải bản đầy đủ ngay(0 tr)

×