ebook img

Learning C# by Programming Games PDF

518 Pages·2019·8.796 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Learning C# by Programming Games

Wouter van Toll Arjan Egges Jeroen D. Fokker Learning C# by Programming Games Second Edition Learning C# by Programming Games Wouter van Toll • Arjan Egges • Jeroen D. Fokker Learning C# by Programming Games Second Edition 123 WoutervanToll ArjanEgges Rennes,France Utrecht,TheNetherlands JeroenD.Fokker DepartmentofInformationand ComputingSciences UtrechtUniversity Utrecht,TheNetherlands ISBN978-3-662-59251-9 ISBN978-3-662-59252-6 (eBook) https://doi.org/10.1007/978-3-662-59252-6 ©Springer-VerlagGmbHGermany,partofSpringerNature2013,2019 Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,whetherthewholeorpartofthematerialisconcerned, specificallytherightsoftranslation,reprinting,reuseofillustrations,recitation,broadcasting,reproductiononmicrofilmsorin anyotherphysicalway,andtransmissionorinformationstorageandretrieval,electronicadaptation,computersoftware,orby similarordissimilarmethodologynowknownorhereafterdeveloped. Theuseofgeneraldescriptive names,registered names,trademarks, servicemarks,etc.inthispublication doesnotimply, evenintheabsenceofaspecificstatement,thatsuchnamesareexemptfromtherelevantprotectivelawsandregulationsand thereforefreeforgeneraluse. Thepublisher,theauthors,andtheeditorsaresafetoassumethattheadviceandinformationinthisbookarebelievedtobe trueandaccurateatthedateofpublication.Neitherthepublishernortheauthorsortheeditorsgiveawarranty,expressedor implied,withrespecttothematerialcontainedhereinorforanyerrorsoromissionsthatmayhavebeenmade.Thepublisher remainsneutralwithregardtojurisdictionalclaimsinpublishedmapsandinstitutionalaffiliations. Coverdesign:CoverdesignbasedonagamespritedesignedbyHeinyReimes.Reusedbypermission. ThisSpringerimprintispublishedbytheregisteredcompanySpringer-VerlagGmbH,DE,partofSpringerNature. Theregisteredcompanyaddressis:HeidelbergerPlatz3,14197Berlin,Germany Preface Introduction Ifyouarereadingthis,thenweassumethatyouareinterestedinlearninghowtodevelopyourown computergames.Ifyoudonotyetknowhowtoprogram,don’tworry!Developingcomputergames isactuallyaperfectwaytolearnhowtoprograminmodernprogramminglanguages.Thisbookwill teachyouhowtoprograminC#withoutrequiringanypreviousprogrammingexperience.Itdoesso throughthecreationofcomputergames. Inouropinion,C#isthelanguageofchoiceifyouwanttolearnhowtoprogram.Thelanguageis verywellstructured,itcontainsmanymodernfeatures,anditisusedalotforgamedevelopmentand softwaredevelopmentingeneral.ComparedtoJava(anotherpopularprogramminglanguage),some thingsareslightlyeasiertounderstandinC#.Also,onceyouunderstandhowC#works,itisrelatively easytomovetoC++,whichisstilloneofthemostimportantprogramminglanguagesinthegame industry. ThisbookgivesyouathoroughintroductiontoC#andobject-orientedprogrammingingeneral.The unique aspect of this book is that it uses the structure and elements of computer games as a basis. For instance, the book contains chapters on dealing with player input, game objects, game worlds, levels,animation,physics,andintelligence.Alongtheway,youwilllearnaboutmanyprogramming concepts,suchasvariables,objects,classes,loops,collections,andexceptionhandling. We’ll also discuss various aspects of software design that are useful for game development.For example,weproposeusefultechniquesformanaginglevelsandgamestates,aswellasahierarchyof gameobjectsthattogetherformaninteractivegameworld.Furthermore,we willshowa numberof commonlyusedtechniquesingames,suchasdrawinglayersofsprites,rotating,scalingandanimating sprites, dealing with physics, handling interaction between game objects, and creating nice visual effects. Throughoutthebook,youwillcreatefourgamesthatgraduallybecomemorecomplicated.Wehave chosen differenttypes of games to show the variousaspects of game development.We start with a simpleshootinggame,we moveon to puzzlegamesconsistingof multiplelevels, andwe conclude withafull-fledgedplatformgamewithanimation,gamephysics,andintelligentenemies. Foreachofthesegames,thebookinvitesyoutowritethecodeyourself.Afterall,thebestwayto learnhowtoprogramistosimplydoit.Alongwiththisbook,we’vecreatedmanyexampleprojects thatyoucanuseforreference. v vi Preface TargetAudience Thisbookisaimedatpeoplewho: • areinterestedingameprogramming, • havelittletonoprogrammingexperiencesofar, • want to knowhow programmingreally works in general, so thatthey can use this knowledgein otherplacesaswell. Usinggamesasaguideline,thisbookwillteachyouthemostimportantelementsofobject-oriented programmingin C#. You’llalso learn aboutprogrammingon a moreabstractlevel, so thatyou can easilyteachyourselfotherprogramminglanguagesinthefuture. Duetothissetup,thebookisalsoveryusefulasatextbookforanintroductoryprogrammingcourse on university level (see the “For Teachers” section). However, our target audience is not limited to students:ifyourecognizeyourselfinthebullet-pointlistabove,thenyoucanbenefitfromthisbook, nomatterwhatyourbackgroundis. Structure ofThis Book This book is divided into five parts. Each part consists of multiple chapters, and each chapter has its own collection of example programs in which you learn new programming concepts. You can downloadtheseexampleprogramsfromthebook’swebsite. Overall,thefivepartsofthisbookhavethefollowingcontents: • PartIservesasanintroductiontoprogrammingingeneral,anditshowshowgamesaregenerally developed.Itintroducesbasicprogrammingconceptssuchasvariables,methods,andparameters. Italsodiscussesthegameloop:thebasisofeverygameprogram. • InPartIIofthebook,youwilldevelopyourfirstgamecalledPainter.Youwillfirstlearnhowtodeal withgameassetssuchasspritesandsounds.Then,youwilllearnabouttheif-instructionandloops such as for or while. Furthermore, you’ll learn about the basics of object-orientedprogramming. Youwillalsoseehowtocreateagameworldthatconsistsofmultipleinteractinggameobjects.In termsof generalprogrammingtechniques,thisis the mostimportantpartof the book.After this part,thegameswillbecomemorecomplicated,buttheywillreusemanyofthetechniquesyou’ve alreadylearnedinPartII. • In Part III, you will continue setting up this structure of communicating game objects by using arraysandcollections.Theseprogrammingconceptsareveryimportantforthesecondgame,Jewel Jam,whichisapatternrecognitiongame.Youwillalsoseehowtoscaleagametodifferentscreen sizesandhowtomodelthegameworldasahierarchyofobjectsthatcancontaineachother. • PartIVintroducesthepuzzlegamePenguinPairs.Thisgameshowsyouhowtodealwithdifferent gamestatessuchasmenusorlevelselectionscreens.You’lllearnhowtoreadlevelsfromfilesand howtostoretheplayer’sprogressinafile.You’llalsolearnhowtodealwithspritesheets:larger imagefilesthatstoremultiple“sub-images”foryourgame.Finally,thispartdealswithorganizing classesintodifferentlibrariesthatyoucanuseacrossdifferentgameprojects. • Finally,PartVrevolvesaroundtheplatformgameTickTick,whichreusesthegameengineyou’ve beenbuildingsofar.Inthispart,youwilldealwithloadingandplayinganimations,andyouwill addbasicphysicstothegameworld,suchasjumping,falling,andhandlingcollisionswithother gameobjects.You’llalsolearnhowtodealwithunexpectederrors(exceptions). Preface vii Eachchapter(exceptChap.1)endswithacollectionofexercises.Sometimes,thesearegeneralques- tions that help you get more familiar with the concepts introduced in that chapter. Other exercises inviteyoutoextendtheexampleprogramsfromthatchapter,usingthethingsyou’velearnedsofar. Themoreadvancedexercisesaremarkedwithanasterisk(*).Furthermore,inthelastchapterofeach part(startinginPartII),there’san exercisethatinvitesyoutoextendthemaingamefromthatpart. Theseareopenandcreativechallengesthatyoucantakeasfarasyouwant. Finally,throughoutthe book,youwillfindtextin grayboxes.These boxesusuallycontain“side notes” that go a bit deeperthan the main text. In this secondedition of the book,we’ve also added QuickReferenceboxesthateachgiveashortsummaryofaprogrammingconcept. Required Materials andTools Todevelopthegamesofthisbook,youwillneedtoinstallafewtoolsonyourcomputer: • VisualStudioCommunity2017,afreeprogrambyMicrosoftforwritingandcompilingcodeinC#. • MonoGame3.6,anopen-sourcelibrarythataddsgame-specificfunctionalitytotheC#language. Onthewebsiteofthisbook,youcanfinddetailedinstructionsonhowtoobtainandinstallthesetools. Chapter1willalsohelpyoufurtherwiththesepreparations. Note thatVisualStudio andMonoGameare updatedfrequently.By the time youread thisbook, newer versions of these tools may already be available. Of course, you are free to use these newer versionsas well. However,if youwantto besure thatyoucan runourexampleprojects,we advise youtoinstalltheversionsmentionedabove. If these versionsof VisualStudio orMonoGamebecomeso outdatedthatthe bookbecomestoo difficulttouse,wewilltrytoupdatethebook’swebsitetohelpyououtasmuchaspossible. Alongwith thisbook,we supplyvariousmaterials.Allthe exampleprogramsused inthisbookare availableas VisualStudio projectsthatyou canopen,edit, compile,andrun yourself.Furthermore, wesupplyasetofgameassets(spritesandsounds)thatareusedinourexampleprograms.Allthese additionalmaterialscanbefoundontheaccompanyingwebsiteofthisbook. Website — Along with the book itself, there is an accompanying website from which you can download all additional materials. The URL of this website is http://www. csharpprogramminggames.com/. ForTeachers: Using This Bookfora ProgrammingCourse Thisbookisverysuitableasabasisforagame-orientedprogrammingcourse.Eachpartofthisbookis concludedbyexercisesandchallenges.Solutionstotheexercisesareavailableonthebook’swebsite. Thechallengesaregenerallymorecomplexprogrammingexercises,andtheycanserve aspractical assignmentsforstudentsfollowingthecourse.Ontheaccompanyingwebsite,anumberofadditional challengesareavailablethatcanbeusedasabasisforpracticalassignmentsaswell. By following the structure of the book throughoutthe course, students will be introducedto the mainaspects of programmingin an object-orientedlanguage.Supplementarymaterialsfororganiz- viii Preface ing such a course are available on the website of this book, www.csharpprogramminggames.com. Asamplescheduleofacoursewith15sessionsand3practicalassignmentsisgivenbelow: Session C#topics Gametopics Chapters Deadlines 1 Introduction 1,2 2 Types,variables Gameloop 3,4 3 if,else,booleans Sprites,sound,playerinput 5,6 4 Classes, methods, ob- Objectinteraction 7,8 jects 5 for,while,randomness 8,9 Ass.1 6 Inheritance Drawingtext 10,11 7 Arrays,strings,collec- Screensizes,grids 12,13 tions 8 Recursion Gameworlds 14,15 9 Abstractclasses,inter- 16,17 faces 10 Gamestates,spritesheets 17,18 Ass.2 11 FileI/O,switch Tiles,levels 19,20 12 Libraries,exceptions 21,22 13 Animation,gamephysics 23,24 14 Enemies 25,26 15 Generalquestions All Ass.3 New intheSecond Edition Inthissecondeditionofthebook,we’vemadeanumberofkeychanges,basedonourexperiencewith usingthebookinauniversity-levelgameprogrammingcourse.Thetexthasbeenrewrittenentirely, andchaptershave beenrestructuredand reordered.All in all, this secondeditionshould providean evensmootherandmoregeneralintroductionto(game)programming. Themostimportantchangesinthiseditionarethefollowing: • We have updated all example programs to work with Visual Studio Community 2017 and MonoGame3.6(insteadofthenowobsoleteXNAGameStudio).Readerscanonceagainfollow thematerialbyusingthemostmodernprogrammingtools(atthetimeofwritingthisbook). • Throughoutthisbook,thetextnowinvitesyoutowriteyourowncode,insteadofexplaininghow the book’s example projects work. The example projects are still there as reference points, but you’reencouragedtogettothosereferencepointsbywritingthecodeyourself.We’veaddedcon- venientcheckpointmarkersthatindicatewhenyourcodeshouldmatchacertainexampleproject. • Wehavemadethemostimportanttermseasiertofindinthetext.Alltermsthatappearintheindex (attheendofthebook)areprintedinboldfacewhenthey’refirstexplained. • WehavemadeaclearerdistinctionbetweengeneralC#programmingconceptsandconceptsthat are specific to game development. For example, primitive types (such as int and string) and the conceptofclassesarepartoftheC#language,buttheColorclassandthegamelooparespecificto theMonoGamelibrary.Ifyouwanttocontinuewithsoftwaredevelopmentingeneral,it’sgoodto beawareofthisdistinction. • We’vemadeprogrammingguidelineseasiertorecognize.Thenew“QuickReference”boxessum- marizeaprogrammingconceptinawaythatclearlystandsoutfromtherestofthetext.Asaresult, Preface ix compared to the first edition, it is now easier to see the difference between an example and the generallessonthatyoucanlearnfromit. • Theexercisesarenowgroupedperchapter(insteadofperpart),andtheycannowbefounddirectly aftertheirchapter(insteadofinanappendix).Thisway,readerscancheckmoreeasilywhetherthey understandthematerialfromaparticularchapter.Theexercisesthemselveshavealsobeengiven anupdate:we’veaddedandchangedseveralexercisestogivereadersamoregeneraleducationin C#programming. If you’realreadyusing the first editionof the bookfor personalreference,then youcan keep using itwithouttoomanydifficulties:bothversionsofthebookstillcoverthesamematerialoverall.Inall othercases,westronglyrecommendusingthesecondedition:it’samoreconvenientintroductionto (game)programmingandamorecompletebasisforacourse.Ifyouareastudentandyourprogram- mingcoursehasbeenupdatedtothesecondeditionofthebook,thenupgradingisespeciallyuseful, alsobecausethebook’sexampleprojectsandexerciseshavechanged. We hope you’llenjoy using this bookfor gainingyour first experiencewith object-oriented(game) programming.Whenyouhavereachedtheendofthisbook,youwillhaveasolidbasisforbecoming a good programmer. What comes after that is up to you, but we hope you’ll be inspired to create wonderfulgamesandotherprogramsinthefuture. Goodluck! Rennes,France WoutervanToll Utrecht,TheNetherlands ArjanEgges Utrecht,TheNetherlands JeroenD.Fokker Acknowledgments Just as games are generally not developed by a single person but by a team, this book was a team effortas well. Firstof all, I’dlike to thankmy co-authorsJeroenand Markfor theirinspiringideas andtheinterestingdiscussionswe’vehadwhilewritingthisbook. This book is based on reading material that was handed out to the (many) students of the game programmingcoursehere atUtrechtUniversity.Their feedbackandcriticalanalysisof the material have been of great help, as well as their motivation to work with the example games. I officially apologizeforanyfrustrationthatoccurredduetoa fewridiculouslydifficultlevelsoftheTickTick game! I wouldlike tothankmycolleaguesfortheirideasandtheirinterestin thiswork.Inparticular,I wouldliketothankCathyEnnisandSybrenStu¨velforprovidingcorrectionsandforreadingthetext indetail.Theirfeedbackhasresultedinmanyimprovementsofthetextandthesampleprograms. The sprites for all the example games in this book were designed by Heiny Reimes. It was a pleasureworkingwithhimondesigningtheexamplegamesandimprovingthem. IwouldalsoliketothankRalfGerstnerfromSpringerfortakingthetimetoreadthemanuscript andhelpingtomakethisbookareality. Finally,I wouldliketothankmywife,Sterre,forhercontinuingsupport.Idedicatethisworkto her. Utrecht,TheNetherlands ArjanEgges January2013 For this second edition, I’ve been given the chance to improve the book and add my own insights and twists. I should start by thanking everyonewho made the first edition possible: you gave me a luxurious starting point with logically chosen topics and fun example games. Thanks to Arjan for entrustingmewiththisupdate,andthanksagaintoRalfSteineratSpringer,whoallowedmetowrite amuchbiggeroverhaulthanwe’dinitiallyplanned. TheimprovementsinthisneweditionarebasedonmyteachingexperienceatUtrechtUniversity. I’d like to thank Paul Bergervoetfor guiding me into the Game Programmingcourse there in 2017 and his successor Remco Veltkamp for his interest in improvingit with me. Also, thanks to all the students who’ve provided feedback on the first edition. Your comments have definitely helped me turnthisbookintoasmootherresourceforstudents. Specialshout-outtoJeroenvanKnotsenburg,aC#guruwithakeeneyeforcleanandreusablecode but(mostimportantly)agreatfriendwho’sbeennearbyeversincewetookourownfirstprogramming coursetogether. xi

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.