game development using python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... ·...

332

Upload: others

Post on 20-Jul-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development
Page 2: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

GAMEDEVELOPMENTUSINGPYTHON

Page 3: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

LICENSE,DISCLAIMEROFLIABILITY,ANDLIMITEDWARRANTY

By purchasing or using this book and disc (the “Work”), you agree that thislicense grants permission to use the contents contained herein, including thedisc,butdoesnotgiveyoutherightofownershiptoanyofthetextualcontentinthebook/discorownershiptoanyoftheinformationorproductscontainedinit.ThislicensedoesnotpermituploadingoftheWorkontotheInternetoronanetwork(ofanykind)withoutthewrittenconsentofthePublisher.Duplicationordisseminationofanytext,code,simulations,images,etc.containedhereinislimited to and subject to licensing terms for the respective products, andpermissionmustbeobtainedfromthePublisherortheownerofthecontent,etc.,in order to reproduce or network any portion of the textual material (in anymedia)thatiscontainedintheWork.

MERCURYLEARNINGAND INFORMATION (“MLI”or“thePublisher”)andanyoneinvolved in the creation, writing, or production of the companion disc,accompanyingalgorithms,code,orcomputerprograms(“thesoftware”),andanyaccompanyingWebsiteorsoftwareoftheWork,cannotanddonotwarranttheperformanceorresultsthatmightbeobtainedbyusingthecontentsoftheWork.Theauthor,developers,andthePublisherhaveused theirbestefforts to insuretheaccuracyandfunctionalityofthetextualmaterialand/orprogramscontainedinthispackage;we,however,makenowarrantyofanykind,expressorimplied,regardingtheperformanceofthesecontentsorprograms.TheWorkissold“asis”withoutwarranty (except fordefectivematerialsused inmanufacturing thebookorduetofaultyworkmanship).

The author, developers, and the publisher of any accompanying content, andanyoneinvolvedinthecomposition,production,andmanufacturingofthisworkwill not be liable for damages of any kind arising out of the use of (or theinability to use) the algorithms, source code, computer programs, or textualmaterialcontainedinthispublication.Thisincludes,butisnotlimitedto,lossofrevenueorprofit,orotherincidental,physical,orconsequentialdamagesarisingoutoftheuseofthisWork.

The sole remedy in the event of a claim of any kind is expressly limited toreplacementofthebookand/ordisc,andonlyatthediscretionofthePublisher.

Page 4: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Theuseof“impliedwarranty”andcertain“exclusions”varyfromstatetostate,andmightnotapplytothepurchaserofthisproduct.

(Companion files are also available for downloading from the publisher [email protected].)

Page 5: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

GAMEDEVELOPMENTUSINGPYTHON

JAMESR.PARKER

MERCURYLEARNINGANDINFORMATIONDulles,Virginia

Boston,MassachusettsNewDelhi

Page 6: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Copyright©2019byMERCURYLEARNINGANDINFORMATIONLLC.Allrightsreserved.

Thispublication,portionsofit,oranyaccompanyingsoftwaremaynotbereproducedinanyway,storedinaretrievalsystemofanytype,ortransmittedbyanymeans,media,electronicdisplayormechanicaldisplay,including,butnotlimitedto,photocopy,recording,Internetpostings,orscanning,withoutpriorpermissioninwritingfromthepublisher.

Publisher:DavidPallaiMERCURYLEARNINGANDINFORMATION22841QuicksilverDriveDulles,[email protected]

JamesR.Parker.GameDevelopmentUsingPython.ISBN:978-1-683921-80-6

LibraryofCongressControlNumber:2018964986

Thepublisherrecognizesandrespectsallmarksusedbycompanies,manufacturers,anddevelopersasameanstodistinguishtheirproducts.Allbrandnamesandproductnamesmentionedinthisbookaretrademarksorservicemarksoftheirrespectivecompanies.Anyomissionormisuse(ofanykind)ofservicemarksortrademarks,etc.isnotanattempttoinfringeonthepropertyofothers.

181920321Thisbookisprintedonacid-freepaperintheUnitedStatesofAmerica.

Ourtitlesareavailableforadoption,license,orbulkpurchasebyinstitutions,corporations,etc.Foradditionalinformation,pleasecontacttheCustomerServiceDept.at800-232-0223(tollfree).

Allofourtitlesareavailableindigitalformatatauthorcloudware.comandotherdigitalvendors.Companionfiles(figuresandcodelistings)forthistitlearealsoavailablebycontactinginfo@merclearning.com.ThesoleobligationofMERCURYLEARNINGANDINFORMATIONtothepurchaseristoreplacethedisc,basedondefectivematerialsorfaultyworkmanship,butnotbasedontheoperationorfunctionalityoftheproduct.

Page 7: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ForMyMother—Shewasatypesetterandlostherjobtocomputers.

Shedoesnotblameme.

Page 8: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CONTENTS

Preface

Chapter0GamesVirtualRealityGameGenresStrategySportsSimulationRolePlayingActionAdventureOtherGames

CommonAspectsofComputerGamesPlatformsDesktopComputersTabletsGameConsolesPortableConsolesCellularPhones

AspectsofInterestingGamesVenueConflictGraphicsandSoundPropsInterfacePace/ScaleFidelityAccuracy

Page 9: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ExercisesResourcesReferences

Chapter1IntroductiontoHowGamesWorkVideoGameArchitectureTheGraphicsSystemObjectLevelGeometricLevelRasterizationCommentsonOptimization

TheAudioSystemGameDesignMechanics

PlayingtheGamebytheRulesMostofaComputerGameIsHiddenTheArtificialIntelligenceGameStateGlobalStatePush/Pull(clientserver)ManagersBroadcast-listenerSharedandGlobalEntities

PongTheGameDesignDocumentC2H6OJetBoatRaceC2H6OJetBoatRaceDesignDocument

ExercisesReferences

Chapter2GraphicsandImagesPygameEssentialsSimpleStaticDrawingPixelLevelGraphicsExample:CreateaPageofNotePaperExample:CreatingaColorGradient

LinesandCurvesExample:NotePaperAgain

Page 10: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

PolygonsBlittingDrawingTextTransparentColorsImagesPixelsExample:NegativeImage

ImageTransformationsRotation

PixelsandColorTheC2H6OJetBoatRaceGameExercisesResourcesReferences

Chapter3TheGameLoopTimeandIntervalsThepygame.timeModuleAGameLoop:BouncingaSimulatedBall

EventsTheMouseTheKeyboardAnOn-ScreenButtonASimpleGameABetterGame

RandomnessinGamesRandomnessGenerally

RandomnessinGames:Dice,CardsProbabilityforBeginnersProbabilityCalculations

GeneratingRandomValuesPseudorandomNumbers

SimulatingRealityandIntelligenceExercisesResourcesReferences

Page 11: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Chapter4GameAI:CollisionsCollisionDetectionPolygonalObjectsAnExample

BroadPhaseCollisionDetection“Operational”MethodsGeometricTestsUsingEnclosingCirclesSphereVS.PlaneCollision(Circle–Line)Circle-CircleCollisionsFindingtheClosestPointonaLinetoaSpecifiedPoint

UsingBoundingBoxesObjectOrientedBoundingBoxes

SpaceSubdivisionNarrowPhaseCollisionDetectionRay/TriangleIntersection

CollisionDetectionintheBoatRaceRayCasting

ExercisesReferences

Chapter5NavigationandControlBasicAutonomousControlHowtoControlaCarCruisingBehaviorAvoidanceBehaviorWaypointRepresentationandImplementation

FiniteStateMachinesFSAinPracticeStateandthe“WhatDoWeDoNow”ProblemOtherUsefulStates

PathfindingA*SearchStochasticNavigationExercisesResourcesReferences

Page 12: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Chapter6SoundBasicAudioConceptsIntroductiontoSoundinPygameSoundOptionsSoundVolumeChannels

CreatingYourOwnSoundsRecordingUsingCellPhonesandMP3DevicesASmallStudioAudioSoftware

PositionalAudioExample:DistanceAttenuationExample:2DPositionalSound

ExercisesResourcesReferences

Chapter7C2H6OJetBoatRaceImplementingtheGame:PrototypesPrototype0Prototype1ScreensButtonsStartScreenOptionsScreenPlayScreenEndScreen

Prototype2ThePlayScreenUserControlTheBoatClassArtificialIntelligenceCollisionsNavigationWaypointsAvoidingaBoatCollidingwiththeShore

Sound

Page 13: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

EngineSoundsCollisionsandExplosionsStartingGunFinish

TestingSummaryExercisesResourcesSoundEffectsSoundEditingGraphicsEditing

References

Chapter8AnimationCreatingElementaryAnimationsAnimationMathMotionEquations

ReactiveAnimationsUsingRealImages

AmbientAnimationsCharacterAnimationCutScenesAnimationsintheBoatRaceGameWakes

SummaryExercisesResourcesReferences

Chapter9C2H6O–FinalStepsAnimationsWakesExplosionsDeterminingaBoatCollision

SoundsEngineSoundsStartingGun

Page 14: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FinishBingAudience

GameplayCompletingtheRaceStartTimer

IntermediateGoalsFinish

Mini-MapGameData

TuningExercisesResourcesReferences

Chapter10NetworkingTheGame:PythonPongThePaddleClassTheBallClassCommunicationbetweenProcessesExample:MovingaBallontheScreen

NetworkPongTheClientTheServerBlockingandNon-BlockingMessagesThePongClientThePongServerPlayingtheGame

ResourcesReferences

AppendixA:A*inPython

AppendixB:C2H6OJetBoatRaceGameDesignDocument

AppendixC:TheNPC(Boat)ClassfortheExampleGame

Page 15: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Index

Page 16: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ACKNOWLEDGMENTS

ThankstothemakersofAudacityforallowingmetoincludetheirsoundeditingsoftwarewiththebook.

Thanks also to themakers ofVideoMach for allowingme to include theirvideoeditingsoftwareandprovidingakeyespeciallyforus.

SpecialthankstoNigelGebertforcomposingandplayingashortjazzpianopieceformetouseasanaudioexample.Heevennamedit“KeysforJim.”Hownice.

Page 17: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

PREFACE

Thisbook isaboutcomputergames. It’sabouthow todevelop themusing thePythonlanguage,butthebookalsoincludessomedesigninstruction,ideasabouthandlingassets,andahostofthingsthatshouldbeusefulforagamedeveloper.

Python is a programmer’s language, in that it provides features thatprogrammers usually want and often recode again and again in their variousprograms.Lists,dictionaries,sets,arbitraryprecisionintegers,dynamictyping–it’sanencyclopediaof the toolsaprogrammerusesall the time,orwould if itwere convenient. Well now it is. PyGame, the module used to help aprogrammer create games, adds to that a surface on which to draw, manygraphics primitives, sound, animation, and interaction. It’s awonderful paletteonwhichgamedeveloperscandiptheirbrushes.

IfyoulookupmynameontheInternetyouwillseethatIamaprofessorofArt.That’strue,butIfeellikeabitofafraud,andthereasonisthatIhavenotrainingasanartist. I studiedmathematicsandcomputer scienceatuniversity.SohowdidIendupinart?

Iwas known forwork in image processing and vision in the 1990s as anacademic.ForsomereasontheGameDeveloper’sConferenceinterestedme.In1998,Iregisteredandattended,andmylifewaschanged.Theenergytherewasincredible.People everywherewerecompletelyenthralledby theirwork.Theywerehaving fun.Theyweredoing thingsandspeakingabout things that Ihadnot heard about in my academic venues, and those things were fascinating.Moreover,theirworkhadanimmediateimpactonpeople.

True, the companies were in competition for a share of the commercialgamesmarket, but the people at the conferencewere excited aboutwhat theyknew and about sharing it. Sharing means, in this context, bringing backsomething as well as giving something to the others. Moreover, the groupcontained computer programmers, musicians and audio specialists, artists,designers,andbusinessfolks.Atruemeetingofmultidisciplinaryminds.

This book arose from my experience at GDC and my love of computer

Page 18: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

programming.Ihavewrittenotherbooksongamedevelopment,butforacasualprogrammerorhomedeveloper, I think thatPython isagreatway toproceed.Pythoniseasytolearn,andPyGamehaseverythinga2Ddeveloperneeds.

IdopresumesomeproficiencyinPython.That’snecessarytokeepthebookunder1000pages;toprogramgames,onefirstneedstobeaprogrammer.Whatthebookwillteachisstillsignificant.Computersciencedegreesareuseful,butfewdegreeprogramsofferanytreatmentofassets:art,sound,graphicsobjects.Handlingthoseisessentialtoanygame,andassetsareakeycomponentofmanypracticalcomputerprograms.

Theprojectinthisbookisbynecessityincomplete.Itisaboatrace,2D,andseen from above; but is has sound, animation, interaction,AI, and everythingthat a simple game should have. It could be more fun. It could have morefeatures. I leave these things to you.As an instructional device I think it haseverythingthatyouneed.Asagameitstillneedsyourtouch.

There is a lot of code in the book. The code is also included in thecompanion files, along with the color figures and some very useful tools forasset creation. The programs are included so that you can play with them,modifythem,andexperiment.Ifyoudonot,thenyouaremissinganelementoftheinstructionthatthisbookoffers.

Playinggames is fun.Makinggames is fun too,butcanalsobeprofitable,educational,anduseful inagreatmanyways.Theinformationyougleanfromstudyinggamedevelopmentappliesalsotootherdigitalmedia.That’sabonus.As amarketer,webdeveloper, artist, or appdeveloper,what you can learnbystudyinggamedevelopmentisenormous.

And, of course, it’s fun. If you are not having fun then you are doing itwrong.

JimParkerDecember2018

Page 19: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER0

GAMESFor all of recordedhistory, humanshaveplayedgames.The earliest board

game ispossibly theRoyalGameofUr,namedafteroneof theoldesthumancities,havingbeenestablishedatabout3800BC.This iswhat iscalleda two-playerchasegame,similarinbasicconcepttoParcheesiandlikelyapredecessortoBackgammon.

Why are people so interested in games? There are likelymany reasons: aneed to keep our minds occupied during periods of inactivity, an interest insocial contact, and a desire for achievement are three. For whatever reasons,gameshavealwaysbeenapartofhumansociety.

Butwhatisagame?

Page 20: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE0.1(LEFT)TheRoyalGameofUr.(Right)Knucklebonedice.

BYBABELSTONE(Ownwork),CC0,

https://commons.wikimedia.org/w/index.php?curid=10861909,https://commons.wikimedia.org/wiki/File:British_Museum_Royal_Game_of_Ur.jpg,https://www.shapeways.com/product/LE3XNVQQM/knucklebone-dice-set.

Creating a perfect definition of theword game is not a profitable activityunlessit leadstosomethingpractical.Hereagameshouldbedefinedinawaythat leads to a practical design and implementation process, and not morephilosophical concerns. Some things that some people may consider to be agamemaynotbe included in thedefinition,but the idea isnot toexcludeanyparticularthing.Theideaistoincludeasmanythingsaspossiblethatwethinkofasgames,andtoprovidecluesforhowonemightbegintomakeone.

Agame involvesplay, another term that is hard todefine.Let’s say that agame is an activity that people engage in voluntarily. A game is a structuredactivity, in thatagamehas rulesandat leastonegoal.Agameshould involvevariation or chance. Many simple games, like snakes and ladders, are purelygames of chance; such games are often played by children, possibly as anintroduction to how to play games.Most games have some chance and someskill,meaningplayersdevelop,overaperiodoftime,astrategyforplayingthegame.Gameslikechesshaveverylittlechance.Chessuseschancetoselecttheplayerwhowillmovefirst,butthatisall.

A game is entertaining. It can be other things also, but it must at leastprovide some degree of engagement for the player. As in other forms ofentertainment,thefeelingsthatagameimpartsneednotalwaysbehappyones,butthegamemustencouragetheplayertocontinueplayinginsomeinterestingway.

Bythisdefinitioncatchisnotagame,astherearenorules.Aballissimplythrownaround.Yetitisanactivity,anditisentertaining.

Page 21: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE0.2Aplaybow.

HTTP://WWW.PATRICIAMCCONNELL.COM/THEOTHERENDOFTHELEASH/A-NEW-LOOK-AT-PLAY-BOWS.

Gamesalluseamutualacceptanceofthefactthatwhatisoccurringisplay.Theimplicationofthisisthatthereshouldbenoreal-worldramifications.Whilethegameisbeingplayed,theplayersareoperatingunderthegamerulesandnottherulesoftheworldorsociety.Somepeoplerefertothisasbeinginthemagiccircle.Thisexplainshowakingandapeasantoranemployerandemployeecanplaychesstogether.

Gamesare alsoused to teach.Thishappens in theanimalkingdom,wheregames played by cats, for example, teach hunting skills. This appears tocontradict the“noconsequence”rule,but it isalways true thatplayingagamefrequentlymakesonebetteratplayingthegame.Dogsalsoplay,andthatbringsupthemagiccircleagain.Whenadogwishestoplaywithanother, theybeginwithaplaybowwherethechestdropstotheground,theforelegsareextended,andtheeyesarelookingatthepotentialpartner.

If the invitation isaccepted, twodogsofdifferingstatuscanplay,and thatmeanstheycandothingsnotnormallyallowed:staring,growling,evenbiting.Thegamecanendquickly,though,ifoneofthedogsgoestoofar,perhapsbitingtoohardortakingthewrongtoy.Thenthemagiccircledisappears,andreallifehasresumed.

There are a few general game classes. Kinetic games are usually playedoutdoors with little in the way of equipment and, again, are often played by

Page 22: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

children.Tag andhide and seek are examples.However, charades couldbe inthiscategorytoo.Suchgamesinvolvethemotionoftheplayers.

Boardgames use a set of objects or pieces that are placed on a relativelysmallplayingsurface,aboard.Playersusually take turnsmovingthepieces tolocationsontheboardfollowingasetofrules.

Card games use a collection of paper orwooden chips that aremarked insomeway.Thechips(cards)areusuallyhandedoutrandomlyattheoutsetofthegame,and through following the rules theyarecollected intosetswheresomesetsaremorevaluablethanothers.Dicegamesandgameslikedominoscanbeplacedinthisclass.

FIGURE0.3Examplesofmathematicalgames.

Word games include guessing games, such as Yes and No (also called 20questions);ISpy;How,When,andWhere(fromAChristmasCarol);andahostofothers.Thesegamesusenopropsandcanbeplayedanywhere.

Mathematicalgamescanusepropertiesofshapes,numbers,orrelationshipsto create puzzle-like games that can be very complex indeed. They are oftenplayedusingapencilandpaper.NimandSproutsaretwosuchgames.

Therearesomeotherclassesofgames,butonethathasdevelopedinthepastfew decades is the computer game. These are not merely computerimplementations of the other kinds of games, but they are games that use thespecificcharacteristicsofacomputertoengageinplay.Thosepropertiesincludetheabilitytodomanycalculationseachsecond,multimediacapabilities(images

Page 23: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

andsound),andmanydifferentwaysofacceptinguseinput.Thismeansthatacomputer can display images and sounds under the control of a user (player).Objectsthatdonotreallyexistexceptasimagesonascreencanbemovedaboutandcaninteractwitheachotherandaplayer.Thisopensawholenewrangeofpossibilitiesforplay.

It has been estimated that 69% of the human beings on this planet haveplayedavideogame.Thisseemsareasonablenumbergiventhepopularityandubiquity of games as observed in shopping malls, in movies, and in mediagenerally. It amounts to about five billion people. What these players knowabout games varies quite a lot, but common knowledge concerns rules ofspecificgames, interface issues suchaswhatkeys topressorbuttons topush,and some tactical information about game play, like where to hide, when tojump, and so on. Very few of these people know how the games work at animplementationlevelthough.Theinternalactionsofthegame,fromkeypresstoavatarmotion,areamysterytomostpeople.

VIRTUALREALITY

Thetermvirtualmeans“almost”or“nearly.”Virtualrealitypresentsaformofrealitythatisnotquiterealbutseemslikeit.Moderncomputergamesoftenpresent a three-dimensional view of the game area and permit the player tonavigatethroughthisspace,encounteringfriendsandobstaclesastheygo.Thispresentation is similar to the virtual reality of books and films such as TheLawnmowerManandreachedthepeakofitsformintheHolosuiteofStarTrek.InStarTrekthesuiteisusedforentertainment.Complexgamesareplayedandcomplexcharactersarecreatedwithwhichtointeractinanaturalway.Computergamesarenotyetatthatstage,buttheyseemtobeapproachingit.

Bothcomputergamesandvirtualrealityareinsomesensesimulations.Theyarecomputerprogramsthatpresentarealisticviewofanonexistentworld,butaworldthathasthesameorsimilarlawsastherealone.Thismayincludegravity,time, speed, physical contact, sounds, and even human reactions.All of theseaspects of the virtual worldmust be simulated by the computer program thatimplements the game.When a character lets go of its grip on an object, theobjectfallstothegroundbecausethesoftwaredescribesthatprocess.Whentheobjectstrikestheground,thecomputerprogramplaysasoundeffect,becauseasoundwould be produced by the impact.Nothing that happens in a computergamehappensunlessacomputerprogramimplementedit.

Whenwe play cards or chess, there is really no discussion about how thegameisimplemented.Twopeoplesetuptheboardordealthecards,andaway

Page 24: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

you go.A computer game, on the other hand, has a very complex underlyingimplementationwhichisreallythesubjectoftheentirediscussionhere.Howarecomputergamesmade?Thenatureofvirtualrealitygivessomeideaofwhatisneeded.Avideogameneedswhatvirtualrealityneeds:

– Avideo(graphical)display– Anaudiodisplay(speakers,soundcard)– Awayforaplayertocommunicatetheirmovestothecomputer– Awayforthecomputertorememberpositionsandmakemoves

Ifyouexaminewhatpeopledoknowaboutgames, some internal structurecan be inferred. That players know rules of games implies that games have aconsistent set of rules that will be implemented by a computer programsomehow. The players’ knowledge of the user interface implies a level ofconsistency there too. We observe, for example, that the arrow keys, orsometimes the keys “W,” “A,” “S,” and “D,” are used to move the player’savatar,butnotthekeys“R,”“G,”“N,”and“M”;thereareconventionsforuserinterfaces.Thevideogamescreensdisplayimagesthatmove,andgameactionsresult in sounds that the player canhear anduse as cues.Thus, a videogamemust be able to display images and sounds and do so in response to usercommandsorinternaleventsinthegame.

On the other hand,whatwe need to know to design and build an originalgame is significantlymore than that.There’s only somuch that you can learnfromexaminingagamefromtheoutside.Gamesarecomplexsystemsinvolvingcomputerdevicesandsoftware,art(textures,3Dmodels,sprites),music,soundeffects,videoandanimation,story,andadesignedstructureforplay.Thereareagreat many existing games, and techniques and tools that will help a gamedeveloperintheirtaskhaveevolvedoverthelastfewdecades.Ifwe’regoingtobuildagame,weshouldbecomefamiliarwithatleastsomeofthosethings.

Notallcomputergamesarehigh-resolution,immersive(i.e.,virtualreality),real-time games. In fact, each type or genre of game has a preferred style ofrepresentation.

GAMEGENRES

Videogames canbe classified according tohow thegame is played ratherthanwhat the game is about, just aswe did for games in general.A genre isdefined by the kind of challenge the gameoffers to the player rather than thestory it presents, if any. The games in a genre need not occur in the same

Page 25: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

locations, in the same time periods, or even have the same graphical style,althoughpresentationstyleismoresimilarbetweengameswithinagenrethaningeneral. There are quite a few genres in the literature, but these are themostcommonones.

StrategyThese games give the player a singular position in the game where they

knownearlyeverythingaboutthecurrentstate.Byusingplansinvolvingplacingandmovingtheirobjects(forces), theplayeropposesotherplayer-controlledorgame-controlledobjects.Objectshavespecificpowerswithinthegame,andbycleveroppositiontotheobjectsseentheplayerachievesagoal,whichisusuallydomination of the other players. There is often an economywithinwhich theplayercanacquiremoreobjects.

Sub-genresincludetowerdefensegames, inwhichtheplayersetsoutstaticdefensesalongapathtraveledbytheiropponentandreal-timestrategygamesinwhichplayers act in real time against a dynamicgame state (Warcraft,AgeofEmpires).

Thesegamesoftenuseamedium-levelresolutionandhaveapointofviewfromabovetheplayingarea.

SportsSportsgamesare theeasiest tounderstand,because they reflectanactivity

thatmostpeoplealreadyknowabout,thatbeingsports.Anysportcanbemadeintoagame.Golfinggamesusetheratherclumsymouse-keyboardinterfacetopermit a player to control a golfer on a course,which is something of a soloactivity. Team sports like football and hockey present more variation to theplayer,andoftenpermit the switchingofpointofviewbetween the individualteammembers.Thegamestrytosimulatethestyleofplayofactualathletessothataplayercancompeteagainsttheirfavoriteindividuals.

Racinggamesfall intothiscategory.Actualracetracksareusedinmanyofthese,asareactualdriversandcars.Anumberof special interfaceshavebeendevisedtopermitplayerstouseasteeringwheelandpedals,modelingthewaycarsarereallydriven.

Sports games are the most difficult to create. They tend to use high-resolutiongraphicstomimicwhatwouldbeseenontelevision,whichisthewaymanypeopleviewsports.Sport fansknowquitea lot about their sport, so thegamemustbequiteaccurate.Thefans inparticularknowhowtherealplayers

Page 26: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

actuallyplay,andtheywillbecriticalofmistakesinthisarea.Eachyearplayersmove between teams and new ones enter the sport, so the game must beregularly updated. And if that is not enough, the physics involved in sportsgamesisverysophisticated.Considerthecomplexityofacollisionbetweentwohockey players skating at high speed (rag doll physics) or how a race carbehaveswhenitcrestsahill,leavestheground,andthenlandsinawetspotonthetrack.

SimulationSimulation games have become more popular in the first part of the

twentyfirst century. While all games contain a simulation at their heart, asimulationgameexposes that simulationandpermits aplayer tomanipulate itdirectly.Themost obvious type of game in this genre is a flight simulator, inwhichtheplayerfliesanaircraft.Asinsportsgames,flightsimulatorsusereal-worldfeatures:realairports,aircraft,andterrain.Aircombatcansometimesbean aspect, as well as the distinct nature of each aircraft. There are also shipsimulatorsandtrainsimulators.

However,therearemorecomplexsimulationgameswhereonesimulatesanecosystemoranentirehumanorother lifetime.Games likeSimCity allow theplayer to build andmanage an entire city. Tycoon games (Zoo Tycoon,RollerCoasterTycoon)aresimulationsofbusinessesandeconomies.

RolePlayingThese games are referred towith an abbreviation,RPG.They are in some

sensederivedfromtheoriginalnon-computergameDungeonsandDragonsandcast the player in a role where they can pretend to be one of a number ofcharacters, each having specialized abilities. There is a storyline and a set ofgoals,butthemannerwithwhichtheplayerachievesthegoalsisuptothem.

Action RPGs focus on combat and can be solo games (Dragon Slayer),multiplayer,ormassivelymultiplayer(MMORPG),usingtheInternet togatherhundredsormoreplayers into thesamegameat thesame time(FinalFantasyXI,ElderScrollsOnline).

ActionThis genre actually began the video game phenomenon.Action games are

sometimes called twitch games because they require the player to respondquickly to the visual and auditory stimuli provided by the game.The player’s

Page 27: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

viewpointiscentraltothesegames,whichofteninvolvefightingofsomekind.Platformershaveatwo-dimensionalpresentationasseenfromoneside.The

player controls a character who runs and jumps while collecting objects,fighting, and avoiding traps and enemies.DonkeyKong is the best known ofthese games. They require little in the way of complex graphics and can beplayed on very small, low-powered computers. Shooters are very popularbecause the game play is so obvious: enemies approach and you shoot them.They, of course, shoot back. Game developers like these because they are sosimpleinconceptandeasytobuild,althoughmoremodernonesdohavemuchbetter graphics and even complex narratives. First-person shooters (Doom)followtheplayerprecisely,whereasthird-personshootersrenderthescenefromadistance.

Fightinggamesfocusonindividualcombat.Variouskeypresscombinationscorrespond to actions that the avatar makes in a combat situation: punches,kicks, jumps, and so on. Memorizing the key sequences and speedy pressesunderrealtimeactionsmakethisstyledifficultforsome.

AdventureAdventuregamesusegameplaystylethatisrelativelysedate.Theplayerhas

some rather general goals and achieves them by solving puzzles and byinteractingwithgameelements likeother characters, terrain, orobjects.Thesegamesusenon-confrontationmorethanviolence.Someoftheearliestcomputergames were textbased adventures (Advent,Zork) that could be played on theearlydumb terminals and telex interfaces.Myst isprobably thebestknownofthesegamesinthemodernera.

OtherGenresThere are many other genres in common use: kinetic or rhythm games

(Dance Dance Revolution), horror and survival horror (Silent Hill), casual,puzzlegames,triviagames,andothers.Eachhasatypicalimplementationstylein terms of the interface, and a preferred graphical presentation that is anadvantageforthatgenre.

COMMONASPECTSOFCOMPUTERGAMES

Computer games have common requirements which have implications forthedesignofgames.Theneedforparticipationandrulesimpliestheexistenceof

Page 28: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

objects.Aplayermanipulatessomekindofobjectaccordingtotherules,whichdefinesplay.Theobjectcouldsimplybetheplayer’shand,oraball,orastone.There can be multiple objects and multiple object types. An object ismanipulated by the player and can, in turn, affect the player, which providesinteraction.

The way a player manipulates the objects is called mechanics, or gamemechanics. The basicmechanics for basketball ismake the ball go through ahoopfromabove,forexample.

Agamedesignerreallydesignsmechanics.

Theexistenceofobjectsimpliestheexistenceofsomekindofplayingarea,volume, or space within which the game activity takes place. A game objectneedsspacewithinwhichtoact.Agamespacecouldbeaboard,asincheckers,or a table for card games, or a simulated 3Dworld for computer games likePortal,SilentHill,orPlanetside.

Thegamehasapurpose,goal,orendpoint.Theplayermustmanipulatetheobjectsaccordingtotherulessoastoaccomplishthegoalorreachtheendpoint.Thegoalcouldbetemporary,tobereplacedbyanothergoalwhentheoldoneisachieved. There could bemultiple goals to be achieved, either collectively oroptionally.Or,insomerarebutpopularinstances,thegoalscouldbeselectedbythe player. That is the case inThe Sims, where there is no designer-specifiedgoal, but the players can manipulate the virtual worlds to achieve goals theyhavedevisedthemselves.Thistheoneofthemostpopulargamesevermade,butthe concept of the sandbox, a place where players can manipulate the worldfreely, has relatively few examples.Most gameshave designer-specified goalsandawayofkeepingscore.

Agameshouldhave thesecharacteristics.Whatdoes this sayabouthowagame,especiallyacomputergame,shouldbebuilt?Whatare the things thatacomputer game needs to implement, at a generic level? First, theremust be away of interacting with the game. How does a player interact? Usually bymanipulating an object, or multiple objects, within the gameplay space.Interactionwhenusingapersonalcomputerusuallymeansusingakeyboardormouse,although special-purpose game devices do exist. So, a computer gameneeds a straightforward way to accept input from those devices and use it toupdatethegame.

Next,werequireanobjectinanabstractsense.Anobjectismanipulatedbytheuser,soitslocationandstatemustbemodifiable.Theobjectmightbeabletointeractwithotherobjects.Forexample,itmaycollidewithawall.Itshouldbe

Page 29: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

able tocreatenewobjects (bullets,missiles,money, food)anddestroyordropobjects(moneyagain,traps,tools).

In the virtual space defined by the game, an object has a location and anorientation.Itwillnormallyhaveatleastonegraphicalrepresentationwithinthatspace so that the player can see its location and orientation andmodify it aswanted.

Whilemostgameshavethesecharacteristics,computergamescertainlydo.They define the structure of a video game as a piece of software, and thatstructureisreferredtoasthearchitecture.Inordertovisualizehowacomputergameworks,we’ll lookataspecificgameand thengeneralizewhat is learnedtheretoallvideogamesinthenextchapter.

PLATFORMS

Computer games are played using a computer—everyone knows that. Butthere aremany kinds of computers, and each one presents special advantagesand disadvantages for hosting a game.The features of importance include thespeedoftheprocessor;thenatureofthegraphicsarea,includingitssize,color,space, and speedof access; thenature of theuser interface; speed and cost ofInternet access; and the amount of memory available. Games are usuallydeveloped for a particular platform, but they may expand their range ofplatformswithtime.

DesktopComputersPCsandMacsaregooddevicesonwhich toplaygames.PCs inparticular

have a large variety of devices that can be used to supplement the gaminginterfaces.Desktopstypicallyhavealargeamountofmemory,runat3GHzandmore, and multiple processors and most importantly possess a high-poweredgraphicscard.Moderngraphicscardsaremuchfasterthantheprocessorsonthecomputer and are programmed to respond to a game’s specific needs.ProgrammingaPCcanbedoneinanyofdozensoflanguages.

PCs have a range of video and audio output devices. Color quality ofmonitors is nowexcellent, althougheachmonitor is just a little different fromthe others. Multiple high-quality speakers can be fed by 5.1 and 7.1 channelsound cards to create a compelling 3D sounddisplay.By theway, the “.1” in“5.1”referstothesubwoofer,whichisnotreallyadistinctchannel.Thequalityofthedisplaysplacesaresponsibilityonthedeveloperstoprovidegoodsoundandimages.Defectswillbeobvious.

Page 30: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Ofcourse,computersareallsoldwithhigh-speedEthernetcards,soInternetaccessisnotaproblem.Also,gamesarenowoftendownloadedtoaPCfromtheInternet using services such as Steam. This means that software updates togames, something that was once impossible, are now done while the playersleeps.

There are some pitfallswhen using desktop computers as gaming devices.After someone has owned a computer for a fewweeks, it is unlike any othercomputerintheworld,becauseusersalwayscustomizethem.Newprogramsareinstalled,specialdevicesareconnectedtothebus,securitymeasuresaretaken,and a host of smallmodifications aremade.The fact that no twoPCs are thesame does make it difficult for developers to guarantee that their games willwork.Thentherearesoftwareupgradesfromthesystemvendorsandthesimplevariation in operating system levels and versions. What can the developerdependon?Notmuch.So,theymustprovideitforthemselves.

TabletsTabletsarenotquitecomputers.Theyhaveasmaller,slowerprocessor,less

memory, and no extendability. The screens are small and have small, slowgraphicscards.Their Internet is restricted towireless.There isnokeyboardormouse,usuallyjustatouchscreen.

Thismeansthatthetouchscreenhastobeusedformostuserinput.Atouchscreenmapsontoamouseprettyeasilyintermsoftheoperationsitcanperform,butavatarsareusuallycontrolledusing the“w,”“a,”“s,”and“d”keys,whicharenotavailable.

Tabletshavesoundcapabilitybutarelimitedtostereo.Headphoneswouldbethe rule. Some tablet games have been downsized from a desktop, but theadvancedonessimplywillnotwork.

GameConsolesA game console is a specialized computer designed to run games. The

system isoptimized forgameperformance in every regard.Becausea consolehas no other job, it has limited customizability and a much smaller range ofthings it can do, but it does those things very fast. It generally has multipleprocessors,anadvancedgraphicscard,andsomediskspacesoastostoreafewgamesandhighscores.GamescanbedistributedondisksandontheInternet.

A computer game that executes on a console is sometimes called a videogame,possiblybecausetheyusedtousethetelevisionasamonitor.

Page 31: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Programmingagameforaconsoleisactuallyaquitecomplextaskinvolvingalotofspecificknowledgeofthearchitectureofthemachineandsomeparallelprogramming.Theresultscanbespectacular.

Popular consoles are the PlayStation (now at version 4), Xbox (multipleversions),andNintendoSwitch.

PortableConsolesPortableconsolesarehandheldcomputers thatonlyplayvideogames.The

kingoftheportablesistheGameBoybyNintendo.Thatversionhassoldover118 million units, although it is no longer made. It has an 8-bit computer,meaning the graphics and sound were very primitive indeed. However, youcouldplayitonaschoolbusorinasubway.

TheGameBoyhasbeenreplacedbytheDSand3DSwith32-bitprocessors,whichhavesold152millionunits.ThebestsellinggamewasSuperMarioBros.at31millioncopies.Financiallythiswouldbethedevicetocreategamesfor,butNintendo keeps a very tight reign onwho can create for these devices. Theykeepcontrolpartlybecausetheyownthepatentonthegamedistributiondevice,asmallchipthatfitsintothebodyoftheconsole.Nobodyelsecanmakethose.

OtherportablesincludethePlayStationVitaandtheSonyPSPSlim.

FIGURE0.4TheoriginalGameBoy.

Page 32: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CellularPhonesCell phones are ubiquitous and havemultiple purposes, so itmakes sense

thatgameswouldbecreated for them.Theproblemis that theyare really justvery small tablets.Thismeans that the screen size (what developers call “realestate”)isalimitingfactor.PlayingagamelikeCivilizationorWorldofWarcraftcouldbetricky.Itwouldcertainlybeconstraining.Yettheadvantagesareclear.AphonehasInternetaccess,ithasmanybuilt-indeviceslikeGPS,tiltsensors,andaccelerometers,andithassound.

Cellular phones are frequently based on the Android operating system,althoughiPhonesarenot.Thismeansthatadeveloperhassomeclearchoicestomake when building a game, and the Android operating system is upwardcompatibleforatleastafewversions.

Buildingagameforaphonemusttakeintoaccountthespecificconstraints,althoughthereareafewgamesthatcanbeplayedonnearlyanydevice;AngryBirdscomestomind.

ASPECTSOFINTERESTINGGAMES

Games that have had an enduring quality tend to have things in common.Veryfewgameshaveallofthese,andsomehaveonlyone,butthesearethingsthatshouldbethoughtofwhendesigningandbuildinganewgame.Genreisanimportantconsiderationwhenincorporatingfeatures,as is thestyleandqualitylevelofthegraphics,thenatureofthesound,andsoon.

VenueSome games take place in interesting locations, often real places that you

mayhavevisited:SanFrancisco,NewYork,Paris.People like toseenewandinterestingplaces, andpeoplewhohavebeen to those places like to see spotsthey can recognizewithin the game.Of course,many people have seen theseplaces inmovies and on television, so that gives the sites an extra degree offamiliarity.Thisisimportant,andnotjustbecausethelocationsareoftendistantandexotic tomanyofus. Ifwecouldcreateagame thatwoulddrive throughyour own hometown, for instance, thatmight interest you. Themakers of theMonopolygamehavedonethisbycustomizingtheirgameforvariouscities,anditseemstowork.

Naturally,simplyplacingtheactioninanexcitingplaceisnotgoodenough—youmustportraythatplaceusinggraphicsandsoundwellenoughsothattheplayercanidentifyit.Thisisanimplementationissuemorethanadesignissue,

Page 33: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

butisimportant,anditwillbediscussedinmoredetail.If thegame isadrivinggame, thenplacing itona racetrack isanobvious

thingtodoandcanactuallytakeawayfromthefununlessthattrackisfamiliartotheplayer.ThetrackatIndianapolisiswellknown,forexample,andaracingfanwouldidentifyitinamoment.Inabasketballorhockeygame,thedesignersandimplementersgotosomesignificanteffortstotrytomaketheplayerslookandactliketherealplayersandtohavethevenuesbeaccuraterepresentationsoftherealthing.Fansknowtheirsportandcanbeverycriticalwhenthegamedoesnotlookright.

Itisalittleunusualtopermittheplayertogettoofarawayfromthepaththatthe game designers have set out. In some games you can go anywhere in thesimulatedworld andmanipulate objects—this is an essential aspect of play inTheSims,forinstance.Suchgamesaresometimescalledsandboxes,becausetheplayer, rather than the designer, defines the way the game is played. It is afeatureofmostgamesthattheplayerappearstohavemuchmorefreedomthantheyreallydo;theyappeartohavechoices,butforsimplicity’ssakethechoicesall seemto lead to thesamefewconsequences.Thisappearanceof freedomisvery important to computer games in general, not just racing games. It isnecessarybecausewejustcan’tsimulatetheentireuniverse.

Notyet,anyway.

ConflictAgamemost often haswinners and losers; games keep score.Clearly the

goal is towin,andanygamethatdoesnotallowtheplayer towinwillnotbepopular.Thisistheminimumconflictrequirementofanygame,evenonesthatinvolve collaboration. Perhaps the term challenge should be used in place ofconflict.Inanycase,agamepresentstheplayerwithobstaclestobeovercome,andsuccessisamatteroflearninghowtodealwiththeseobstacles.

Thereareavarietyofconflictsourcesingames,andvarietycanbeessentialto game play. Indeed, any narrative depends on a degree of conflict to beinteresting. While narrative in some games is usually there only to providebackground,oranexcusefortheaction,othertimestheconflictisfundamentalto the story (WorldWar II, for instance) as it defines both the goals and themeansofachievingthem.

So,what kind of conflict arewe talking about?First-person shooters haveoneoftheobviousformsofconflict,wherethegoalsareachievedbyshootingyour opponents. Sports games have obvious conflicts, as do racing games: todefeatanopponentusingtherulesofthesport.InCrazyTaxiwehavecustomers

Page 34: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

refusingtopayifwegettherelate,andtheyberateusforgoingtoofastorslow.IntheTycoonseriesofgames(e.g.,ZooTycoon),conflict iscreatedbyforcingthe player to balance costs and income through building attractions. Not allgamesusecompetitionasconflict,butmostdo.LittleBigPlanetisacooperativegameinwhichtheplayerscancreatenewcontent,buttherearestillgoalstobeachieved that present challenges; it lacks the incentive to defeat an opponent,andsointhatwayitisnotcompetitive.

GraphicsandSoundAll reallygoodgamesexcel in someaspectsofgraphicsor soundorboth.

Graphicsdonothave tobehigh resolutionand threedimensional,but theydohavetobeappropriateforthespecificgame.GameslikeHaloofferhigh-qualitygraphics andgoodanimation,butwe shouldnotmistake“high resolution” for“interesting.”TheSimpsonsHit&Runofferstheplayerstheabilitytoexploreatown that they know fairly well—Springfield, home of the Simpsons. Do notunderestimate thevalueofsandboxmode; if theworld is interesting, then justlookingaroundcanbeentertaining.

Soundmaybemoreimportantthangraphics,especiallyforimpartingmood.This includes excitement, and a fast-moving rock and roll audio backgroundaddsenergytoagameinthesamewaytheetherealthemesfromHalfLifemakeitsworldseemdangerousandspooky. It isnotusuallya trade-off,andwecanhavegoodgraphicsandaudioifwejusthavethewherewithaltocreatethem.

Naturallysomegamesrequirebettergraphics,becausetheyneedtobemorefaithfulsimulations,whereasotherscanbeverycartoony,likeDoubleDash,andstill offer a huge degree of entertainment value. As a result of theseconsiderations,thebestgameshaveincommonanappropriatelevelofdetailingraphics, with good audio and appropriate and entertaining objects andbackdropsrenderedpredictably.

PropsPropsareitemsthatcanbemanipulatedinthegame.Allgameshaveprops

ofsomekind.Sportsgamesingeneralhavefewerpropsthanmostgames,andsimulationgamesoftenhavemany.Aballisaprop;soisabulletoramissile,and theycanmoveon theirown.Powerupsandpenaltyobjects areprops too.Propshaveanimmensepotentialformakingagamemoreinteresting.Withoutthepossibilityofpickingupweaponsandspeedups, theDoubleDash game isjustacartoonracegame.Beingabletoslowdownanopponentfromadistance,

Page 35: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

andhavinghimbeathreatfrombehind,addsanelementofexcitement.Propsalsoallowamoreinterestingnarrative,sinceentiremissionsandlevels

can depend on moving props from one place to another. They can impartimportantpropertiesthatremainfromleveltolevel,likemagicicons,fuel,andskill points. This leads to the conclusion that complexitymakes a gamemoreinteresting.Thereissometruthtothis,solongasthegameremainsplayable,butit is more likely that a degree of unpredictability makes the game moreinteresting.Thegamemustbeconsistent,butitisbestifitdoesnotrepeatitselfexactly each time it is played. Props can be used both tomake a gamemorecomplexand tomake it lesspredictable.The locationof thepropscanchangealongwitharepeatablecharacterthatotherwisecouldbecomedull.Apatternofplaycanbeusefulsometimes,butit’srarelyentertaining.

InterfaceGames are fundamentally an interactivemedium, and interfaces are at the

heartofinteraction.Therehasbeenasignificantefforttostandardizesomegameinterfaces.Forexample,onconsoleswefindverysimilarcontrolsdoingsimilarjobs, especially on games that run on multiple consoles. Also, games of aspecific genre tend to use consistent control sequences, like arrow keys formotion.Gamesvaryalittleonuseofkeys/buttonsandmousegestures,andthereisstilltoomuchvariationgenerallyforidenticalmechanics.

Someracinggamesusethemousetocontrolspeedanddirection.Themousehasmoredegreesoffreedomindirectionalcontrol,andthefasterthecargoes,the harder it is to control itwith amouse.One tends to oversteer, andmousepositionisrelative,notabsolute.Still,giventhepopularityofgamesfortabletsand smartphones, the use of the mouse is increasing. The touch gestures ontablets translate intomouse clicks andmotions directly.Anyway,most tabletsandphonesdon’thavekeyboards,sousingkeysisabadidea.

Therearenowmanyspecialgame interfacesavailableat lowcost,mostofwhichuse theUSB interface.This ismuchbetter than theoldparallelportor,evenolder,the“gameport”thatusedtobeavailableonPCs.Thesewerealmostalwaysusedtoplugina“joystick,”acurioustermforagamecontrol.

One such special-purpose interface is the steering wheel-pedal set thatconvertswheel andpedalmotions into character sequences.The fact that theycan be configured to send any sequence you like means that game interfacesdon’t have to be standard anymore, at least in the long run. More and morepeople will acquire the special interfaces until the keyboard becomes old-

Page 36: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

fashioned.Figure0.5showsoneparticularbrand,theLogitech.Another USB interface device is the flight stick; the idea is to make the

interfacelookmorelikethatofanairplanebygivingitasimilarcontroldevice.TheLogitechWingmanshowninFigure0.5isoneexample,whichagaincanbeconfiguredtoprovidespecificcontrolsequencesforanypossibleaction.

FIGURE0.5Special-purposegamecontrollersforspecificgenres.(Left)Adrivingcontrollerthatemulatesasteeringwheel.(Right)Aflightstickforaircraftandothervehiclesimulations.

Aproblemisthatthereisno“feel,”inthattheactionisfromtheplayertothe

Page 37: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

game only. In a real airplane or car, the control—wheel or stick—provides aforce that counters the player’s actions, and that can be relative to the speed,direction,drivingsurface,orevenwind.Fewgamecontrollersdothis.Somecanvibrate, which gives a limited feedback. The Reactive Grip controller(Provancher, 2012) simulates responses of various weapons, like swords andguns,andisprobablythebestexampleofareactivedevicerightnow.

Therearemanyotherpossibilities,andprogress isproceedingrapidly.AtarecentGameDeveloper’sConference, for example, therewas an interface forsale that input brain waves from a couple of small electrodes attached to theskullandusedthesignalstoplaysomesimplegames.Theprice?Onehundreddollars. There is university research that includes somework on hand gesturerecognition as applied to controlling games on the PC—hand motions areinterpretedasrequeststomove,picksomethingup,andsoon.Ultimatelygameswill become an invisible technology, like telephones and TV. They will beanywherewelikeandwillrequirenospecialknowledgeorhardwaretoplay.

Pace/ScaleThe driving games that are the most fun typically allow you to go fast.

Submarines move slowly but inevitably and cannot turn or stop in anyreasonabletime.Thepaceofthegamemustbeappropriate(thatwordagain)forthe kind of situation being simulated by the game. In addition, as the playergainsexperience, thegameshouldpresentmoreandmoredifficulties. Insomegamesthismeansthatthegamespeedsup;othertimestherearemoreorstrongeropponents.

Animpressionofspeedcanbegivenbyplacingobjectsneartheplayerthatmovepastatahighspeed.Buildingsaregoodforthisbecausetheyhavealotofdetail that flashespast ina similarway towhatwe’dseeonmoviesor in reallife.Infact,avarietyofobjectsinarangeofdistancesiseffectiveinconveyingtheillusion.

Soundiscrucialaswell.Playafasttempogamewiththesoundofftoseethedifference.A fast-movingmusic trackhelpsa lot, asdoesagood setof speedimplyingsoundeffects:positionalsound,Dopplereffects,andsoon.

Oneniceideathatissimpletoimplementandisnowastandardingamesisabackdropwithscenerypaintedonit.Thiseffectisusedinmoviestoo;theshotsoftheinsideofBorgshipsonStarTrekareactorsinfrontofpaintings,andquitea lot of science fiction depends on paintings to convey distance and strangeenvironments.Theuseofdropsinagamecanadddepththatisnoticedifabsent,butusuallydrawsnocommentotherwise.

Page 38: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

A3Dgameconsistsofaterrainmodelontopofwhichwehavebothmovingandstationaryobjects.Thereisusuallyadistancebeyondwhichobjectswillnotberendered(far clippingplane), and asobjects get closer they seem to “pop”intoexistencewhentheypassthatdistance.Inthefardistancewehaveanimagepainted on a surface that passes for the horizon. This often has hills and skypaintedonit,oranurbanbackdrop.Inanycase, thedrophasnorealdepth.Agamewillhavethedroprotateastheplayerturnssoastogivetheillusionthatthecarchangesdirection.

Fidelity/AccuracyWhen we create a game, we create an entire universe. We get to decide

where thingsare,howbig theyare,what theyeat,andsoon.Inparticular, therulesofphysicsasweunderstandthemintherealuniverseareflexible,andwedecidehowtheyworkinouruniverse.Inmanykindsofgames,theaccuracyofthephysics takesabackseat toplayabilityandentertainmentvalue.So, ifyouhaveeverplayedDoom,youwillprobablyknowthattheplayercanseemtorunprettyquickly througha level.Youmaynotknowthat ifyoumeasuredit,youwouldseethecharacterhasatopspeedof60mph!Thisdoesnotdetractfromthefun;onthecontrary,restrictinggameobjectstonormalspeedswillslowthegamedownalot.

Physics includes a variety of topics, including how collisions are handled,how fuel is consumed, how fast the vehicles can accelerate andwhat the topspeedsare,howfastcarscanenteraturnbeforetheyskid,andhowavehiclecanbecome airborne if it reaches the peak of a hill.Most games do take libertieswithphysicstoenhancegameplay,especiallythemorecartoon-stylegames.Wewilldiscussthisfurtheraftertherehasbeenachancetolookathowphysicsisimplementedinagame.Justrememberthatanyrulecanbeviolatedifitmakesthegamemorefun.

EXERCISES

Thefollowingproblemswillexerciseyourknowledgeofthematerialinthischapter,andtheywillsometimesrequirethatyoudosomemoreresearchbeforeyouareabletocompletethem.

1. Describethevenue,conflict,pace,scale,andfidelityoftwogamesthatyoucurrentlyplay.Thinkaboutothergamesyouenjoy—dotheyhavecommonelements?

Page 39: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

2. ThegameNimhasaknownstrategyforwinning.Anygameforwhichawinordrawcanbe forced is said tobe strongly solved.Whatothergamesarestronglysolved?Nametwo.

3. Aseriousgame isone thathas some function inaddition toentertainment,suchaseducation.Nameatleastoneseriousgame.

4. Describe the interface toAngryBirds.Howdoes the interfacecontribute tothefactthatthegamecanbefoundonsomanydifferentplatforms?

5. Artstylecanbean importantaspectofagame.Sketch twopossiblevisualinterfacesforacomputer-basedNimgame.

6. ThegameSnakesandLaddersispurelyrandom.Thereisnostrategythatcanbe used; it all depends on the throw of the dice. Suggest rules thatwouldallowsomedegreeofstrategyinthisgame.

7. Consider the kind ofmaterials that can be found in a dollar store or craftstore.Makeupagamethatusessucheasilyfoundmaterials,writeasetofrules,andplay thegamewithat least twootherpeople.Did thegameplaythewaythatyouthoughtitwould?

RESOURCES

YaleGameTheoryclass,http://oyc.yale.edu/economics/econ-159.MIT course on Computer Games and Simulations for Investigation and

Education, https://ocw.mit.edu/courses/urban-studies-and-planning/11-127j-computer-games-and-simulations-for-education-and-exploration-spring-2015/

MIT Game Design course, http://ocw.mit.edu/courses/comparative-media-studies/cms-608-game-design-fall-2010/.

Raph Koster, Theory of Fun for Game Design,http://www.theoryoffun.com/theoryoffun.pdf.

https://www.archimedes-lab.org/game_nim/play_nim_game.html.

REFERENCES

1. ElwynR.Berlekamp,JohnH.Conway,andRichardK.Guy.(2001).WinningWays forYourMathematicalPlays,Vol.1–4.AKPeters/CRCPress.BocaRaton,FLA.

2. Johann Huizinga. (2016). Homo Ludens: A Study of the Play-Element inCulture.Kettering,OH:AngelicoPress.

Page 40: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

3. Aki Järvinen. (2008).Gameswithout Frontiers: Theories andMethods forGameStudiesandDesign.Tampere,Finland:TampereUniversityPress.

4. WilliamProvancher.(2011).Multidirectionalcontrollerwithshearfeedback.USPatent13/269,948,filedOctober10,2011,andissuedAugust14,2013,PublicationnumberUS2012/0038468A1.

5. Miguel Sicart. (2008). “Defining Game Mechanics.” The InternationalJournal of Computer Game Research 8, no. 2(December).http://www.gamestudies.org/0802/articles/sicart

6. JohnvonNeumann andOskarMorgenstern. (1947).Theory ofGames andEconomicBehavior,2ndedition.Princeton,NJ:PrincetonUniversityPress.

7. DanWhitehead.(2018).GameOver:TheGamesWeLovedtoPlayandtheConsolesTimeForgot.StudioPress.

Page 41: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER1

INTRODUCTIONTOHOWGAMESWORK

Computergamesarefirstofallgames,andsecondcomputerbased.Agoodwaytobeginasastudentofgamedevelopmentistoexaminearealgametoseehowit functions insomedetail.Wecan take itapartand takea lookathowacomputer game is structured at thedesign and implementation level.A simplegame that everyone knows is ideal for this purpose.Pong is one of the firstcomputergames,andithasalloftheelementsofothergames,exceptthatitissimpleenoughtounderstandcompletely.First, let’s takealookathowagameoperatesatthecomputerlevel.

VIDEOGAMEARCHITECTURE

The word “architecture” can be defined as construction or structuregenerally;anyorderedarrangementofthepartsofasystem:thearchitectureoftheuniverse.1

Accordingtothisdefinition,gamearchitectureshouldbeabout theinternalstructureofagame, itsgeneralorganizationasafunctionalsystemin termsoftheway that thepartsarearranged tocreateaworkinggame. Inorder to trulyunderstand the structure of a game, you prettymuch have to know somethingaboutcomputerprogramming,becausethecomputeristheenablingtechnologyand any computer game is a piece of software at the core. Without being aprogrammer, it is only possible to have a general appreciationof howa gamefunctions.Youneedtoknowwhat thepartsare—not thevisibleparts likecarsandroads,butthestructuralandfunctionalparts,liketheaudiosystemandtherenderer.Youneedtounderstandhowthepartscommunicatewithoneanotherandwhatonepartneedstoknowtoaccomplishitstask.

A game player cannot be required to know this. The player needs only toknowtherulesofthegame,thetask,theinterface;thosethingsneededtoplay.Infact,mystudentshavetoldmethatafterstudyinggamesandwritingone,they

Page 42: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

never look at a game in the same way. They still play games, but they findthemselves asking, “why did they put that building there?” and “how do theyimplement those torches?”So,knowinghowgamesfunction“under thehood”cansometimesinterferewith,orothertimesenhance,theexperienceofplayingthem.

Inatechnicalsense,acomputergameisaninteractivereal-timesimulationwithagraphicalandaudiodisplay. Ifyouaccept thisdefinition, then therearealreadyanumberofidentifiablecomponentsthatcomprisethegamesystem:thegraphicssystem,theaudiosystem,theuser,andthescheduler.Theonlyessentialpartthatismissingistheartificialintelligence(orAI),whosejobistokeeptrackofthesimulatedobjectsinthegame.

Figure 1.1 shows a diagram of the basic components and how they areconnected. It is not the only organization, and it certainly does not show toomanydetails,butitshouldbegoodenoughfornow,anditwillformthebasisofthis discussion. So, the remainder of this chapter will describe each of thesecomponents of a game and how andwhat they communicatewith each other.Thiswillgiveyouamuchclearer ideaofhowtheoverallgamefunctionsasasoftwaresystem.

Acomputergameofferstheplayeraworldthatdoesnotreallyexist.Withoutgettingtoophilosophicalaboutit,whatyouseethroughthecomputerscreenisarendition of data that represents a simulated situation.What you see is a realscreenwithrealimages,butthesituationandwhatisbeingdrawndonotexistintherealworld—itisananalogy,avirtualenvironmentinwhichyoucontrolthelaws that dictate how objects interact (for instance, gravity or the results of acollision).A significant part of a game, in termsof code and time required tocreate it, is thepart thatdisplays imagesandsoundsfromtheimaginaryworldfortheplayertoevaluate.

Page 43: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE1.1Generalarchitectureofacomputergame.

Beforeproceeding,itshouldbenotedthattherearemanytypesofgamesandthateachhasitsownspecificneeds.Thismeansthattheviewpoint,ortheplacefromwhich the simulated universe is seen,will vary from game to game andgenretogenre,andsothediscussionmustbesufficientlygeneraltoallowmanyperspectives. Many games that are played online, through browsers, areeffectivelytwo-dimensional(2D),andsothediscussionwilleventuallyfocusonwaystorender2Dgameseffectively.

In a three-dimensional (3D) environment, we perceive the game universefromourparticularpointinspaceandprojecttheviewfromthatpointontoa2Dplane for display on the screen. What is going on a great distance away isunlikely to be relevant to us, and so the graphics system might not botherdisplayingit.Theregionaheadforthenextfewfeetormetersoryardsiscrucial,and how we respond to that will influence the meters following that. Theimportant thing as a gameprogrammer is to display the things that the playerneeds tomakegameplaydecisionsand to feel that thesimulatedworld is real.The display of key data involves two main aspects: visual data, requiring acomputer graphics system, and sound data, which requires an audio display

Page 44: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

system.Mostgameshavebothofthesethings.

TheGraphicsSystem

Many people still think that games are all about graphics. They are not,really, but many games use more CPU time in drawing the scene than foranything else.An efficient graphics system can leave a reasonable number ofCPU cycles for use by other aspects of the game system, and that is veryimportant.Agoodgameusesanappropriate levelofdetail for theapplication,andthat’simportanttoo.Thebasicproblemaddressedbygamegraphicssystemsis placing enough frames (images) on the screen every second to give theillusionofmotionandrealism.Moviesuse24framespersecondtoachievetheirdegree of realism, while television uses almost 30 per second. However, atelevision displays an image that is about 525 x 525 pixels, while a motionpicturehasamuchhigherresolution.

Anotheraspectofpicturedisplay thatmustbeconsidered is thenumberofdistinct colors that can be shown. This is sometimes called quantization, andtelevision,forexample,candisplayfarfewercolorsthancanamotionpicture,andacomputerscreenfallsinbetween.

Somesimplemath:at24framespersecond,withacomputerscreenhavingaresolutionof1024x768andusing24-bitcolors,weneedtobeabletocalculateandwriteout56megabytesofdatapersecond.Thisseemslikequitealot,evenon a modern PC, so we have to use a few little tricks. First, and mostimportantly, the video card has been taking a larger role in the calculation ofscreenupdatesforgames.Videocardscandrawmillionsofpolygonspersecondandcandomoreadvancedandesotericoperationsliketexturemapping,supportforstencilbuffers,andmip-mapping.ThismeansthattheCPUdoesnothavetodothesethingsbutsimplyorganizesthedataforthevideocard.

Thefundamentaldifferencesbetween2Dand3Dgamescanbesummarizedbysaying that ina3Dgameallobjectsare3Dandneed tobeviewed fromaparticularpointinspace.Thegraphicssystemwillflattenthescenebyprojectingitontoaflatsurface,andthismeansthatsomeobjectswillbehiddenbyothers,somewillbetoofarawaytosee,somewillbebehindusandsonotvisible,andall objectswill be transformed so that theusual visual cueswill apply for theviewer (player). This last item usually means something called a perspectivetransformation,inwhichobjectsfartherawayfromusappeartobesmallerandparallellinesappeartomeetatadistancepoint.Forexample,inadrivinggameifwearedrivingacarandlookingthroughthefrontwindshield,thenourfieldofviewisrestrictedtotheregioninfrontofus,say60degreestoeachsideofdead

Page 45: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ahead.Objectsthatarenotinthatregioncanbeignoredandshouldnotrequireanysignificantamountofcomputation.Also,objects that are too farawayarealsotobeignored,astheywillbetoosmalltosee.Ofcourse,figuringoutwhatcanandcannotbeseenrequirescomputationaleffort.

In a 2D game we usually view all objects from the side or from above.Sometimes the gameplay area is bigger than the screen, and the backgroundscrollsastheplayer’scharactermovesabout.Objectsina2Dgamearesim-plerandeasiertodraw,andperspectiveisnotanissue.

Someof thework indrawing theviewsmustbedonebyyouas thegameprogrammer, butmuch of it can be handled by your graphics card. There arequiteafewsuchcardsoutthere,andeachhasitsowncapabilitiesandinterfaces.Ifyouwantyourgametorunonmorethanonecomputer,youcannotcodeyourgraphics systemfora specificdevice.Fortunately, thereare softwarepackagesthat form a layer between us and the graphics card, hiding the differencesbetweenthecardswhilepresentinguswithaconsistentinterface.Thisisreallyessentialforacommercialgame,anditisprettyimportantforustoo.

The programming language Python has no built-in support for graphics orgame development. It’s a very popular language for teaching introductorycourses and is popular in the programming community, especially the Linuxcommunity. However, associated with Python is a very useful package calledPygame thatprovidesallof the facilitiesneeded tobuildalmostanycomputergame,andthatbeginswithaveryusablegraphicslibrary.Itallows2Dgraphicsand a 3D library that looks likeOpenGL; this bookwill rely heavily onwhatPygamesuppliesforgraphicssupportgenerally.SincePythonrunsonallmajoroperating systems, this means that a game developed using that language isplayable effectively everywhere. The thing to remember about most gamegraphicssystemsisthatthe3Dsystemsarebasedonpolygons,sincepolygonscanbedrawnquicklyusingagraphics card.Wecan represent anyobject as acollectionofpolygons,aswellasshadethem,placetexturesonthem,rotateandscalethem,andsoonusingveryfastalgorithms.

Ifyoureadalotofgameprogrammingbooks,youwillfrequentlyencounterthe phrase graphics pipeline. The idea is that if you can keep a number ofsoftware modules busy at the same time, you can achieve an increase in thenumberofpolygonsyoucanprocesspersecond.Thereareafewwaysthatthepipeline canbeorganized, but here theviewwill be taken that there are threebasicparts:theobjectlevel,thegeometriclevel,andtherasterizationlevel.

ObjectLevel

Page 46: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

At this stage the objects are still understood as such, rather than ascollections of primitive graphic entities like polygons and lines. We doanimationat this level,aswellasmorphingandcollisiondetection—basically,anyoperationthatneedstoknowabouttheobjectsthemselves.Attheendofthisphase,asetofpolygonsorlinesissenttothegeometriclevel.

This part of the pipeline is the most sensitive to the game itself. It isimplemented in software, most often by the game designers and creators,becauseitistheywhounderstandthegameobjectsbest.

GeometricLevelThe geometry part of the pipeline has a variety of functions that can be

broken off into distinctmodules, as seen in Figure 1.2. 3D geometry ismuchmorecomplexthan2D,andthefigureillustratesthemorecomplicatedsituation.The first step convertsmodel-based coordinates,which are often based on anobject-centeredcoordinatesystem,intoamoreglobalsystemofcoordinatessothatobjectscaninteract.

Next,basedonthepositionoftheviewer(camera),wecomputeacoordinatetransformationthatalignsthepolygonsoftheobjectstoacommonsystembasedon the viewer.One result of this is that some polygons become impossible tosee;theymaybebehindusortoofaraway.

Nowweconsiderthepositionandcolorofthelightsandcreateappropriateshading and color transformations of the object’s polygons. The sun, forexample,ispositionedagreatdistanceawayandiscoloredyellow-white,whileanearbyheadlightmightbeabrighterblue.Thecolorofapixelisafunctionofits own intrinsic color and of the brightness, color, and position of theilluminationsources.

Now we compute the viewing transformation, most often a perspectivetransform. This gives us the view we would expect of a three-dimensionalobject, including the fact that distant objects look smaller thannear ones.Theviewofthescenewillberealisticifitrepresentswhatweexpect,andweexpecta perspective view. The objects that used to be 3D polygons are now two-dimensionalones.

Page 47: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE1.2TheGeometryPipeline

Thepolygonsthatfalloutsideofthecomputerscreenarea,orviewingarea,mustbeeliminated,orclipped.Thisisthenextstage.Polygonsthataretoocloseor far away would have been clipped in the previous stage. Clipping is anontrivialoperation.Forexample,atrianglethat ispartlyoutsideofthescreenarea iscutbyaverticalorhorizontal line,and thisoftenmeans that it isnotatriangleanymore.Finally,allcoordinatesofalllinesandpolygonsareconvertedinscreen(orwindow)X,Ycoordinatessotheycanbedrawnquickly.

RasterizationInthisstage,weconvertlinesandpolygonsintopixels.Theonlythingthata

screen can display is pixels, so it is essential that this step be performedaccuratelyaswellasquickly.Afterthisisdone,wecandoanyotheroperationsthatneed tobedoneonaperpixelbasis.Muchof this isdoneby thegraphicscard.

CommentsonOptimizationIt should be obvious that the codemust be efficientlywritten, because the

graphicssystemmustrenderasufficientnumberofframespersecondsothatthegameappearstobesmooth.Thealgorithmswechoosemustabletodealwiththenumber of polygons likely to appear in the objects, in both space and timeconsiderations.

The gamewe are going to createwill, first and foremost, have to displayscenesonthescreenwiththecorrectpositionsandcolors,followthegamerulesas designed, and play sounds at correct moments. While we will not beintentionally wasteful, efficiency will not be the most important thing.Why?Because code optimization can become boring very quickly, and it is not ourmain interest. There are many reference works on the subject for those

Page 48: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

interested, including Game Coding Complete and Core Techniques andAlgorithmsinGameProgramming.

TheAudioSystemIn general, the purpose of the game’s audio system is to play music and

sound effects. This is supposed to be a simplistic view, and yet even afterdecades of technological changes in game technology and design, the gameaudio system still does pretty much what it always did, and still works in asimilarway.Huge steps forward have beenmade in the area of graphics, butstandardsarestillweakandtherearealotofadhocschemesoutthere.

Most sounds thatwewill need, like an engine sound, a door opening andclosing, crashes and scrapes, and even the music, will be read in from files,usuallyone fileper sound.Averycommonformat for sound files is theWAVfile, basically aMicrosoft standard that is supportedonmostplatforms.Thesecancontaincompressedoruncompressedaudio,canhavemonoor stereo,andcanstoreaudioatavarietyofsamplerates, includingtheCDstandards.It isasimplefileformatandveryconvenientforourpurposes.

However, there may be a need for more sophistication on the part of theaudio system. Itmay be asked to play positional audio, in which each soundappears to originate from a particular point in space. This can be done withstereo,butitismuchbettersuitedtomodern5.1channelaudiosystems,whichcan be truly impressive. Sound cards have recently been designed with somecapacity for sound synthesis, and some degree of synthetic sound andmusic,especiallyusingMIDI,cannowbefoundongames.However,thebasicfunctionoftheaudiosystemissimple,anditsjobisobvious:weneedtoplayandstopasoundoncue.HowthisisdonewillbethesubjectofChapter3.

GAMEDESIGN

Beingagamedesignerisnotascoolasmanypeoplebelieve.Yes,theverybestgetsomeattention,butfewpeopleknowthenameorfaceofthepersonwhodesignedtheirfavoritegame.Moreover,agamedesigner’sjobmostlyinvolvescreating written design documents. Yes, they must have ideas about how thegame will operate, but the key job of a designer is to communicate thoseconceptsindetailtothepeoplewhowillimplementthem.Notjustprogrammers,butespeciallyartists,musicians,andotherdesignerssuchasleveldesignersandcharacterdesigners.

Earlier it was said that a game designer really created game mechanics.

Page 49: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

That’strue.Adesignereithercreatesnovelmechanics,aswasdoneinthegamePortal, or fits existing mechanics together into a new game. Really newmechanicsarerare,buttheydooccurfromtimetotime.Theimportantthingisto incorporate simple mechanics into a novel and interesting situation.AngryBirds did that very well. The use of one’s finger to specify the direction andforce of a throw combined with the interesting concept of knocking down astructuremadeofblocksmadeforacompellinggame.There’sreallynowaytospecifyaformulaforaccomplishingthat.

Fortunately, that’s not needed. A game programmer has relatively littlecreative input toagame.Theprogrammer isgiven thegamedesigndocumentandisassignedapartofthegametoimplement(i.e.,writethecodefor).Agameisaspecialkindofprogram,though,andthereisaspecificsetofknowledgethatoneneedsinordertobegoodatthetask.

MechanicsThesubjectofgamemechanicsisgoingtoariseagainandagain,soagood

definitionwouldbeuseful.Unfortunately,thistermismoregenerallyunderstoodbydesigners,butitishardtodefineforpeoplewhodon’tbuildgames,anditisimpossible to explain to people who don’t play them. A commonly quoteddefinition,andtheoneappearinginWikipedia,is:

A game mechanic is a construct of rules intended to produce a game orgameplay.

Thisisabitcircular—gamesusemechanicsandmechanicsmakeagame,asitwere.Also,noteveryonewouldagreethanrulesmustbedirectlyinvolvedinthedefinition.Järvinen(2008)definesmechanicsas

meanstoguidetheplayerintoparticularbehaviorbyconstrainingthespaceofpossibleplanstoattaingoals.

This is possibly better because it puts rules into a subservient position toplayeractions.Thereisaninstinctiveviewthatamechanicissomethingthataplayerdoes, and something that is designed into the game. Another possibledefinition(Sicart,2008)is:

Game mechanics are methods invoked by agents for interacting with thegameworld.

Page 50: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Bylookingatacollectionofdefinitions,wemightgetaninstinctiveideaofmechanics.Itisakeyconcept.Theideaappearstobethatagamemechanicisadesign feature of a game that allows the player to progress toward the goal.There can be mechanics that interfere with forward progress too. So, oneexamplemechaniccouldbecalleddodge, inwhichplayersmustavoidobjectsmovingtowardtheiravatars.SpaceInvaders isoneexampleof this.Theshootmechanicisacommonone,whereyoumusthityouropponentoratargetwithathrownmissileofsometype.Theracemechanic involvesaplayergettingtoaparticularspotinthegamebeforeanyopponents,andsoon.

Agamemechanic shouldbe interesting to theplayer and simple touse.Abuttonpressormousegestureisusuallyallthatispossibleinagame,sothesemust be converted into game elements that implement the mechanic—pressspacetoshoot,uparrowtomoveahead.Themechanicisnotspecificallyabouttheinterfacethough.OneofthebettergamemechanicsinrecentmemoryistheoneusedinthegamePortal,wheretheplayercreates(usingamouseclick)twocircular doorways through any floor, ceiling, orwall.Walk theplayer’s avatarinto one doorway and it exits through the other! This can be used for quitecomplexmazepuzzles.Themouseclick,however, isnottheissue—itisaboutthepossibilitiescreatedbytheclick.

PLAYINGTHEGAMEBYTHERULES

What we have seen of game architecture up to this point is what can becalled the gameboard, the part that the user sees andmanipulates. There aremanyprogramsthathaveverysophisticatedgraphicalandaudiointerfacesthatare not games. What’s the difference? A game, the kind of game we arediscussing,worksinrealtime,processinguserchoicesandupdatingthedisplayaccordingly.Agameisasimulationand,mostimportantly,isonethathasagoal.Tobeagame,theremustbeawaytoatleastkeepscore,andusuallythereisawaytowin.Thepartofthegameprogramthatdoesthisisvariouslycalledthegamelogicsection,theartificialintelligence,andsomeotherthingstoo.

Thegraphicsandaudiopartsofagamecanlargelybesharedbetweengamesthat are quite different from each other. The game logic is what makes eachgamewhatitis.Itisthecodethatreflectsthegamedesigner’sintent.Evenhere,thestructureofthisprogramhasacertainconsistencyfromgametogame;itisinthedetailsthatthecodediffers.

MostofaComputerGameIsHidden

Page 51: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

The player actually sees a world drawn by the graphics system, but thisworldisparticular to thegameathandandchangesaccordingtorules thatarelargelyinvisibletotheplayer,atleastatfirst.Partofthegameplayisfiguringoutwhattherulesare.Forexample,howfastcansomeonedriveintothatcornerbeforeskidding?Thatisactuallyakindofrule.What’stheratioofbraketogaspedalforaproper180-degreeturn?Again,thisisarulethatisdiscovered.Thenumberofdamagepointsyoucan takebeforeyourcarblowsup isanexplicitrule that is statedup front, a slightlydifferent thing.Most gameplayers don’treadalotofrulesbeforestartingtoplay,andinsteaddiscoveralotoftheexplicitrulesastheygoalong.

Sowhenwe say that a lot of the game is hidden,wemean that the rules,interrelationships between game objects, goals, and even your particularprogressthroughthegamearesavedincodeandinternaldatastructuresandarenot necessarily displayed. Indeed, their internal representation does not lenditselftodisplay.

TheArtificialIntelligenceTheartificialintelligence(AI)subsystemofagameisresponsibleformany

thingsthatthegamedoesthatarenotseendirectlybutarereflectedingameplayandrealismaspects.TheAIdoesobjectmanagement,includingphysics,andthedirectionofindependentsimulatedobjectslikeopponents,inourcaseopposingdrivers.Specifically,theAIkeepstrackofthecurrentpositionandvelocityofallobjects.Thus, it is the logicalplace todocollisiondetection. Itkeeps trackofattributes of objects, including earned attributes like hit points, damage, andfoundobjects(ammunition,money,etc.).

Artificial intelligence has a connotation among the general population,supportedbymoviesandTV,ofcomputersthatcanthink.Inthemoviestheyarealso frequently evil, but we’ll leave that for later. Computer scientists andprogrammers know more about the details, and they realize that AI is aboutmaking a computer appear to be intelligent. The techniques that computerprofessionals use are many and varied, but the truth is that game AI is verysimplisticcomparedwiththetechniquesfoundinresearchlabs,andthegoalsarequitedifferenttoo.

The basic problem is that the gameAI has to function in real time, and itmust steal CPU cycles from what is perceived to be really important—thegraphics system. Thus, the really complex and sexy functions of an advancedrealAIsystemaresimplytootimeconsumingforagame.Goodthingtheyaremostlynotrequired.Forexample,avoicerecognitionsystemwouldbecoolon

Page 52: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

some games, but really isn’t needed. Games AI is rarely required to provetheorems, recognize faces, or invent novel answers to complexquestions. It isrequired todecidewhat todonextand toplana route throughabuildingoraforesttoagoal.Maybeitwillhavetodecidehowbesttopassyouonahairpincurve. Although it is sometimes useful to use an advanced technique like aneuralnetworktoaccomplishagamegoal,itisunusual.

However,onethingthatallAIsystemsmustdoiskeeptrackofeverythingon the screen and most things that are not. Not only does the game have todecidewhenyouhitthewall,butitmustalsokeeptrackofalloftheothercars,even theonesyoucannotsee,andslowthemdownwhen theyhitanobstacle.MostoftheAIsystemisaboutsimplerulesimplyingsimplechoices.Themostcommonimplementationofsuchachoiceis:

if(conditionistrue)then{dothisthing}

This is not especially sophisticated, but it does the job quickly. The samethingcanbeimplementedasatableoratree,asyouwillseeinChapter5.

GameStateThestateofagameisacollectionofinformationthatrepresentsthegameat

any given time. Given the state, a game can be started from that point. Theinformationneededinthestateincludes:

– position,orientation,velocityofalldynamicentities– behaviorandintentionsofAI-controlledcharacters– dynamicandstaticattributesofallgameplayentities– scores,health,powerups,damagelevels,etc.

Allsubsystemsinthegameareinterestedinsomeaspectofthegamestate,becausethestatevariablesareexactlythosethingsthatareessentialtothelookof the game and the play options possible from any point. For instance, therendererneedstoknowthepositionofobjectstodraw,theirdamagelevels,andsoon.

How is thegame statemade available to subsystems?As always there aremany options, each with their own advantages and disadvantages, but for astraightforward driving game, there are only a few that make sense. In mostcasesanobjectiscodedasaninteger.

Page 53: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

GlobalStateThisisjustwhatitsoundslike.Statevariablesareglobal,sharedbyallofthe

modules.A lotofprogramming languagedesign and software engineeringhasgoneintotryingtoshowwhythisisapooridea.Afterall,imagineeverymodulehavingaccess—completeaccess,mindyou—toeveryothermodule’svariables.Chaos!

On the other hand, there is a certain convenience to this scheme. If thegraphicssystemwantstoknowwhereatreeis,itsimplygetsitfromwhereitisstored.Theproblemisthatitcanchangeit,ofcourse.Really,ifyouarewritingaquitesmallsystemwithprettyclearmodules,andyouarerelativelydisciplined,thenthiswillworkoutOK.Themorecomplexthegameis,themorelikelythisschemeis(exponentially!)toresultinproblems.

Push/Pull(clientserver)Here, subsystems have incomplete knowledge of one another, and can

request information from each other in a structured fashion (apull) or send anewvaluetoamodule(apush).This iswhatwewilluseinoursamplegame,and it is whatwe often see in Java andC++ as accessors andmodifiers. Forexample,ifwewanttofindthelocationofaball,weaskforitusingafunction:

getPosition(BALL,x,y);

whichisapull.IfwewishtonotifytheAIsystemthatanobjecthasbeende-stroyed,wedoapush:

setExist(object[i],FALSE);

whichsetstheexistattributeoftheobjecttofalse.This scheme is elegant, but it has another big advantage: it can be used

acrossgreatdistanceswithequal simplicity.Foronlinemultipleplayergames,thepush-pull schemeoperatesona serverata remotesite,andoneofvariousremoteinvocationschemescanbeused,transparently.

ManagersInsomesense this is like thepush-pullmodelwithan intermediatesystem

forhandlingtherequests.TheAIsystemdoesnotownpositionandorientationttributes in this scheme, for example. They are owned by a managementsubsystem that has the simple task of hiding the variables and structures andpermittingaccesstothemusingstandardaccessorandmodifierfunctions.

Page 54: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

So,usingthisschemetheAIsystemwouldhavetoaskforthepositionofanobject just like the graphics system, and would also have to request amodificationtoapositionfromthemanager:

manager.getPos(OBJECT1,x,y);

manager.setPos(OBJECT1,x+1,y+1);

Thisisnotmuchmorecomplexthantheclientserverapproach,andithasasimilar feel. There are few tools that support this model, and so discipline isneededtomaintainit.Therearefewsituationsthisschemewouldavoidthattheclientserverschemewouldnotalsoavoid,andsothat’snotadistinctionbetweenthetwo.

Broadcast-listenerForacertainamountofoverhead,wecanchangetheclient-servermodelinto

oneinwhichmodificationstostateattributescanbesenttoothersubsystemsbyissuinganevent.So,whenthepositionofanopponentchanges,forexample,an“opponent-change” event canbe sent to thegraphics system so that itmaybedrawncorrectly.GivenasystemsimilartotheJava interface scheme thatuseslisteners, all subsystems interested in this change can be alerted at the sametime!Objectsorsubsystemsinterestedinaparticularevent,likepositionchangeofpolice cars for instance,would registerwith the listener so that theywouldreceivetheevents.

So,usingaJava-likesyntax,wecouldhave:

publicclassZextendsqimplementsBallListener

{

...

t1.addBallListener(this);

...

}

publicvoidballMotion(GameEvente)

{

if(e.getSource()==t1)...

}

This shows the three essential parts of the setup: declaring the use of theBallListenerinterfaceintheclassheader,addingthisclassinstancetothelistofthose interested in receiving police motion events, and writing a handler (acallback, really) named ballMotion that will be called when a police motioneventtakesplace.Thereisnodirectcommunicationbetweensubsystemsinthisscheme.Informationissenttothoseinterested,andonlythose,andisqueuedin

Page 55: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

thecasewheretherearemultipleeventsoccurringsimultaneously.Now,thisisprettyclever,andifyoucanmakeitworkproperlyinalanguage

notofferingspecificsupport,itissuretogiveyouaprogrammerrush.Onalmostall PC systems, a process generally uses only oneCPU.We can pretend thatprocessesareindependentifwelike,butswitchingbetweensoftwareprocessestakes time on our single CPU, and treating software events like variablemodifications as if they were asynchronous processes is a little wasteful andobscures the flow of the code. This system works efficiently on a multiple-processor console like the PlayStation. Still, some systems profit from usingthreadsandsuch,andthisisthewaytodealwithstateonsuchsystems.

SharedandGlobalEntitiesThis uses the inheritance characteristic of the language, object-oriented, of

course,inwhichthegameisimplemented.Thinkofitasglobalstate,butwithreferences to classes and inheritance.So, both theAI and thegraphics systemwould have a reference (pointer) to a police car object, and could, bymanipulating the accessor and modifier methods, get and change the object’sposition,orientation,andotherattributes.Thisistheclassicobject-orientedway—cleanerthanusingglobals.

Within this scheme there are many options: a single rooted hierarchy,ownership, multiple inheritance, and so on. This kind of thing has, in fact,become the standard practice in many colleges and universities that teachprogramming(minetoo!),andasaresultthismethod,orfamilyofmethods,hasbecome themost common scheme formanipulating game objects and systemstate.

Animportantcomplaintwiththissetofschemesisthattheytendtobecomedependent on a particular language, usually C++, and then decisions become“religious.”Thisisbecauseofmanyanargumentwith“softwareengineers”overthingsliketheproperuseofmultipleinheritance,forexample.SinceC++isoneof the few languages that permitsmultiple inheritance, a scheme that dependsupon it has limited options for implementation. The problem is that a singlerooted class hierarchy does not scalewell, and the inheritance structure startslooking like nonsense after a while. Therefore, the most complex system(graphics, in general) tends to be able to specify the structure of the rest.Multipleinheritancescalesbetter,butitishardtochangelaterandbecomeshardtomanagewhen the systemgetscomplexenough.Therearealsoperformanceissuesinalloftheseschemes.

There is no best scheme, but one based on a client-server scheme or on

Page 56: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

managerscanworkwellusingobject-orientedlanguageslikeC++andJava,andeveninCwhereobjectorientationishandcoded.Eachmodulecontainsasetofvariables and data structures that cannot be accessed from the other modulesexceptthroughtheaccessorfunctionsprovidedbythemodule.However,whenneeded for testing orwhilemergingmodules, there can be globals and sharedentities;alogfile,forexample,fordumpingtest informationwhiledebugging.ThereisnothingtopreventtheuserofthisschemefromusingJavaorascriptinglanguagelikeLuaasatoolforcreatingsmall,specific-purposesub-modules—asthecontrollerforanopponent,forinstance.

However we do it, the management and control of the system state in acomplex system like a computer game must be done carefully and withdiscipline. While the best way has yet to be determined with certainty, it isabsolutelyclearthatmodularity,planning,anddisciplinemustbeusedifsuccessistobeachieved.Sittingdowninfrontofthecomputerandstartingtoentercodeis sure to fail, later ifnot sooner.Agamedesigndocument isessential so thatmorethanoneprogrammer/developercanworkonthegameatthesametime.

PONG

Pong issufficientlyoldthat it’spossiblenowthatsomepeopledon’tknowwhatitis.Theideaistocreateabasicsimulationoftabletennisorpingpong.Itisagamebythedefinitiongivenpreviously:

– Itisanactivity,certainly.– Itisentertainingbysomestandard.Ithasnootherpurpose.– It has rules. There is a ball that moves about the screen according to

basicrulesofinteraction.Itbouncesoffofwalls,basically.– Ithasobjects.Thereisaballandtwopaddles.– There is aplaying area, a window on the screenmeant to represent a

table-tennistable.– Therulesare:Aballwillbecreatedandwillbemovinginaspecificdirection.Eachplayer(therearetwo)controlsapaddle,whichisjustaverticallineon

thescreenneartheleftorrightendoftheplayingarea.Byusingkeyson thekeyboard, theplayercanmake thepaddlegoupand

down.Thekeymechanicistoblockthepassageoftheballsothatitdoesnotreach

theleftorrightendoftheplayingarea,thatis,hittingtheballwithyourpaddle.

Page 57: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Iftheballpassesyourpaddleandgetstothesideoftheplayingareayouareprotecting, then your opponent gets a point. A new ball is created when thishappens.

Theobjectseachhaveagraphicalrenditionthatisdisplayedonthescreenatthe locationwhere they are supposed to be in the play area. The paddles aresimplylines,andtheballisjustacircle.Theprogramthatimplementsthegamehas tokeepupdating the screen tomake it seemas if theball andpaddlesaremoving.

FIGURE1.3ThePongdisplay.

This is an optical illusionmuch like the one used bymotion pictures andtelevision. If the human visual system is presented with repeated still imageswhere objects appear in slightly different positions, it has the appearance ofmovement.

What the gamedoes is tomove the objects to newpositions based on themovementsspecifiedbythegameandtheuserandthendrawtheobjectsagain.Itdoesthismanytimeseachsecond.

Thegamesoftwaredoesotherthingstoo,ofcourse.Itkeepstrackofeventsthathappeninthegame.Whentheballhitsawall,that’sanevent.Whenaballhitsapaddle,it’sanevent.Whentheballreachesoneendofthetable,that’sanevent. These are the basic events in Pong, but the end of the game shouldprobablybeanevent,althoughitcanonlyhappenonce,andtheresettingiftheballafterapointcouldbethoughtofasanevent.

It should be clear that this computer game is implemented by properhandlingofalloftheeventsthatcanoccur.Let’smakeitintoaprinciple:

Thesoftwareinvolvedinacomputergamekeepstrackofallobjectsandimplementstheinteractionsbetweenthemaccordingtotherules.

Page 58: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Agameisreallyasimulation.InPongthere’snorealballorpaddles,onlyasimulationofaballandpaddles.Therecanbenoactualimpactbetweenaballandapaddle,onlyanevent that indicates theirgeometryhasoverlappedandaresponsebythegameprogramtodosomething,inthiscasechangethevelocityof the ball. Pong is a real-time simulation of table tennis with sound and agraphicaldisplay.

It is a willing suspension of disbelief on our part that objects in a gamebehave as real objects in the world do.When that fails to happen, we noticeimmediately,thegameisnowflawed,andthefourthwallisbroken.Theplayerisnowusingapieceofsoftwareandisnolongerimmersedinagame.

GoingbacktothegamePong,Figure1.4showsapotentialstartingpointforthe game. The ball starts at a location (xb, yb) with a velocity (dx, dy). Thepaddlelocationsarealsoknown.Thissituation(state)canbedrawnimmediatelyasthefirstimage(frame)inthegame.Thenextsituationhastheballmovedintoanewposition.Thisisdonequitesimply:

xb=xb+dxyb=yb+dv

Ifthepaddlesarenotbeingmoved,thenthiswillbetheonlychangeinthegame, and the next image (frame) will be drawn with the ball in the newposition.

FIGURE1.4Theobjectsintheponggamespace.

If the leftpaddle isbeingmoved, itwillbebecause the leftplayermade ithappenbypressingakey.Letthekeythatmovestheleftpaddleupwardbe“w”andtheonethatmovesitdownwardbe“s,”althoughthisisadesigndecision.If

Page 59: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

the left player presses “w,” the left paddle will move up. Howmuch? That’sanotherdesignchoice,solet’scallthatdistancedpy.Theprogramwoulddothis:

y1=y1-dpy

If the“s”keyhadbeenpressed, then the leftpaddlewouldmovedownbythesameamount:

y1=y1+dpy

Thisworksthesamewayfortherightpaddle.Theup-arrowkeywillmoveitup,andthedown-arrowkeywillmoveitdown.Iftheup-arrowispressed:

yr=yr-dpy

andifthedown-arrowispressedthen:

yr=yr-dpy

When the new frame is drawn, the paddles will be drawn in their newpositions.Thisprocesscontinuesforstepafterstep,frameafterframe,untiltheball’sxpositionbecomesmallerthan0(wentpasttheleftpaddle)orgreaterthanthescreenwidth(wentpasttherightpaddle)ortheballcollideswithsomething.Colliding with a wall changes the ball’s y velocity, so it changes direction.Collidingwithapaddlechangesitsxvelocity.That’sbasicallythegame.

FIGURE1.5SequenceofconsecutiveframesfromthegamePong.

Figure1.5showsasetofconsecutiveframesfromthegameillustratingwhat

Page 60: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

thegamesoftwaremustdobetweeneachpairofframes.Thingsthatshouldbemoved must be moved, collisions must be resolved—velocity changes, forexample.Otherthingscouldoccur,likeachangeinscoreoranewball,butthepoint is clear: the software must look for any possible event that happensbetweenanytwoframesandworkthatintothegamedisplay.

THEGAMEDESIGNDOCUMENT

Agamedesigndocument(GDD)shouldspecifyeverythingthatcanhappenin a game and how itwill be resolved.Each interaction between each pair ofobjectsneeds tobedefined inacarefulmanner,and inenoughdetailso thataprogrammer can implement it in the way that the designer anticipated. Eacheventmustbecarefullyandfullycharacterized.Itisasoftwarespecificationandmuchmore,becauseitdefinessoundsandartisticassetsaswell.Programmers,artists,musicians,andleveldesignersallhaveaccesstothissamedocument.It’slikeaBible.

Aprogrammerdoesnotcreate thisdocument; thegamedesignerdoes.Theprogrammer needs to know how to read it though. A book about gameprogrammingshouldteachhowtoreadadesigndocument.Solet’sdothat.

C2H6OJetBoatRaceA game starts with an idea. Ideas are relatively common in creative

industries,butgoodideasarelesscommon.Inthegamesarena,ideashavetobewinnoweddown to avery few thatmaybeworth implementing. It’snot clearthattheideaforagamebeingpresentedhereisinfactagood idea,butforthepurposes of explaining a design document and how to use one, it serves thepurpose.

The idea concerns a boat racing game. Some number of boats begin at awharfandhavetoroundacircuitthreetimesandpassafinishline.Therewillbenatural hazards—fishing boats, ducks and geese,whales,wind,waves, and soon.Theywillhavetoperformonepitstop,sofuelwillbeaconsideration.Therewillbeopponentswhichwillbecontrolledby thegameAIsystem,andwhichwillbedesignedtobeentertaining.

That’sjustanideathough.Toturnthisintoadesign,onemustdefinewhattheobjectsare,whatthemechanicsare,whattheeventsare,whatthegoalsare,howtheeventsmove theplayer toward theend(goal),andwhat theartassetsandsoundassetsare,aswellascompleteadetailedassessmentofevery-thingthat can happen in the game. A game cannot crash. An accounting program

Page 61: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

shouldn’t,butsometimesdoes,andwhilethereareconsequences,thecrashingofanaccountingprogramisnotseenassomuchofanissueasisthecrashingofagame.Games,exceptonlineones,donotusuallyhaveupdatesorbugfixes,sotheinteractionsandeventhandlingmustbecarefullydefined.

Thegamedesigndocument(GDD)fortheJetBoatgamewillbedevelopedfurther in each chapter. It is typical for the GDD to evolve as the gamedevelopmentprogresses,but it isessential that there isonlyoneversionof thegame that iscurrentandsharedbyallof thedevelopersatanygivenmoment,andthateveryoneknowswhereitis.Aversioncontrolsystemcouldbeused,butthere are documentmanagement and share systems such asGoogleDocs thatworkverywellforthispurpose.

The following document is incomplete and will be filled in as more isunderstood about aspects of the game such as pathfinding, collision detection,audio,andsoon.Itisclearfromthedocumentthatartisticassetsareakeypartofthegameandspecialisttalentisneededtodevelopacompellinggame.Inthefinaldocumentsomeimageswillbeincluded,aswellasfilenamesandlocationsforallassets.

C2H6OJetBoatRaceDesignDocument1.GameOverview

1.1 Concept–Thisgamewillinvolvetheplayerguidingajetboatthroughacourse down a river and around a lake and over a finish line, whileescapingtraps,avoidingobstacles,andpickingupboostsandfuel.

1.2 Genre–Thisisabasicracestylegame,2Dwithoverheadview.1.3 Audience–Anyage,butwithayoungerdemographic.1.4 Game Flow – After moving through the initial screens, the player is

signaled to begin the race. The game begins at a small dockwith threeotherboats,andinitiallyallmovedowntheriverandjockeyforposition.Alakeisenteredthathasfloatingpylonstoguidetheplayer,eachhavinganumber and a color. The number indicates the next pylon to pass insequence, and the color indicates what side of the pylon the boat mustpass;greenmeanspassontheright,redmeanspassontheleft.Thefirstboattopassthefinalpylonwinstherace.

1.5 VisualStyle–Theviewoftheplayingareaisfromabove,anditscrollstofollowtheplayer.Itisatypical2Dracegameinthataspect.Boatsare21stcenturyjetboats.

Page 62: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

2.GameplayandMechanics

2.1. Gameplay2.1.1. GameProgression–Thereisonelevel,andonegoal.2.1.2. Mission/ChallengeStructure–nospecificmissions.2.1.3. Objectives–Theoverallobjectiveistocrossthefinishlinebefore

anyoftheother(NPC)boats.Othergoalsinclude:- Topickupflagsalongtheroute- Tofueluptoavoidrunningoutoffuel- Tointerfere,ifpossible,withtheotherboats

2.1.4. PlayFlow–Thegameisfocusedonthehumanplayer.Otherboatswill attempt to interfere by bumping into the boat, droppingobstacles,andotherwisegettingintheway.Theplayermustmovethroughtheobstacles,passthemarkerscorrectly,andpassoverthefinishline.

2.2. Mechanics–

Theplayercancontroltheirboat,makingitaccelerateorturnleftorright.Hittinglandslowstheboat,whichwillbouncebackintothewater.Eachboatbeginstheracewithtwo(2)obstaclefloatsthatcanbedeployedin

thepathofanopponent.Whenstruckbyaboat,theboatslows50%.Eachboatbeginswithinsufficientfueltofinishtherace,soeachboatmust

stoptorefuel(pitstop)atleastonce.Therearetwolocationsonthelakewherethatcanbeaccomplished,simplybystoppingthere.

Theracebeginsonariver,entersalakewherethreelapsmustbemade,andendsonanotherriverwherethefinishlineis.

Smallflagsarefloatingneartheboat’spathandcanbepickedupbydrivingoverthem.Theyareworthrandomnumbersofpoints,eachpointrepresentinganamountoftimethatwillberemovedfromtheplayer’sfinishingtime.

Aclockkeepstrackofthetimethattheboathasspentontheracesofar.Theboatwiththesmallesttimeatthefinishwins,irrespectiveoftheirphysicalplaceintherace.

2.2.1. Physics–Thegametakesplaceonthesurfaceofthewater,whichis ahigh friction surface.Accelerationcanbequick,but slackingoff on the accelerator will slow the boat quickly. Turning tooquicklycanfliptheboatover,slowingtheplayer’sprogress.

2.2.2. Movementinthegame–The“q”keyacceleratestheboatforward,

Page 63: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

andreleasing itwillslowtheboat.Turnsareperformedusing the“a”key(left)andthe“d”key(right).

2.2.3. Objects – Running over objects enables their action on the boat(Collision).

2.2.4. Conflict–Otherboatscanrelease theirobstacles to interferewiththe player’s boat and may collide with it either on purpose orthroughalcohol-fueledaccidents.Thisslowsbothboats.

2.2.5. Economy–Thereisnoin-gameeconomy.2.2.6. ScreenFlow–Agraphicaldescriptionofhoweachscreenisrelated

toeveryotherandadescriptionofthepurposeofeachscreen.Therewillbeanopeningscreen(loadgameassets)Startscreen(play,exit,options,sound)Optionsscreen–selectboats,soundon/offPlayscreenEnd–win/lose,savescore,replay/exit

2.3. GameOptions–Theplayercanselectaboatthathasspecificpropertiesoftopspeed,acceleration,andmaneuverabilityfromasmalllist.

2.4. ReplayingandSaving–Thegamecan’tbesaved,butitcanbereplayed,andalistofplayersandscorescanbemaintained.

3.Story,Setting,andCharacter3.1. StoryandNarrative–There isnonarrativehere, justa race.Cut scenes

beforeandafter theracearerealboatracingscenesfromactual jetboatraces.

3.2. GameWorld3.2.1. General look and feel ofworld –A2Dplane showingwater and

landareas,flags,boats,refuelingarea,andobstacles.3.2.2. Thestartarea isadockalonga river.When thegamebegins, the

playerandNPCsacceleratetotheleftalongtheriver.3.2.3. The river opens into a lake that has refueling areas and colored

pylons.Thefirstpylonisred,meaningitistobepassedontheleftsideOFTHEBOAT.Thesecondpylonistotheleft,meaningthatboatswillcirclethelakeinaclockwisedirection.

3.2.4. There are islands in the lake, spectators, other boats, and tworefuelingareas,oneoneachsideofthelake.

3.2.5. There is another river entering the lakewhich contains the finishline,and it is tobeusedafter threecircuitsof the lakehavebeenperformed.

Page 64: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

3.3. Characters.NPCboatshavevariouscolorsandshapes.

4.Levels–

4.1. Levels.Onlytheone4.2. TutorialLevel–Later

5.Interface

5.1. WindowsandTransitions5.2. VisualAssist.HUD(Head’sUpDisplay)5.3. Cameraisabovetheplayer’sboat.

HUDis in the lower rightcorner,andshowsawiderareawithotherboats,pylons,andscenefeatures.

5.4. ControlSystem–Keyboard5.5. Audio

MusicAtthebeginningofthegameandtheend.soundeffects–

soundsofimpactsotherboatsterrainpylonsflags

watersoundsStartinggunEndindicator

ambianceenginenoisesvoiceofanannouncer(script)crowd

5.6. HelpSystem–asinglehelpscreencanbeopenedatanytimebytypingthe“h”key.Contentslater.

Page 65: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

6.ArtificialIntelligence

6.1. PlayerandCollisionDetection–Later6.2. Pathfinding–later6.3. OpponentAI–later6.4. FriendlyAI–none

7.Technical

7.1. TargetHardware–Anydesktop7.2. Development hardware and software, including Game Engine – Python

andPygame7.3. Networkrequirements–Later

8.GameArt–Keyassets,howtheyarebeingdeveloped.Intendedstyle.

Terrain4playerboatsNPCboatsPylonsFlagsObstaclesWatertrailanimations

EXERCISES

Thefollowingproblemswillexerciseyourknowledgeofthematerialinthischapter, and they sometimes require thatyoudo some researchbeforeyouareabletocompletethem.

1. Give your own definition of fun. Don’t think too long about it—try to beinstinctive. Can fun be measured, using your definition? Is it possible topredicthowmuch fun somethingwill be, or is it onlyobservable after thefact?Howisengagementdifferentfromfun?

2. Explain the conflict/challenge in Tetris, Mortal Kombat, Frogger, andDefender.Howisitmaintained?

3. Whatisthe(a)goalofthegameMarioKart?PacMan?TheSims?

Page 66: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

4. Describe, as concisely as possible, the major mechanic of Angry Birds,Portal,andSpaceInvaders.

5. Examinetenormoreweb-basedgamesandlistthecontrols(buttons,sliders)found on the open (splash) screen and on any options screen. List this inorderoffrequency,mostcommonfirst.

6. Manygamesarezero-sumgames,inwhichthereisawinandalossforeachchoiceandsituation.Eachgain foroneplayer isoffsetbyacorrespondinglossforanother.Givethreeexamplesofazero-sumgame,andexplainwhytheyfallintothiscategory.

7. Sketch a game loop forTetris, stating in simpleEnglish at each stepwhatneedstobedoneforthisgameinparticular.

8. WriteashortGDDforanycomputergameyouhaveplayed,butdonotnamethegame.Givethistoanotherperson;cantheyfigureoutwhatthegameis?

REFERENCES

1. Pippin Barr. Games Blog. (n.d.).http://www.pippinbarr.com/games/pongs/Pongs.html

2. Aki Järvinen. (2008).Gameswithout Frontiers: Theories andMethods forGameStudiesandDesign.Tampere,Finland:TampereUniversityPress.

3. Mike McShaffry and David Graham. (2013). Game Coding Complete.Boston,MA:CourseTechnology.

4. Katie Salen and Eric Zimmerman. (2004). Rules of Play: Game DesignFundamentals.Cambridge,MA:MITPress.

5. Daniel Sanchez-Crespo. (2004).Core Techniques and Algorithms inGameProgramming.Indianapolis,IN:NewRidersPublishing.

6. Thomas Schelling. (1980). The Strategy of Conflict, revised edition.Cambridge,MA:HarvardUniversityPress.

7. Brian Yap. (1999).Analytical Perspectives in Game Design: Architecture.http://numbat.sourceforge.net/numbbatV2/architecture.html.

Page 67: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER2

GRAPHICSANDIMAGESAsagameprogrammeroneofthefirstskillsrequiredistobeabletodisplay

renderings of the playing volume. This means that the volume itself and allobjectsmust be drawn in their correct locations, orientations, and sizes. Eachgameobjecthasadistinctsetofcolorsandtextures,andconsistsofacollectionofsimplergeometricshapes.Somearedrawnasthosebasicshapes,whileothersmaybepre-drawnimagesthatarepastedintoplace.Inanycase,thegamemustbeupdatedmanytimespersecond,meaning thateveryobjecthas tobedrawnthat often. A game programmer needs the software tools to accomplish thateffectively.

Graphicssoftwareisorganizedasasetoflevels,withhigherlevelsallowingthe most complex tasks to be performed and lower levels offering the mostdetailed modification. At the bottom layer of software are functions thatmanipulatepixels. At the next level are lines and curves; these are the basiccomponents of drawings and sketches. An artist with a pencil uses lines andcurvestorepresentscenes.Atthelevelabovelinesarefunctionsthatuselinestocreateotherobjects,suchasrectangles,circles,andellipses.Thesecanbe linedrawings or can be filled with colors. The next higher levels can be arguedabout, but text is probably in the next software layer and then shading andimagesfollowedby3Dobjects,which includesperspective transformationandtextures.

Python itself does not have graphics tools, but various modules that areassociatedwithPythondo.Thestandardgraphicaluserinterfacelibraryforusewith Python is tkinter. There aremany features of thismodule, including thecreationofwindows,drawing,userinterfacewidgetssuchasbuttons,andahostofotherfeatures.ItisfreeandisnormallyincludedinthePythondistribution.

AnotherlibrarythatallowsgraphicsprogrammingiscalledPygame,andthisis designed for building computer games using Python. Let’s look in detail atPygame, as it will allow us to draw pictures, manage interfaces, and doanimations.

Page 68: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

PYGAMEESSENTIALS

To start creating computer graphics, it is necessary to understand howPygamemanagesthescreenandotherresources.ThereisadistinctsetofstepsthatmustbefollowedinorderforeventhesimplestPygameprogramtowork.Afterthebasicstepsareaccomplished,wecandrawintoagraphicswindowandhaveitappearonthescreen.

Itwillbeassumed that thePygamemodulehasbeen installedcorrectlyonthecomputer.Forsomeinstructionondoing,thisseeAppendixA.

ThefirststepinusingPygameinaprogramistoimportthePygamemodule.Assumingthatithasbeeninstalledcorrectly,thisisamatterofbeginningwiththefollowingstatement:

importpygame

Next,therearevariablesthatneedtobeinitializedandstoragethathastobeallocated for Pygame towork.One example is that fontsmust be loaded andplacedintoadatastructure.Thisisdonewiththefollowingstatement:

pygame.init()

Nothingseemstohappen,butPygameisnowreadytowork.Next,wecreateadrawingstructurecalledasurface:

surf=pygame.display.set_mode((400,450))

Thevariablesurfwillnowcontainareferencetoasurfaceobject,andinthiscase itwill be thedisplaysurface, becauseweaccessed it through thedisplaypart of the Pygame object. The display surface is the place where things aredrawnifwewantthemtobevisibleonthescreen;thinkofitastheplayingarea.Thereareothersurfacesthatcanbedrawnonthatwillnotdisplaybydefault,soin general a surface in Pygame is a thing thatwe can draw into. Themethodset_mode takes a tuple as a parameter that gives the size of the surface. Thissurfacewillbe400pixelswideby450pixelshigh,anditwillappearbrieflyonthescreenandwillthenvanish.Whydoesitvanish?Becausetheprogramendsafterthelaststatement,takingthewindowwithit.

Howcanwekeep thedrawing areaon the screen?Don’t end theprogramuntil told!We could, as one example, read something from the keyboard andthenterminatetheprogram.Here’sthefirstfullPygameprogram,whichisnon-standardbutfunctional:

Page 69: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE2.1AnemptyPygamedrawingwindow.

importpygame

pygame.init()

surf=pygame.display.set_mode((400,400))

pygame.display.update()

input()

Thewindowwill stay on the screen until a character is typed in the inputregion (not the drawing window!), at which point the program continues toexecute and terminates, taking the window with it. This is not suitable forplayingagame,butitillustratesaproblem:we’llneedtoexecutethegameloopandacceptuserinputsomehowwhilekeepingthedrawingwindowopen.ThisissomethingPygamewasdesignedtodo.

SIMPLESTATICDRAWING

Everything drawn on the display surface has a color, and it is a tupleconsisting of the red, green, and blue component of the color. Thus, the tuple(255,255,255) would be the color white. (0,0,0 would be black.) To humans,colors have names. Here’s a list of some named colors and their RGBequivalents:

Color Red Green Blue Color Red Green BlueBlack 0 0 0 Olive 128 128 0White 255 255 255 Khaki 240 230 140

Page 70: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Red 255 0 0 Teal 0 128 128Green 0 255 0 Sienna 160 83 45Blue 0 0 255 Tan 210 180 140Yellow 255 255 0 Indigo 75 0 130Magenta 255 0 255 Orange 255 165 0

The background is black by default. Assuming that the display surface isnamed surf, then the background color can be changed by a call to the fillmethod,passingatuplespecifyingthecolor:

surf.fill((255,0,0))

Inthiscasethebackgroundcolorwillbered.PygamealsohasaColorclassthat has red, green, and blue components andmethods for converting to non-RGBcolorspecificationslikeHSV.After:

c=pygame.Color(255,0,0)

surf.fill(c)

thecolorstoredincwillberedaswellasthebackgroundcolor.

PixelLevelGraphicsTheonlypixel leveloperationdrawsapixelataspecified location;so, for

example,thecall:

surf.set_at((x,y),c)

will set thepixelatcoordinates (x,y) to thecolorc.Settingacollectionofpixelsthatareadjacenttoeachotherwillcreatealine.

Example:CreateaPageofNotePaperNotepaper has blue lines separatedby enough space towrite or print text

between them. Itoftenhasa redvertical line indicatingan indentation level,aplace tobeginwriting.Drawing this is amatterofdrawinga setof connectedbluepixelsinverticallyseparatedrowsandthenmakingaverticalcolumnofredpixels.Hereisonewaytocodethis:

importpygame

pygame.init()

Page 71: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

surf=pygame.display.set_mode((400,400))

c=pygame.Color(0,0,200)

surf.fill((255,255,255))

y=60#Heightatwhichtostart

forninrange(0,27):#Draw30horizontalbluelines

forxinrange(0,400):#Drawallpixelsinoneline

surf.set_at((x,y),c)#Drawabluepixel

y=y+20#Thenextlineis20pixelsdown

c=(200,0,0)#Pixelcolorred

foryinrange(0,400):#Drawconnectedverticalpixels

surf.set_at((25,y),c)#toformthemarginline

pygame.display.update()

input()

FIGURE2.2Agraphicofasheetoflinedpaper.

Page 72: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE2.3Acolorgradientdrawnaspixels.

Theoutputof thisprogramisshowninFigure2.2.Whenpixelsaredrawnimmediatelynexttoeachothertheyappeartobeconnected,andsointhiscasetheyformhorizontalandverticallines.Thisisnoteasytodoforarbitrarylines;itisnotobviousexactlywhichpixelstofillforalinebetween,say,(10,20)and(99,17).That’swhythelinedrawingfunctionsexist.Notethatwe’restillusingacalltoinput()topostponetheendoftheprogram.Thiswillcontinueforafewexamples,andthenthestandardmethodwillbeexplained.

Example:CreatingaColorGradientWhencreatingavisualonacomputer,thefirststepistohaveaclearpicture

ofwhatitwilllooklike.Forthisexample,imaginetheskyonaclearday.Thehorizonshowsalighterbluethantheskydirectlyabove,andthecolorchangescontinuously all theway fromhorizon to zenith. If a realistic sky backgroundwereneeded, thenitwouldbenecessarytodrawthisusingthetoolsavailable.Whatwouldthemethodbe?

First,decideonwhatthecolorisatthehorizon(y=ymax)andatthehighestpointinthescene(y=ymin).Nowask:“howmanypixelsbetweenthosepoints?”The change in pixel color will be the color difference from ymax to ymindivided by the number of pixels. Now simply draw rows of pixels beginningwiththehorizonandmoveuptheimage(i.e.,decreasingYvalue),changingthecolorbythisamounteachtime.

As an implementation, assume that the color at the horizonwill be blue=

Page 73: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

(40,40,255)andthetopoftheimagewillbe(40,40,128),adarkerblue.Theheightoftheimagewillbe400pixels;thechangeinblueoverthatrangeis127units.Thus,thecolorchangeovereachpixelisgoingtobe255.0/400.Acolorcan’tchangeafractionalamount,ofcourse,butwhatthismeansisthatthebluevaluewilldecreasebyapproximately1unitwitheveryincreaseofacoupleofpixels in height.Do not forget that the horizon is at the bottomof the image,which has the greatest Y coordinate value, so that an increase in Y means adecreaseinheightandviceversa.

Theexampleprogramthatimplementsthisis:

importpygame

pygame.init()

surf=pygame.display.set_mode((400,400))

surf.fill((255,255,255))

blue=0

delta=255.0/400

foryinrange(0,400):

yy=400-y

c=(40,40,blue)

forxinrange(0,400):

surf.set_at((x,y),c)

blue=blue+delta

pygame.display.update()

input()

Figure2.3showswhatthegradientimagelookslikeasagreylevelimage.

LinesandCurvesStraightlinesandcurvesaremorecomplexobjectsthanpixels,consistingof

many pixels in an organized arrangement.A line is actually drawn by settingpixelsthough.Thefactthata line() functionexistsmeansthat theprogrammerdoesnothavetofigureoutwhatpixelstodrawandcanfocusonthehigherlevelconstruct,thelineorcurve.

A line isdrawnbyspecifying theendpointsof the line.UsingPygame thecallis:

pygame.draw.line(surf,col,(x0,y0),(x1,y1))

whereoneendofthelineisat(x0,y0)andtheotherisat(x1,y1).Thecolorof the line is specified by the second parameter col. If any part of the lineextendspasttheboundaryofthewindowthat’sOK;thelinewillbeclippedtofit.

Page 74: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Example:NotePaperAgainThe example of drawing a piece of note paper can be done using lines

insteadofpixels,anditwillbealotfaster.Drawacollectionofhorizontallines(i.e.,thathavethesameYcoordinateattheendpoints)separatedby20pixels,asbefore having a blue color. Then draw a vertical red line for themargin. Theprogramisavariationonthepreviousversion:

importpygame

pygame.init()

y=60#Heightatwhichtostart

width=400

height=400

surf=pygame.display.set_mode((width,height),

pygame.SRCALPHA)

surf.fill((255,255,255))

y=60#Heightatwhichtostart

forninrange(0,27):#Draw30horizontalbluelines

pygame.draw.line(surf,(0,0,200),(0,y),(width,y))

y=y+20#Thenextlineis20pixelsdown

c=(200,0,0)#Pixelcolorred

pygame.draw.line(surf,c,(25,0),(25,height))

pygame.display.update()

input()

Theoutput from thisprogram is thesameas that for theversion thatdrewpixels,whichisshowninFigure2.2.

Acurveistrickierthanaline,inthatitishardertospecify.ThemethodusedinPygameiscommon:acurve(arc)isdefinedasaportionofanellipsefromastartingangleforaspecifiednumberofdegrees,asreferencedfromthecenteroftheellipse.Here’sacalltoarc:

pygame.draw.arc(surf,c,box,start_angle,end_angle)

The parameter surf is the surface to draw on, c is the color, box is anenclosing bounding box as a tuple (upper left x, upper left Y, width, height),start_angleisananglebetween0and2πradians,andstop_angleisanangleinthe same range. The angle 0 is to the right, 90 degrees is up, 180 degrees (πradians) is left, and 270 degrees is down. The angle specifies the part of theellipsetodraw.Figure2.4showssomeexamplecallstocurveandtheirresults.Thecurvesaredrawncounterclockwise.Thevalueconv isπ/180andconvertsanangleindegreesintoradianswhenmultiplied.

Page 75: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE2.4Examplesofthecurvemethod

Beforeproceeding,wehaveafewexamplesofdrawinginPygamenow,andsome generalizations can be made about the structure of the module. ThevariablepygamehereisaninstanceofaclassthatcontainsmostofthecodethatimplementsPygame.Withinthatclasscanbeseensomemethodsandotherclassinstances,asfollows:

init() InitializePygameSRCALPHA Aconstant,indicatingapixelformatwith

analphachannel(opacity)color Aclassrepresentingcolordisplay avariable,aclassreferenceset_mode() Modifydisplaysize;ReturnsTHEdisplay

referenceupdate() Drawthisdisplaytothescreensurface Aclassrepresentingaplaceonecandrawfill() Setthecolorforfillingpolygonsonthis

surfaceset_at() Setapixelspecifiedby(x,y)tothefill

color

Page 76: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

draw Amodulefordrawingsimpleobjectsline() Drawalinearc() Drawacurve

Online documentation for Pygame is extensive, and a quick search shouldlocate anything that the system can provide. The key web site right now ishttps://www.pygame.org.Lookingupthedrawmoduleonthatsitewefind:

pygame.draw.rect — drawarectangleshape

pygame.draw.polygon — drawashapewithanynumberofsides

pygame.draw.circle — drawacirclearoundapoint

pygame.draw.ellipse — drawaroundshapeinsidearectangle

pygame.draw.arc — drawapartialsectionofanellipse

pygame.draw.line — drawastraightlinesegment

pygame.draw.lines — drawmultiplecontiguouslinesegments

pygame.draw.aaline — drawfineantialiasedlines

pygame.draw.aalines — drawaconnectedsequenceofantialiasedlines

That’severythingthatdrawcando.

PolygonsFor the purposes of discussion, a polygon will include all closed regions,

including ellipses and circles.A rectangle is drawn using the rectmethod, as

Page 77: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

showninFigure2.5a.

pygame.draw.rect(surf,((0,200,50),(100,100,200,300))

Thesurfandcolorparametersareasbefore,andtheboxisspecifiedastheupper left coordinates, the width, and the height. By default, the rectangle isfilledwith the specified color. An additional final argument specifies the linethickness with which to draw the rectangle, and if this is specified then therectangleisnotfilledwithcolor(Figure2.5b):

pygame.draw.rect(surf,(0,200,50),(100,100,200,100),1)

Theellipsemethodtakesthesameparametersasdoesrect,anditdrawsanellipsewithintherectangledefinedbythethirdparameter(Figure2.5c).

pygame.draw.rect(surf,(230,230,0),(100,100,200,100),1)

pygame.draw.ellipse(surf,(0,200,50),(100,100,200,100),1)

Acircle is an ellipse drawn in a square. Thismakes the center and radiusratherimplicit.Thereisacirclemethodalso(Figure2.5d):

pygame.draw.rect(surf,(230,230,0),(50,50,100,100),1)

pygame.draw.circle(surf,(0,200,50),(100,100),50)

Thethirdparametertocircleisatupledefiningthecenter,andthefourthistheradius.Afifthwouldbethelinethickness,andfillingwouldturnoff.Inthecasehereofacircleat(100,100)andradiusof50,theenclosingsquarewouldbefrom(100-50,100-50),whichis(50,50),for(100,100)pixels.

FIGURE2.5(a)AFilledRectangle;(b)UnfilledRectangle;(c)AnEllipse;(d)ACircle,Filled

BlittingToblitistocombineseveralgraphicsorbitmapsintoasingleone.Itisoften

accomplishedusingaBooleanfunction,andoften isveryfastdue tohardwareassistance. Pygame has one special Surface that is the display Surface, but itallows us to draw on other surfaces too. To display what is drawn on thesesurfaces,wewouldblitthemtothedisplaySurface.

Blitting has consequences and requires specifications that are not usually

Page 78: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

appreciatedby the definition.Consider the creationof twoSurfaces named s1ands2inadditiontothedisplaysurface,anddrawintoeachofthose:

s1=pygame.Surface((400,400))#NewSurface

pygame.draw.rect(s1,(230,230,0),(50,50,100,100),1)

s2=pygame.Surface((400,400))#NewSurface

pygame.draw.circle(s2,(0,200,50),(100,100),50)

The Surface s1 contains a rectangle, and the Surface s2 contains a circle.Neitherappearson thedisplaySurface,whichalreadyexistsdue toapreviouscall and is named surf. A blit is a copy from one Surface to another. Somequestionsare:

-WhichpartoftheSurfacebeingblittediscopied?-Where(coordinates)isthesurfacebeingblittedto?-Whathappenstothepixelsthatalreadyexistintheregionbeingblittedto?

The method that copies (blits) one surface to another is blit, the simplestformofwhichis:

surf.blit(s1,(0,0))

ThiscopiesallofSurfaces1tosurfsothattheupperleftofs1isat(0,0)ofsurf.We can copy s1 to any pixel coordinate in surf. To draw a circle and arectangle indifferentSurfacesand thenblit themto thedisplaySurfacewouldinvolvecreatingthesurfaces,drawinginthem,andblittingthem:

s1=pygame.Surface((200,200))#S1is200x200

s1.fill((255,255,255))#Whitebackground

pygame.draw.rect(s1,(230,230,0),(50,50,100,100),1)

s2=pygame.Surface((200,200))#s2isalso200x200pixels

s2.fill((255,255,255))#Whitebackgroundtoo

pygame.draw.circle(s2,(0,200,50),(60,60),50)

#Blitrectangleto(0,0)andcircleto(100,100)

surf.blit(s1,(0,0))#s1hasarectangle:blit

surf.blit(s2,(100,100))#s2hasacircle:blitpygame.display.

update()

Heres1isblittedbefores2(i.e.,isdrawnfirst),andthereisoverlapbetweenthedrawnregions.Thus,theonedrawnlast(s2)appearstobedrawnovers1.Ifwethinkintermsoflayers,thelastsurfacedrawnisthetoplayerandisvisible.Layersbeneathmaybepartlyorcompletelycoveredbylayersabove.ASurfaceisrectangular,sonoticethatthebackgroundsurroundingthecircleisalsodrawn

Page 79: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

overthesquarebelow.Figure2.6showstheresult.Theblitfunctionhasotherparametersthatwe’llgetintoshortly.

DrawingTextDrawingtextisaccomplishedbyloadingafontandthendrawing(rendering)

atextstringtoasurfaceusingthatfontasaguide.AninstanceoftheFontclass,andthereisadefaultforthat,canrendertextontoasurface.Thatsurfaceisthenblitted to the target surface, possibly the display. A simple example involvesplacingthetext“Hellothere”atlocation(100,100):

font=pygame.font.Font(None,36)

text=font.render(“HelloThere”,1,(10,10,10))

surf.blit(text,(100,100))

FIGURE2.6(a)Afilledrectangle;(b)Unfilledrectangle;(c)Anellipse;(d)Acircle,filled.

The method pygame.font.Font selects a font to be used and returns aninstance.Afonthasaname,inthiscaseNone,indicatingthatweshouldusethedefault,andasize,inthiscase36.Eachcomputersystemhasadifferentsetoffontsavailable,sowe’lluse thedefault.Next, the fontclasscandraw(render)thetextontoasurface.Thecall:

text=font.render(“HelloThere”,1,(0,0,255))

Page 80: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

renders the text “Hello there” in the color (0,0,255), which is blue. Thesecondparameter1meanstoantialias,whichwillyieldnicesmoothcharacters.Finally:

surf.blit(text,(100,100))

will blit the text to the display Surface surf at location (100,100). Thecoordinates(100,100)arethoseoftheupperleftofthetextSurface,whichwillbearectanglelargeenoughtoenclosethestring.

AproblemisthatthistextSurfacewillwriteoveranythingunderneathasarectangulararea.Thiscanbefixedbyusingatransparentbackground.Thekeythingstoknowaboutdrawingtextarethatfont.renderdrawsatextstringintoaSurface and returns that Surface, which then must be blitted to the place itbelongs.

TransparentColorsWhenonepixelisdrawnovertopof(i.e.,at thesamelocationas)another,

the one drawnmost recentlywill be visible. Thismay not always bewhat isneeded.Background pixels of text images being blitted should be invisible sothatthebackgroundcanbeseenwiththetextontop.

Transparency is a value that can be numerical. Let’s say that a value of 0means that the drawn pixel is invisible and a value of 255 means that it isopaque. Values in between have degrees of transparency. Then we want thebackgroundofatextboxtohavethevalue0forthisparameter,andthetexttohaveavalueof255.Lookingat thisvalueithasthesamepropertiesasdoesacolor component, and so it is generally implemented as a fourth componentcalledalpha.AcolorcanbespecifiedasRGBA,whichmeansfourcomponents:red,green,blue,andalpha.

Not all Surface objects can implement transparency. They must have aproperty called 32-bit color and have the SCRALPHA property. Creating aSurfacelikethisisdoneasfollows:

surf=pygame.display.set_mode((w,h),pygame.SRCALPHA,32)

where the thirdparametermeans that theSurfacecansupport transparencyandthefinalonemeansthatithasthirty-twobitcolors:fourvaluesofeightbitseach.

ThepreviousexamplehavingarectangleandacircledrawnandthenblittedtothedisplaySurfacecannowbeimplementedusingtransparency:

Page 81: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

importpygame

pygame.init()

surf=pygame.display.set_mode((400,400))

s1=pygame.Surface((200,200),pygame.SRCALPHA,32)

s1.fill((255,255,255,0))

pygame.draw.rect(s1,(230,230,0),(50,50,100,100),1)

s2=pygame.Surface((200,200),pygame.SRCALPHA,32)

s2.fill((255,255,255,0))

pygame.draw.circle(s2,(0,200,50),(60,60),50)

surf.blit(s1,(0,0))

surf.blit(s2,(100,100))

pygame.display.update()

input()

The fill color valueof (255,255,255,0) yields a fully transparent color thatwillcomprise thebackgroundof thecircleand the rectangleSurface,allowingthebackgroundtoshowthrough.Noticethatthebackgroundcolorisblack;thisisthedefaultonthedisplaysurface.Tochangeit towhite,asanexample,callsurf.fill:

surf.fill((255,255,255))

FIGURE2.7Exampleoftransparentcolors.

ImagesUnlikethegraphicalcomponentsdisplayedsofar,animageisfundamentally

Page 82: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

a collection of pixels. A camera captures an image and stores it digitally aspixels,andso itwasneveranythingelse.Displayingan imagemeansdrawingeach pixel in the appropriate color, as captured.Pygame can load and displayimagesinfilesofvariousformats:JPEG,GIF,BMP,andPNG.

UnlikelanguagessuchasJava,Pythonhasnoimageclass.Animageisreadfromafileusingthefunctionpygame.image.loadandisreturnedasaSurface.ThismeansthatitcanbedisplayedimmediatelyusingablitandthatindividualpixelscanbeaccessedusingtheSurfacemethodget_at().

Thefile“charlie.gif”isaphotoofCheckpointCharlieinBerlin(Figure2.8).ItcouldbereadintoaPythonprogramwiththecall:

im=pygame.image.load(“charlie.gif”)

Thevariableimnowholdstheimage,andcanbedisplayedusing:

surf.blit(im,(0,0))

While the details are not completely relevant, it is good to know thatim.get_width()and im.get_height()give thewidthandheightof the image inpixels.

ThecompletePythonprogram(usingPygame)thatcanloadanddisplaytheimageisthus:

importpygame

pygame.init()

im=pygame.image.load(“charlie.gif”)

width=im.get_width()

height=im.get_height()

surf=pygame.display.set_mode((width,height),

pygame.SRCALPHA)

surf.fill((255,255,255))

surf.blit(im,(0,0))

pygame.display.update()

input()

Thisdisplaystheimageinawindowthatisexactlythecorrectsize.ThemodulePygame.imagehasfunctionsforloadingandsavingimages,but

noneformanipulatingthem.Theotherimportantfunctionisonethatsavesdataintoanimagefile:

Pygame.image.save(Surface,filename)

Page 83: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE2.8CheckpointCharlieimagedisplayedinaPygamewindow.

PixelsAnimageisjustaSurfaceafterithasbeenreadfromafile.Individualpixels

canbeaccessedusing themethodget_atpassing thexandy coordinates.Thecode

pix=im.get_at((i,j))#Parameterisatuple

returnsthecolorofthepixelsat(i,j),whichisatuplecontainingred,green,blue,andalphacomponents.

Changingthevalueofthepixelatlocation(x,y)isaccomplishedbycallingim.set_at()

im.set_at((x,y),color)

whereagain,colorisatuple.Pygamedoesnothavefacilitiesformodifyingimagesdirectly,butrequires

theybeplacedintoaSurfacefirst.NowthepixelscanbeaccessedindividuallythroughthatSurface.

Example:NegativeImage

Page 84: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Aphotographic negative is not something that is encounteredmuch in theageofdigitalphotography.Anegativeistheintensityinverseoftheimage:blackpixelsarewhiteinthenegative,andwhitepixelsareblack.Inbetweenpixelsarereversed in value, usually on a scale of 0 to 255. So, if a specific pixel has avaluex,thenitsvalueinthenegativeimagewillbe255-x.

Using the Checkpoint Charlie image again, let’s create a negative imageusingthispixelvaluerange.First,wehavetoconvertthecolorpixelsintogreyvalues.AneasywaytodothisistoaveragetheR,G,andBvalues.Forapixelvaluepix:

grey=(pix[0]+pix[1]+pix[2])/3

Nowthisvalueissubtractedfrom255andisreplacedintotheimage:

grey=255–grey

im.set_at(x,y,grey)

Thewholeprogramis:

importpygame

pygame.init()

im=pygame.image.load(“charlie.gif”)

width=im.get_width()

height=im.get_height()

foriinrange(0,width):

forjinrange(0,height):

pix=im.get_at((i,j))

grey=(pix[0]+pix[1]+pix[2])/3

grey=255-grey

im.set_at((i,j),(grey,grey,grey))

surf=pygame.display.set_mode((width,height),pygame.SRCALPHA)

surf.blit(im,(0,0))

pygame.display.update()

input()

Thecolor(grey,grey,grey)isagreypixel,thesamecolorintensityforeachofred,green,andblue.Theforloopisusedtoexamineeverypixelintheimage.

Page 85: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE2.9CheckpointCharlieimage:(a)grey;(b)negative(greysreversed).

ImageTransformationsAnimageisreadintoaSurfacepriortodisplay,butitmaynotbethecorrect

sizeforthedisplaywindow.It’spossiblethatthedisplaywindowwillbeusedtodisplaymanyimagesofvarioussizesconsecutively,ofdisplaythumbnailsofacollection.Itwillbenecessarytoresizeimagesfromtimetotime.Pygamehasamodulenamedtransformthatcandothisandmore.

Toresizeanimagenamedim,acalltoscalewilldothejob:

im=pygame.transform.scale(im,(newx,newy))

wherenewxisthenewwidththatwewanttheimagetohaveandnewyisthenewheight.Tocreateanewimagethatis1/4theareaoftheoldone,reducethewidthandheightbyafactorof2:

im=pygame.transform.scale(im,(im.get_width()//2,im.get_height()//2))

Imageshaveanaspectratio, the ratioof the image’swidth to itsheight. Ifthisischangedthentheimagewilllookdifferent,perhapsstretchedorsquashed.When scalingan image, care shouldbe taken to ensure that the aspect ratioAstaysthesame.AneasywaytodothisistosetonedimensiontoaneededvalueandthencomputetheothersoAisnotmodified.Ifyouwantthewidthtobe100pixels,thensettheheightto100/A.Ifyouwanttheheighttobe100pixels,thensetthewidthtoA*100.

Usingscale,onecanmaketheimageeitherlargerorsmaller.

RotationAn image in a Surface can also be rotated using the transform module.

Page 86: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

pygame.transform.rotate (surf, angle)will perform a counterclockwise rotationoftheimageintheSurfacesurfbythespecifiedangle.Angleisindegreesandisarealnumber.Rotatinganimageimby30degreeswouldbecodedas:

s=pygame.transform.rotate(im,30)

ThereturnedimageswillhavetherotatedimagecenteredinanewSurfacelarge enough to contain it. A rectangle that is rotated will require a largerboundingboxtoholdit,soswillinevitablybelargerthanim(Figure2.10b).

Rotating an image requires that it be completely resampled. Few if anypixelswillhavethesamevalues.Animageisseenasa2Drectangulargrid,andwhen rotated itbecomesanewgridwith thenewpixels interpolated from theneighborsof theold image.What thismeans is thatan imageshouldneverberotatedmultipletimes.Ifso,eachimagewillbealittlemoredistortedthanthepreviousoneuntiltheresultholdsnorelationtotheoriginal.

Omitting some of the initial setup code, here’s a program that rotates animageby2degreestentimes,andthenback:

surf=pygame.display.set_mode((width,height),pygame.SRCALPHA)

im=pygame.transform.scale(im,(width//2,height//2))

foriinrange(0,10):

im=pygame.transform.rotate(im,2)

foriinrange(0,10):

im=pygame.transform.rotate(im,-2)

surf.blit(im,(0,0))

pygame.display.update()

TheresultinFigure2.10aisquitedistorted.Thecorrectwaytodomultiplerotationsistorotatetheoriginalimagebyalargerangleeachtime:

foriinrange(0,10):

s=pygame.transform.rotate(im,2*i)

FIGURE2.10CheckpointCharlieimage:(a)aftermultiplerotations;(b)afterone30-degree

Page 87: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

rotation.

Because a game often requires that sprites, represented as small rasterimages, be rotated, we need to understand the rotation method pretty well.Consider a small image of a boat, which will used as a sprite in the boatracegame. As visualized in Figure 2.11, the boat image initially points to theright,whichisthe0degreeorientation.Theboatalwaysmovesinthedirectionitisfacing,soifitmakesachangeindirection,thespritewillhavetoberotatedtofaceinthatdirection.

Therotatemethodwillrotatetheimageaboutitscenter.Thisoftenmakesthebounding box larger at first, and so the point that is the center of the imagechanges.Iftheimageistoberotatedmanytimes,thisbecomesobvious.Figure2.11wascreatedusingthecode:

boatr=pygame.transform.rotate(boat,angle)

display.blit(boatr,(250,200))

where the image of the boat is in a Surface named boat. This image isrotatedbythespecifiedangleandisreturnedasanewSurfaceboatr,which isthenblittedtothecenterofthescreen.Inordertohavethisrotationappeartobeaboutthecenteroftheboat,theimagemustbetranslatedtotheorigin.By“theimage”wemeantherotatedboatimage,whichchangesinsize.

boatr=pygame.transform.rotate(boat,angle)

sx=boatr.get_width()

sy=boatr.get_height()

display.blit(boatr,(250-sx/2,200-sy/2))

Thevaluesof sxandsy reflect the sizeof the rotated image,andso (sx/2,sy/2)wouldbethecenterofthatimage.Thisplacesthecenteroftherotatedboatimageatthecenterofthedisplay.Itcould,ofcourse,beplacedanywhere.

FIGURE2.11Rotationofaboatsprite.Theboundingboxandaxishavebeenadded.

PIXELSANDCOLOR

Page 88: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Colors are important in graphics, of course, because lines, shapes, andregionswillbedrawnindifferentcolors.Onacomputerscreenandinmemory,graphics are drawn as individual pixels, even if we don’t specify individualpixelsdirectly.Weknowthatapixelisacolororintensityvaluethatismeasuredordrawnataparticularlocationinanimage.Thekeytorepresentingapixelisto represent the color, and coloron a computer is usually specifiedby its red,green, and blue components (RGB). The choice of how to implement a pixelwouldseemtobemadeforus:itwillbeacollectionofthreevalues,oneholdingthe amount of red at that location, one holding the amount of green, and oneholdingtheamountofblue.

The Pygame color class represents colors as described thus far, and so apixelwouldbeofthattype.Avariableoftypecolorhasared,green,andbluecomponent, each of which is an unsigned integer. Each component, red forinstance,canhaveavaluebetween0and255.Avalueof0meansthatnoredispresentinthecolor,andavalueof255representsthemostredthatispossible(saturated).

Thecolor type inPygame is really justa tuplewith three (or four)values.Settingacolorvalueiseasy:

c=pygame.Color(128,90,20)

causesthecolorinctobeamediumbrown.Itcannowbeusedtosetcolorvalues,suchas:

surf.fill(c)

Theredcomponentofccanbeaccessedusingeitherc[0],whichisthefirstcomponentofc,orc.r.Thelatterispreferred,anditcanbeusedtomodifythecolorcomponent.Thecode:

c.r=255

setstheredcomponentofctothelargestpossiblevalue.Similarly,forgreenandblue,thecomponentsc.gandc.bwouldbeused.

Inadditiontothered,green,andbluecomponentsofapixel,thereisafourthpropertythatisofinterest.It’scalledalpha,anditreferstothedegreetowhichthepixelisopaqueortransparent.Apixelthatiscompletelytransparentwouldbeeffectivelyinvisible,sinceanythingdrawnbefore(i.e.,underneath)itwouldshowthrough.Conversely,apixelthatisopaquewouldcoveranythingbeneathit.Theuseofanalphavaluetocontrolthedegreeoftransparencyallowsobjectsunderneath any pixel to be visible to a greater or lesser degree. This usually

Page 89: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

appearsasacolorchangeinoverlapareas.It is important to remember that an alpha of 0 means that the pixel is

completely transparent.Analphavalueof255means that thepixel isopaque.This is the opposite of what one would expect if alpha is the degree oftransparency, since 0 transparency would seem to mean it is not transparent.Figure2.12showstheeffectofchangingthealphavalue.Thegreen(rightmost)circleineachoverlappingpairhasaspecifiedalphavalueof(lefttoright)255,200,128,and96.Notethatthecoloroftheothercircleshowsthroughmoreandmoreasthealphaofthegreencirclegetssmaller.

AlphaisamoredifficultaspectofcolortouseinPygamethaninsomeotherlanguagesandgraphicssystems.ThestandarddisplaySurface inPygamedoesnot display the alpha color channel, and so trying to draw transparent colorsdirectlywillfail.ASurfacecanbecreatedthatpermitstransparentcolors,andthiscouldbeblittedtothedisplaysurface.

Consider the program that created Figure 2.12. The red circles are allopaque, having an alpha of 255, and can be drawn directly on to the displaysurface. So can the first circle. The second circle has an alpha of 200.Whatneeds to be done is to create a new Surface having the property that it candisplayalpha.Itneedstobelargeenoughtoholdthecircleaswell.Thecodeis:

surf=pygame.Surface((60,60),flags=pygame.SRCALPHA)

The flag SRCALPHA indicates that this new surface must deal correctlywith alpha values. Next, draw the circle in this Surface, specifying the alphavalueasthefourthcomponentinthecolor:

pygame.draw.circle(surf,(0,255,0,128),(30,30),30)

Inthiscasethealphais128.NoticethattheSurfaceisjustlargeenoughtoholdthecircle,andthatthecircleisdrawninthecenteroftheSurface.ThefinalstepistoblitthisSurfacetothedisplay:

display.blit(surf,(250,40))

FIGURE2.12Theeffectofthealphavalueonpixelcolor.

Thelocationtowhichthissurfaceisblitteddictateswhereinthedisplaythecirclewillappear,sosomeplanningisneeded.Drawingthesituationusingsome

Page 90: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

graphpaperisalwaysausefulmeasure.AnewSurfaceshouldbecreatedeachtime;thatis,foreachcircle.Thecode

thatcreatesFigure2.12is:

importpygame

pygame.init()

display=pygame.display.set_mode((500,150),pygame.SRCALPHA,32)

display.fill((255,255,255))

pygame.draw.circle(display,(255,0,0,255),(50,50),30)

pygame.draw.circle(display,(0,255,0,255),(75,75),30)

surf=pygame.Surface((60,60),flags=pygame.SRCALPHA)

pygame.draw.circle(display,(255,0,0),(150,50),30)

pygame.draw.circle(surf,(0,255,0,200),(30,30),30)

display.blit(surf,(150,40))

surf=pygame.Surface((60,60),flags=pygame.SRCALPHA)

pygame.draw.circle(display,(255,0,0),(250,50),30)

pygame.draw.circle(surf,(0,255,0,128),(30,30),30)

display.blit(surf,(250,40))

surf=pygame.Surface((60,60),flags=pygame.SRCALPHA)

pygame.draw.circle(display,(255,0,0),(350,50),30)

pygame.draw.circle(surf,(0,255,0,96),(30,30),30)

display.blit(surf,(350,40))

pygame.display.update()

input()

THEC2H6OJETBOATRACEGAME

Muchof the informationcommunicated fromagameback to theplayer isdonevisually.Ourabilitytodisplayimagesanddrawgraphicsisessentialtothiscommunication, and immediately demonstrates the dependence of a game onartisticassetsandgooddesign.ThecaseoftheJetBoatGamewearedevelopingisagoodexample.

Page 91: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE2.13Terrainimagefortheboatracegame.

The game requires art assets, and those must be described first by thedesigner and then placed into the design document for use by artists anddevelopers.Themostsignificantpieceofart istheterrain.Thisisthestageonwhich thegame isplayed,or theboardonwhichcheckersorBackgammon isplayed.Itwillshowthelakeandriversonwhichtheboatswillberaced.Figure2.13shows the terrain image thatourgamewilluse,but therearemanyotherpossibilities.Havingacompetentartistisessentialforthistask,andgoodartistsareworthjustasmuchasgoodprogrammers.

TheterrainartinFigure2.13wascreatedbyaprogrammer,usingaterraintexturegenerationtool(http://cpetry.github.io/TextureGenerator-Online/).

When the game is executing, a portion of the terrain image is displayed,usuallyonewithinwhichtheplayer’savatar(inthiscaseaboat)isfound.Thegamedisplay is awindowwithin themuch larger terrain image,which in this

Page 92: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

instance is 8000 x 7000 pixels. The mobile elements of the game, boats forexample, are objects having a position and speed, the speed being specifiedultimatelyinpixelsperframe.Thesearedrawnovertheterrainimage.Thefirstimagedrawn is the one further in the background, and themore recent objectdrawnwillbeontopofthis(Figure2.14).Theobjectsthatcanmovecouldbedrawninnewpositionsineachframe.

FIGURE2.14Drawingofthegameinvolvesdrawingspritesandobjectsovertheterrain.

The game thus has a background, static objects (i.e., trees, walls, piers,rocks), anddynamicobjects (i.e., boats, buoys,markers, power-ups).An artistcreatesthemandplacesthemintoanimagefile,andtheprogrammermustreadthoseimagesanddrawthemwheretheybelong.

EXERCISES

Thefollowingproblemswillexerciseyourknowledgeofthematerialinthischapterandsometimesrequirethatyoudomoreresearchbeforeyouareableto

Page 93: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

completethem.Solutionstosomeoftheseareavailable.

1. Writeafunctionthatwilldrawaregularhexagon.Assumethatthehexagonhas sides of lengthh, andwill be drawn in such away that theupper leftcorneroftheboundingboxisspecificasaparameterpos.Thecallwouldbe:

hex(display,col,h,pos)

wherecolisthecoloranddisplayisthesurfaceonwhichtodraw.2. Create a program thatwill display an image that is specifiedwhen a user

typesthefilenameofthatimageontheirkeyboard.3. Writeaprogram thatdrawsa target consistingof tenalternatingwhiteand

blackcircles.4. Write a program that displays an imageon the screen.When themouse is

clickedarectangle isdrawnwithinwhich the imageappearsmagnified2x.Thismagnifyingwindowcanbedraggedaroundthescreen,magnifyingtheimagebeneathitasitmoves.

5. Image file formats GIF, JPG, and BMP differ in how they store data andcompressit.FindanimageandsaveitasaGIF,JPG,andBMPfile.Usinganimage display utility of your choice, examine those images at variousdegreesofmagnification.Whatcanyouobserveabouttheeffectofdifferentformats on the image data? (Not all images will illustrate the likelydistortionsofeachformat.)

6. Create a program that displays an image and allows the user to select aportion of it using the mouse: click, drag, and release will define arectangularsubimage.Thissub-imagenowbecomesthewholeimage,fillingthewindow.WhentheRETURNkeyispressed,theimagebeingdisplayedinthewindowissavedasafilenamed“output.jpg.”

7. Makebubbles.Bubbles ina liquidarebasically spherical,butget largerasthey rise to the surface, where they eventually burst. Create a sketch thatmakesbubbles that lookmoreor less real.They should rise to the surfaceandincreaseinsizeastheydo.(Lookupthefunctionrandom.)

8. Findanimageofatelevisionsetandmakeacopyinafile.Findanyotherimageyouwantanddisplaythetwoimagessothatitlookslikethesecondimageisbeingdisplayedonthetelevision.Whatdidyouhavetodotomakethisappearnatural?

RESOURCES

Page 94: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

2DGamegraphicstutorial:http://gamebanana.com/tuts/11225Intro to 2D Graphics: http://rbwhitaker.wikidot.com/introduction-to-2d-

graphicsProcessingdocumentation:http://processing.org/reference/Techniques for fancy and lightweight 2d graphics (game producer blog):

http://www.gameproducer.net/2008/03/03/techniques-for-fancy-and-lightweight-2d-graphics/

Sprite Database: http://spritedatabase.net/. Useful information anddownloads.

OpenGameArt:http://opengameart.org/.Downloadablespritesand2Dart.

REFERENCES

1. CharlesKelly.(2012).Programming2DGames.BocaRaton,FL:AKPeters(Taylor&Francis).

2. J.R.Parker.(2011).AlgorithmsforImageProcessingandComputerVision,2ndedition.Indianapolis,IN:Wiley.

3. John Pile Jr.. (2013). 2D Graphics Programming for Games. CRC Press(Taylor&Francis).

4. AllenSherrod.(2008).GameGraphicsProgramming.Boston,MA:CourseTechnology(CengageLearning).

5. Daniel Shiffman. (2008). Learning Processing. Burlington, MA: Morgan-Kaufman.http://www.learningprocessing.com/.

Page 95: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER3

THEGAMELOOPInChapter2,allofthePygameprogramsendedwithaninputrequest.This

was so thewindowwould stay open long enough so that the graphical outputcould be seen. This is not the correct way to do this. Pygame has devised aschemethatnotonlykeepsthegraphicsonthedisplaywindow,butrepeatsthedrawing process as often as needed so that the game can progress frame byframeandpermittheusertointeractusingthemouseandkeyboard.

BecausePygamewas specificallydesigned tobeused inmakinggames, itallows theprogrammer to easilydowhatwas suggested inChapter1: to keeptrackof all objects and implement the interactionsbetween themaccording tothe rules. This means that Pygame allows for fixed-time intervals to passbetweenframesandhasanimplementationofanevent.

TIMEANDINTERVALS

Thegameloopistheheartofanygame.Ahigh-levelabstractionofwhatitdoesis:

LoopforeverMoveobjects

CheckforcollisionsHandleEventsHandleSoundsDrawallobjectsatcurrentpositions

Apotential problemwith this loop is that itwill not always take the sameamountoftimetoexecute.Thiscanresultingameplayissuesthatinterferewithpartsof thedesign.Aclassic example is theold arcadegameSpace Invaders.Figure3.1showshowthisgamecouldlook,althoughthisisnotascreenshotforcopyrightreasons.Theplayercontrolsthefootballshapediconatthebottomofthescreen,whichcanfirelittlesquaremissilesupwardwhenabuttonispressed.

Page 96: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Ifthemissilehitsoneoftheshapes(representingspaceships)above,themissileandshipwilldisappear.Theentirearrayofshipsismovingleft,thendown,thenright, thendown,andsoon tocreatemoving targets.Theproblemwas thatasthe targets were shot and vanished therewere fewer objects remaining in thegame,andthegameloopwouldexecutealittlefaster.Whentherewereonlyacoupleofshipsleft,theyweremovingveryquicklyindeedandwerehardtohit.Althoughthiswasinfactabug,itwaskeptinthegameasafeature.

Thegame loop should takeabout the sameamountof timenomatterhowmuchworkmustbedone. It’snotpossible tospeed theexecutionup, sowe’llhavetoslowitdowntoasteadypace.Inthepreviousgameloopsketch,thiscanbedonebyaddingonemorestatementatthebeginning,makingitlooklikethis:

LoopforeverWaituntilthecurrentfixedtimeintervaliscompleteMoveobjects

CheckforcollisionsHandleEventsHandleSoundsDrawallobjectsatcurrentpositions

Thewaitwillensure thata fixedframerate isassured. If, forexample, theframerateissetto30persecond,theneachframewilltake0.333seconds,andwhenthatperiodhasexpired,themoveobjectsstepcanbedone.

Page 97: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE3.1SpaceInvadershadabugthatmadethegamerunfasterasobjectswereremovedfromplay.

Thepygame.timeModulePygame has amodule named time thatmonitors the passage of real time.

Thisissomethingthatmostprogrammingclassesdonotgetinvolvedwith.Yetoperatingsystems,networking,andgamesrequirecloseattentiontothepassageof time. The time module offers four functions and a class that offer theprogrammerawaytokeepclosetrackoftime,mainlyelapsedtimeorintervals.

The function pygame.time.get_2ticks() returns the number of millisecondsthathavepassedsincepygame.initwascalled.This functioncouldbeusedfortimingthemainloop,butitwouldnotbethebestchoice.Ifwewantedtoprintamessageeverysecond,thenhere’scodethatwoulddoit:

importpygame

pygame.init()

t=1000#1000milliseconds=1second

whileTrue:#Loopforever

#OthercodehereGamecode

ifpygame.time.get_ticks()<t:#Timesinceinit<tmillisecs?

continue#No.loopagain.

print(t//999)#Printseconds

t=t+1000#Addonesecondtot

ift>10000:#Stopafter10seconds

break;

Thiswill print amessage each second for ten seconds. The comment thatsays“Othercodehere”couldhavesomePythoncode thatwouldexecuteeachsecond.Changing the constant 1000 to 33would give the period of time thatwouldaccommodateoneframeat30framespersecond.Thiswouldwork,buttheproblemisthattheloopwillexecuteconstantly,burningupCPUtimedoingnothingatall.This isusuallyconsideredtobeabadthing.Otherprocessesonthecomputerwouldsuffer.

The function pygame.time.delay() does some of that work for theprogrammer.Itpausesforthespecifiednumberofmillisecondsusingthesamemethod—runningaloop,executingCPUcycles,untilthespecifieddurationhaspassed.Thepreviousloopwouldbeexecutedinthefollowingway:

importpygame

pygame.init()

t=1000

Page 98: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

whileTrue:

#Othercodehere

delta=t-pygame.time.get_ticks()#Calculatetimeremaining

ifdelta>0:#Waitforthattimeperiod

pygame.time.delay(delta)

print(t//999)

t=t+1000

ift>10000:

break;

The value of the expression t - pygame.time.get_ticks() will be the timeremaininginthecurrentframe.Eachtimethroughtheloopthiswillgetsmallerasrealtimeadvances.TheproblemwithbothofthesecodesnippetsisthattheCPUisactiveduringthetimedelay.It’seatingupCPUcyclesfornoreason;aCPUcanbemade topause, to switch to another process for awhile and thenreturn.Thefunctionpygame.time.wait()makestheprocess“gotosleep”tosharethe processor with other programs. A program that waits for even a fewmilliseconds will consume very little processor time, but it is slightly lessaccuratethanthefunctionpygame.time.delay().Thenewcodewouldbe:

importpygame

pygame.init()

t=1000

whileTrue:

#Othercodehere

delta=t-pygame.time.get_ticks()#Calculatetimeremaining

ifdelta>0:#Waitforthattimeperiod

pygame.time.wait(delta)

print(t//999)

t=t+1000

ift>10000:

break;

Thisisthebestversionsofar.Waitallowsotherprocesseslikeyourbrowserandemail reader toexecutewhile thegame iswaiting. Itdoes require that theprogrammerkeeptrackoftheremainingtimeprettycarefully.Thereisanotherchoice,onethatisfrequentlyusedinPygame.

ThetimemodulehaswithinitaclassnamedClock.Thisclasshasmethodsthatcanreturnrealtimevaluesandtimeintervals,butithasonemethodthatisexactlywhatweneedforthegameloop:it’scalledtick(x).Itwillcomputehowmanymillisecondshavepassedsincethepreviouscall,buttheimportantthingisthatitwillwaitforaslongasyouwantanddosoinawaythatagameprogramwould find convenient. If avalue for theparameterx ispassed, theparameter

Page 99: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

willbeconsideredtobethedesiredframerate.Thefunctionwilldelaytokeepthe game running slower than the given ticks per second. So, by calling themethodClock.tick(40)onceperframe,theprogramwillneverrunatmorethan40framespersecond.Thepreviouscodewrittentouseclock.tickwouldbe:

importpygame

pygame.init()

clock=pygame.time.Clock()

whileTrue:

clock.tick(1)

#Othergamecodehere

print(t)

t=t+1

ift>10:

break;

Thissnippet is the typicalPygamemain loop,but the framerate isusuallyfaster,meaningthattheparametertotickwouldbeperhaps30or40(framespersecond)ratherthan1.

GameLoop:BouncingaSimulatedBall

Usingclock.tick()apracticalgameloopcanbecreated.In thiscase,aball,indicatedbyacircle,willmovearoundthescreen.Itwillchangedirectionwhenitreachestheedgeofthewindow.

Thepositionoftheballonthedisplaysurface,indicatedbyavariablenameddisplay,will be indicated by variables x andy. The number of pixels the ballmovesduringoneframeisindicatedbythevariablesdxanddy.Themainactionthattakesplaceeachpassthroughthegameloopwouldbetoupdatetheball’spositionanddisplayit:

x=x+dx

y=y+dy

pygame.draw.circle(display,(200,200,200),(x,y),20)

Of course, within a very few iterations, the position of the ball will beoutside of the screen and thus will not be visible. Consider the horizontaldimension,forexample.If thevalueofxbecomes larger than thewidthof thescreen, then theball shouldnotmoveany further right.The simpleway todothat is tochange thesignon thevariabledx so that thex valuenowdecreaseswitheachframe.Ifthevalueofxbecomessmallerthan0,meaningithasmoved

Page 100: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

past the left sideof the screen, then the sameaction, changing the signofdx,withhavetheeffectofmovingtheballtotherightineachframe,againkeepingtheballonthescreen.Thesamecanbedonefortheverticalmotionusingyanddy.

Thegameloopwouldlooklikethis:

importpygame

dx=3#SpeedinXdirection

dy=4#SpeedinYdirection

x=100#Xposition

y=100#Yposition

radius=20

pygame.init()

clock=pygame.time.Clock()

display=pygame.display.set_mode((500,300),pygame.SRCALPHA,32)

whileTrue:

clock.tick(30)#Makesure1/30secondhaspassed

display.fill((100,100,100))#Clearthescreen

x=x+dx#Moveobjects

y=y+dy

pygame.draw.circle(display,(200,200,200),(x,y),radius)#Drawtheball

if(x<radiusorx>500-radius):#Outsideofthescreeninx?

dx=-dx#Changethemotiondirectioninx

if(y<radius)or(y>300-radius):#Outsideofthescreeniny?

dy=-dy#Changethemotiondirectioninx

pygame.display.update()#Updatethescreen

Inthecode,checkingthexandyvaluesisdone,accountingfortheradiusofthecirclesothatitlooksliketheballisbouncingoffofthesides.AscreenshotfromthisprogramappearsinFigure3.2.

This program executes forever, and it requires the user to stop it from thekeyboard.There’sabetterwaytoendaprograminPygame.

EVENTS

Aspointedoutbeforeinthisbook,aneventcanbedefinedassomethingthathappens.InPythonandPygame,aneventisalsoaclassandamodule,eachonerepresentingsomethingspecificthatcanhappenwhileaprogramexecutes.

What is meant by something that happens? It’s usually somethingunpredictable, such as a key press ormouse gesture. Accordingly, one of themostimportantusesforeventsinPygameisuserinput.

The pygame.event module contains thirteen functions, but the mostimportantoneisget().Whenaneventoccurs,likeakeypress,arecordofthatisplaced intoaqueue.Theget() function returns the listofevent objects in that

Page 101: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

queueandremovesthosefromthequeue.Whatisreturnedisalist(actually,aneventlistobjectreference)ofthingsthathavehappenedsincethepasttimeitwascalled.Eachof theseeventsmayneed tobehandleddifferently, ina loop thatlooksatthemall.

Thetypicaleventhandlingloopis(inpseudocode):

FIGURE3.2Screenshotofthebouncingballprogram.

foreventinpygame.event.get():

ifevent.type==someeventtype:

#dosomething

ifevent.type==someothereventtype:

#dosomethingelse

Thisgetseacheventfromthelistandcheckstoseewhattodowithituntiltherearenomoreevents.Thevariableevent.typeindicateswhichspecificeventhasbeenencountered.Therearefifteenofthose,butmostarenotcommon.Theyare:

EventName WhatHappened?QUIT GameisoverACTIVEEVENT Pygamehasbeenactivatedorhidden,

perhapsbymouseKEYDOWN AkeyhasbeenpressedKEYUP AkeyhasbeenreleasedMOUSEMOTION Themousehasbeenmoved

Page 102: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

MOUSEBUTTONDOWN AmousebuttonhasbeenpressedMOUSEBUTTONUP AmousebuttonhasbeenreleasedJOYAXISMOTION JoystickwasmovedJOYBALLMOTION JoyballwasmovedJOYHATMOTION JoystickhatwasmovedJOYBUTTONDOWN AjoystickorpadbuttonwaspressedJOYBUTTONUP AjoystickorpadbuttonwasreleasedVIDEORESIZE PygamewindowwasresizedVIDEOEXPOSE PartofthePygamewindowwasexposedUSEREVENT Auserdefinedevent

The names in boldface are the most important ones for most situations.Theseareconstantsinsidetheeventmodule,sothefullnameoftheQUITeventwouldbepygame.QUIT.

The bouncing ball loop complete with a QUIT event handler would bewritten:

whileTrue:

clock.tick(30)#Makesure1/30secondhaspassed

foreventinpygame.event.get():

ifevent.type==pygame.QUIT:

exit()

display.fill((100,100,100))#Clearthescreen

x=x+dx#Moveobjects

y=y+dy

...

pygame.display.update()#Updatethescreen

ThisexitstheprogramwhentheQUITeventisencountered.

TheMouseThe threebasicmouseevents,MOUSEMOTION,MOUSEBUTTONDOWN,

andMOUSEBUTTONUP,giveallthatisneededtodealwithmouseinput,andbecause finger gestures on a touch screen are essentially the same as mousegestures,thesameeventsareusedforthoseaswell.

Page 103: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

TheQUIT event has no other data connectedwith it, but other events do.These are called parameters even though they are variables local to the eventmodule. In the case of mouse events, the parameters are the position of themouse in thedisplay surface, thedistance themousehasmoved since the lastevent,andwhichbuttonwaspressedorreleased.

The parameters are named and can be accessed via the object referencereturnedbyget().

Event.buttons Atuplehavinganentryforeachmousebutton.So,buttons[0]is1iftheleftbuttonispressedand0otherwise.Buttons[1]isthemiddlebuttonandbuttons[2]istheright

Event.pos Atupleholdingthepositionofthemousewhentheeventoccurredas(x,y).

Event.rel Atupleholdingthedistancethemousehasmovedsincethepreviousmouseevent(dx,dy).

The event can be printed, so a program that allows the viewing of theparameterswhileaprogramexecuteswouldbe:

importpygame

pygame.init()

clock=pygame.time.Clock()

display=pygame.display.set_mode((500,250),pygame.SRCALPHA,32)

whileTrue:

clock.tick(30)

foreventinpygame.event.get():

print(event)

ifevent.type==pygame.QUIT:

exit()

Atypicaloutputlinewouldbe:

<Event(4-MouseMotion {‘pos’: (465, 82), ‘rel’: (-31, -1), ‘buttons’: (0, 0,0)})>which shows the currentmouse position, themotion since the previousevent(totheleft),andthatnoneofthebuttonsarepressed.

TheKeyboardAnother important kind of event is a key press. The event KEYDOWN

occurswhenanykeyispressed,andKEYUPoccurswhenakeyisreleased.Thismeans that a key could be depressed formultiple frames (iterations). The key

Page 104: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

thatwaspressedisidentifiedintheeventobjectitselfasthevariableevent.key.This variable holds a pygame constant that represents the key, and it isnot acharacterconstant.Everycharacterhasacorrespondingconstantwithinpygamethatidentifiesit.Thecharacter“a”isrepresentedaspygame.K_a, forexample(acompletelistcanbefoundathttps://www.pygame.org/docs/ref/key.html).

Consider that agamewill allow theplayer to accelerate anobject forwardwhenthe“w”keyispressedandslowitdownaslongasthe“s”keyispressed,whichisastandardscheme.Aloopthatdetectsthesekeypressesis:

foreventinpygame.event.get():

ifevent.type==pygame.KEYDOWN:

ifevent.key==pygame.K_w:

forward=True

elifevent.key==pygame.K_d:

backward=True

ifevent.type==pygame.KEYUP:

ifevent.key==pygame.K_w:

forward=False

elifevent.key==pygame.K_d:

backward=False

Anotherwaytodetectkeypressesistousethekey_pressedmethod.Thisisapartofthekeyclassofpygame,anditreturnsatupleofflagsthatindicatethestate of every key: False (or 0) means the key is not pressed, and True (1)indicates that it is pressed. Testing to see if the “w” key is pressedwould beaccomplishedasfollows:

pygame.key.get_pressed()[pygame.K_w]

This method does not require the use of the event class and can be usedanywhereinthecode.Itisalsointerestingtonotethatthepygameconstantsforcharactersareactually indices into the tuple.Code that is equivalent to that inthepreviouseventloopcouldbewritten,usingkey_pressed,as:

z=pygame.key.get_pressed()

forward=False

backward=False

ifz[pygame.K_w]:

forward=True

elifz[pygame.K_s]:

backward=True

AnOn-creenButtonA button, in the user interface sense, is usually a rectangle that is drawn

Page 105: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

withinawindow.Whenamousebuttonisclickedwhilethecursoriswithinthisrectangular area, some task is performed. Almost everyone who has used acomputerhas“clickedonabutton.”Here’showitworks.

Themousepositionistestedaftereachtimeitismovedtoseeifthecursor,whichistheiconthatrepresentsthemouseposition,lieswithintherectangulararea defined by the button. The button itself can be defined by its upper leftcoordinates ULX and ULY, its width, and its height. If mouseX is the xcoordinateofthemouseandmouseYistheycoordinate,thenthecursoriswithinthebuttonif

(mouseX>=ULX)and(mouseX<=ULX+width)and

(mouseY>=ULY)and(mouseY<=ULY+height)

Ifthisistruethebuttonissaidtobearmed,meaningthatthebuttononthemouse will now cause an action. Let’s assume that the action desired is tochangethebackgroundcolorofthedrawingsurfacetored.Theloopwillbethesameasthepreviousoneuntiltheeventloopisencountered.Then:

foreventinpygame.event.get():

ifevent.type==pygame.MOUSEBUTTONDOWN:

When themousebutton is pressed, this eventwill occur and the code thatfollowswillbeexecuted.Was themousebuttonclickedwithin the rectangularregion defined by the screen button?Let the screen button have an upper leftcornerat(100,100),awidthof100,andaheight0f50.Then:

mouseX=event.pos[0]

mouseY=event.pos[1]

if(mouseX>=ULX)and(mouseX<=ULX+width)and

(mouseY>=ULY)and(mouseY<=ULY+height):

display.fill((255,0,0))

becausewewanttochangethecolorofthedisplaysurfacetored.Whenthescreenisupdated,thecolorchangewilloccur:

pygame.display.update()#Updatethescreen</CODE>

Thisworks,butitiscustomarytodrawtherectangleonthescreensouserscanseeitandknowwheretoclick.Thishastobedoneeverytimethescreenisrefreshed.Somewherebefore thecall toupdateshouldbea line thatdrawstherectangle:

pygame.draw.rect(display,(0,255,255),(100,100,100,50))

Page 106: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE3.3The“button.”Left–Thebuttoncanbeseenbuthasnotbeenpressed.Right–Afterpressingthebutton.

ASimpleGameUntilnow,wecouldnotreallybuildacomputergamebecauseinputfromthe

userwasnotpossible. Interaction is essential in agame.Nowwehavemouseinput,andthat’salmostallweneed.

Here’sasimpleidea:wehaveabouncingball,aswemadebefore.Whenthemouseisclickedwhilethecursorininsidetheball,itdisappearsandreappearssomewhereelseonthescreen.Thisisnotmuchofagameintermsofitsbeingfun,butithasmanyoftheneededcomponents.Also,alotofthecodealreadyexists.

Beginningwith the existing program from earlier in the chapter gives thebouncingballpart.Addingthemouseinterfacemeanstestingtoseeifamouseclick finds the cursor within the circle on the screen. The circle is drawn atlocationx,yanditsradiusisgivenbythevariableradius,sowhatweneedtodoistoaddamouseclickeventandthenchecktoseewhetherthelocationofthatmouseclickiswithindistanceradiusofthepoint(x,y).

foreventinpygame.event.get():

ifevent.type==pygame.MOUSEBUTTONDOWN:

mouseX=event.pos[0]

mouseY=event.pos[1]

ifdistance((mouseX,mouseY),(x,y))<=radius:

#dosomething.

ThefunctiondistanceissimplytheEuclideandistancefunction,andthetwolocations between which the distance is to be determined are tuples. Thecomment “do something” is where the ball is removed and placed in a newlocation.Thatcanbedonesimplybychangingthevaluesofxandy.Let’splacetheballat100,100again:

foreventinpygame.event.get():

Page 107: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ifevent.type==pygame.MOUSEBUTTONDOWN:

mouseX=event.pos[0]

mouseY=event.pos[1]

ifdistance((mouseX,mouseY),(x,y))<=radius:

x=100#Xposition

y=100#Yposition

Thisprogramiscalledgame01.Itlacksafewthingstomakeitacompletegame.Therearenointroandextroscreensandnoscorekeeping.It’sbasicallyatoy.

ABetterGameScorekeepingisanimportantpartofagame,butitcansometimesbetricky.

Asimplewaytodoitistohavetheplayercontinueuntiltheyfailandcountthenumber of times they succeeded. A better game than the previous onewouldallowtheplayertokeepclickingandtomakethetaskhardereachtimetheyaresuccessful.Asuccessfulclickisapoint,andthegameisoverwhentheyfail.

Makingthegamehardercanbeassimpleasmakingthemotionoftheballfaster or making the ball smaller. The former is better because it has amoregenerouschallenge.Onecanonlymaketheballsosmall,afterall.Makingtheball move faster means increasing the values of dx and dy by some amount,whichiseasytodo.

A problem is that dx and dy can be positive or negative, so just adding afixedvaluetothemmayslowthemdown,ratherthanspeedthemup.Afunctionnamedsign(x)canbeusedthatreturns1ifthesignofxispositiveand-1ifitisnegative.Nowspeedinguptheballisaccomplishedby:

dx=dx+sign(dx)

dy=dy+sign(dy)

Now we need a score. This is simply an integer count of the number ofsuccessful clicks. It should be displayed on the screen and updated after eachframe.Thevariablewillbenamedscore:

t=font.render(“Score:“+str(score),1,(255,255,255))

display.blit(t,(20,20))

Thefinalmodificationtogame01is toquit thegameif theusermissestheball.Theeventloopisnow:

foreventinpygame.event.get():

ifevent.type==pygame.MOUSEBUTTONDOWN:

mouseX=event.pos[0]

Page 108: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

mouseY=event.pos[1]

ifdistance((mouseX,mouseY),(x,y))<=radius:

dx=dx+sign(dx)#Xspeed

dy=dy+sign(dy)#Yspeed

score=score+1

else:

exit()

FIGURE3.4Game02,clickinonthemovingballtogetpoints.

Thisisgame02,andascreencaptureofthegamebeingplayedisshowninFigure3.4.

RANDOMNESSINGAMES

Randomness has a huge role in games, not just computer games but allgames.Adeckofplayingcardsisalwaysshuffledsothatthecardsaredealtinarandom order. Dice are used in many games to create random integers. Incomputergames,randomnumbersareusedtoresolvebattles,toplaceopponentsonaplayingarea,todeterminehowtoevaluateaplayer’schoice,andtoproviderealisticpatternsof traffic,movement, andother aspectsof realism inagame.Why? Because a sufficiently complex situation has the appearance of being

Page 109: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

random.Howoftenwillabusarriveataspecificstop?Ofcourse,thereisaschedule,

butdobussesarriveatthestopexactlyontime?Always?Iftheydid,wouldthatseem like a realistic situation? Probably not. So, a game that involved bussesarrivingwouldlikelyaddarandomnumbertothescheduledtimetodeterminewhenthenextbuswouldarrive.Thevariabilitymakesitseemmorereal.

If we use a machine (the computer) to generate random numbers, it isactuallynotpossibletoproducetrulyrandomnumbers.Itishoweverpossibletocreate a set of equations that when used repeatedly will produce a series ofnumberswherenomatterhowmuchof theseriesyousee, it isnotpossible topredictwhatthenextnumberintheseriesis(unlessofcourseyouhaveaccesstothe set of equations). One very useful aspect of these pseudorandom numbergeneratorsisthatifyoustartwiththesameseed,youareguaranteedtoproducethe identical sequence of numbers. Now, this is not good for games andgambling, but it is extremely useful when testing a program and in somesimulations.Whentestingaprogramitisimportanttobeabletoreproducetheidenticalstatementexecutionsequence.

Forotherapplications,itisjustasimportantthatwebeunabletoreproducethe sequence. If Video Lottery Terminals or other gambling machines wentthroughanidenticalsequenceeachtimetheywereturnedon,itwouldprobablybealotlessfunandtheoperatorsofthesemachineswouldnolongerbeabletocountonthefactthatmanymorepeoplewilllosethanwillwin,asisthecaseinallgambling (i.e., itwouldn’tbegamblinganymore). In theseapplications thesequenceofnumbersusedmustbeasclosetorandomaswecanget.

RandomnessGenerallyWhenwesaythatsomethingisrandom,whatdowemean?Ineverydaylife,

things that we call random are things that are unpredictable. Objects that aremoving at random have no identifiable pattern; events that occur at randomcannotbeanticipatedorpredicted.Thattheeventwilloccurmaynotberandom,butpreciselywhen itwilloccurmightbe.Whenwill thenextredpickuptruckpassby?Whenwillthenextcustomerarriveatthebankteller’swindow?Whowillwinthenextcivicelection?Thesearethingsthatarecommonlythoughtofasrandomevents.Thetechnicalmeaningofrandomrelatestothesethings,butitismorespecificandlessintuitive.

Consider aguessinggame inwhichaplayer is asked toprovide anumberbetween1and10.Iftheplayerguessescorrectly,theywinsomemoney,perhaps$8.Otherwise they lose $1. The player chooses the number 7. Is 7 a random

Page 110: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

number? How can this be established? One way to look at it is that therandomnessofthatparticularnumber7isdeterminedbytheprocessusedtogetthat7.Perhapsdicewererolled,ormaybetheanswerisalways7.Thisisapartof thecommonmeaning impliedwhenwe say something is random,and so ithas some value, but it’s not a technical ormathematical definition, because itcannotbeaccuratelydefinedortested.Youmaybelievethat7wasrandom,butifyoudidnotknowhowthatnumberwasarrivedatyouwouldhavenowayofdeterminingifitwas.

Let’s repeat the experiment.The number 7 is chosen again. Is this onerandom?Thesameargumentsapplyhereasappliedtothefirstexperiment.Doesanythingchangeifwelookatthewholesetofexperiments(inotherwords,bothofthemtogether)?Itproducedapairofnumbers,“77”;aretheserandom?Somemightsaythattheystarttodetectapattern(thatIampickingonlysevens)andthatthisisnotrandom.OfcourseitiseasilypossiblethatIselectedtwosevensinarow,andthatithappenedbychance.Whatifthisexperimentisrepeatedahundred times and produces a six each time?Now it’s pretty clear that thesenumbers are not random and that the pattern can be defined with someconfidence.Thepointofthisexerciseistounderscoretheideathatnumbers,andthings in general, are random relative to one another only.Randomness existsonlyincontext,asarelativepropertyofsequencesofnumbers.

Whatif the7thatIpickedistheresultofadierollandyoucanwatchmeroll it?Does thatviolate the rule that random things are random in relation toothers?Notatall.Randomnessisapropertyofacollectionofeventsorobjects,preferablyalargecollection.Thisistrueevenifthecollectionweareusingwasproducedatanothertime,asisthecasewithmydieroll.Weassumethattherollin question is like all the other rollswe know, and sowe can say this one israndom too. Looking at the properties of large collections of numbers isessentiallywhatstatisticsisallabout.

Whenwelookathumanbehavior,itisinfactdifficultforahumantobehavein a random fashion. People have learned connections between events: thingsthatarerelatedtoeachothercan’tberandomwithrespecttoeachother.Wealsohave misunderstandings about randomness, make correlations betweenperceptionsandactions, andpossessahostof instinctiveactions thatprecluderandombehavior. Individualscanbe trained tobehave randomly,butwedon’tdoitinstinctively.Thebehaviorofgroupsofpeoplecanseemrandombecauseitissocomplex,buttheappearanceofrandomnessdoesnotnecessarilyimplythatsomethingisindeedrandom.Forexample,ifalargegroupofpeopleisaskedtopick “heads” or “tails” in a coin toss, it may be that the number of peopleselecting “heads” is almost the same as the number selecting “tails.” The

Page 111: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

complexpatterns of the individual lives that produced the specific decisionof“heads”or“tails” that theymade thatdaywouldbe impossible toanalyzeandcan seem random. However, if those selecting “heads” are moved to anotherroomand asked to repeat the selectionmany times, it is likely that this groupwill end up selecting headsmore often than chancewould dictate. Therefore,theirchoiceof“heads”wasnotrandom.

When implementing things on a computer, it is important to realize thatunderneath it all everything is represented using numbers. That’s because theonlythingsthatcomputerscanmanipulatedirectlyarenumbers.Thismeansthatifwewanttocreatearandomcolor,forexample,wefirstneedtocomeupwithawaytorepresentcolorsasnumbersandthengeneratesomerandomnumbers.Thefirststepiseasy:yousimplycreateamappingofnumbersandcolors.Often,itdoesn’tevenmatterifyouareorganizedaboutitsolongasthesamenumberalwaysreferstothesamecolor(5=red,8=blue,0=white,etc.).Oncewehaveourmapping,wecanchoose randomnumbers just likewewould foranythingelse and then “translate” those numbers into their representative colors. If thenumbers are random, then the colors are too. This applies to any elementwewanttobeabletoselectatrandom.

Randomcanbeatrickywordinthatitmeanssomethingtomostpeoplebutalso has a more specific, technical meaning in science generally, and insimulation inparticular.Themainpurposeof thischapter is toexplainwhat ismeantbytheword“random”inthemoretechnicalcontext.

RANDOMNESSINGAMES:DICE,CARDS

Whendiscussing randomness,manypeople thinkofgamblingorofgamesthat involve random selections and actions. Gambling has had an appeal tohumansthroughoutrecordedhistoryandnaturallyinvolveschance.Nosensiblepersonwouldbetagainstaneventthatwascertaintooccurorevenforonethatwasunlikely.Soitisthatwhendiscussingrandomness,thesubjectveryquicklyturnstogambling.

Thesimplestexampleofgamblingisthatofacointoss.Twochoicedecisions(also called binary decisions) are sometimesmade by assigning a decision toeachsideandthendeterminingthe“winner”byflippingacoin.Footballteamsflip a coin to decidewhich side kicks off. The name for the city of Portland,Oregon was chosen based on the toss of a coin (it could have been namedBoston). In1959,amemberofBuddyHolly’sbandflippedacoinwithRichieValenstoseewhowouldgetthelastseatonasmallplaneflyingoutofFargo,NorthDakota after a concertwhen their bus brokedown.Valenswon, andhe

Page 112: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

diedwhen the plane crashed.Because a coin has two sides, and because it ispresumed that the coin is fair and that flipping it creates a random selectionbetweenthetwosides,thisseemsanaturalwaytomakearandomchoice.EventheancientRomansflippedcoinsasagamblinggameCapitavelNavia (headsorships).We’veapparentlybeendecidingthingsthiswayforquitealongtime.

Weallknowthatadie isacubewithdifferentnumbersoneachof thesixfaces,anditshouldbehavelikeasixsidedcoin.Throwingadieproperly,wherethe cube tumbles and then bounces off of another surface, should create atrajectorysocomplicatedthatpredictingthenumberthatwillappearofthetopfacewould be impossible. The random nature of dice has appealed to humangamblerssinceprehistorictimes.Theoldestdieknownis5,000yearsoldandisfromIran,butreferencestogamblingwithdiceareevenolderthanthat.

Playingcardsarealsocommongamblingtools,andtheyarethoughttohaveoriginatedinChinainabouttheeighttotenthcentury,wellaftertheinventionofpaper.Beforethatdeviceslikedominoeswereusedtoplaysimilargames.Thenumberofcardsinthedeckvarieswithtimeandgeography,butthefirstdecksappeared to have four suits just likemodern decks. Contemporary card deckshavefifty-twocards(plusjokers),andthatmeansthatthereisa1in52chanceofpickingaspecificcardfromthedeckandahugenumberofdifferentfive-cardhandsthatcanbedealt.

The progression from coin to die to cards constitutes an increase incomplexityandanincreasingdifficultyinpredictingtheresultofsimpleevents.Events thatareverycomplex in termsof thenumberofpossiblecombinationsprovideamoreinterestingbasisforgambling,atleastpartlybecausetheresultsarehardtopredict.Inaddition,thevalueofacarddrawnfromadeckofcardsseemsmore random than does the result of a coin flip. So, not only are theredifferentdegreesofrandomness,butthereisacommonlyheldapprehensionofthisfact.

The modern discipline that concerns the likelihood of events is calledprobability,and itquantifies thesedegreesof randomness.Acoin tosshas twopossibleoutcomes.Oneoutcomeisheads,and theprobabilityofheadsonanygiven toss is0.5,or1/2—oneoutof the twopossibleoutcomes.Similarly, theprobabilityofrollingadieandhavingsixappearontopis1/6(oneinsix),andtheprobabilityofdrawingaKingofClubsfromashuffleddeckofcardsis1/52.The probability of drawing a King from the deck is 4/52, though, or 1/13,becausetherearefourkingsinthedeck.Thus,theprobabilityofdrawingaheartis13/52,or1/4.Anotherwaytoexpressthisistosaythataquarterofthetimeweexpecttopickaheart.Thesesimpledefinitionsmakesensetomostpeople,butinordertomakeuseofrandomnumbersinsimulations,weneedtobeable

Page 113: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

tomanipulateprobabilities,andtherulesformanipulatingprobabilitiesarelessintuitive.

ProbabilityforBeginnersWhendealingwithcomplexsituationssuchasarecommonintherealworld

and in simulations, therearemanyevents thatoccur,andprobabilitiesbecomemore difficult to determine. Fortunately, there are straightforward rules fordealingwithmultiple events.For example,what is theprobabilityof rolling adietwiceandgettingasixeachtime?Theprobabilityis1/6(onein6)foreachtrial; for both it will be 1/6 * 1/6, or 1/36. The individual probabilities aremultipliedtogethertoproducethecombinedprobability.LookingatthediagramofthissituationinFigure3.5,itshouldbefairlyeasytoseewhythisis.Forthefirstroll,eachpossibleoutcomehasaprobabilityof1/6,includingthetargetrollof“6.”Forthesecondroll,eachoutcomealsohasaprobabilityof1/6,andforeachindividualoutcomeofroll1therearesixpossibleoutcomesforroll2.Thismeanstherearethirty-sixpossibilitiesforthetworolls,andasixfollowedbyasixisjustoneofthose.Thus,theprobabilityis1/36.Thisisalsotheprobabilityofrollingtwosixessimultaneouslyontwodice.

FIGURE3.5Thesetofoutcomesforthetossingofapairofsix-sideddice.

Figure 3.5 shows the possibilities available when rolling a die twice,showingthespecificpaththathastwoconsecutive“6”rolls.Thisisthesameasrollingtwodicesimultaneously.Allpossibleoutcomesarelistedontheleft,and6-6isoneofthirty-sixpossibleoutcomes(1/36).

Now let’s look at a gambling game that involves dice to see how thecalculationofprobabilitiesgetsmorecomplex.Thegameofcrapsisplayedwithtwodicewhere thenumberson thediceareadded together.Aplayer’s turn incraps isasequenceofoneormore rollsdeterminedby the rules. If theplayer

Page 114: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

(shooter)throwsa2,3,or12,thentheyloseimmediately.Iftheyrolla7or11,then they win immediately. If a 4, 5, 6, 8, 9, or 10 shows, then that numberbecomes the “point,” and the player rolls the dice again until that number isrolledagain(win)ora7isrolled(lose).There’smoretoit,butthatisthebasicsetofrules.Here’syourquestion:whatistheprobabilitythattheplayerwillloseonthefirstroll?

Thisisaharderquestiontoanswerthanthepreviousones,becausethereismorethanonewaytorollaparticularnumber.Ontwodice,a3canbemadeintwodifferentways:byhavingthefirstdieshowa1andtheseconda2,orthefirst die couldbe a 2 and the second a1.Theprobability of rolling a three istherefore2/36,or1/18.Ingeneral,theprobabilityofaparticularsumisfoundbylookingat thepossibilities inFigure3.5.Tofind theprobabilityofgettinganyparticularnumber,countthenumberoftimesthesumoftwonumbersequalsthenumberyouwishtoroll,anddivideyourcountby36togivetheprobability.A“2”canonlyberolledbyhavingbothdicebe“1,”sotheprobabilityis1/36,anda“12”canberolledonlyas“6”anda“6,”sothat’s1/36.Thechancesofrollinganyoneof a “2”or a “3”or a “12” is the sumof the individualprobabilities,whichis1/36+2/36+1/36=4/36(or1/9).Incraps, this is theprobabilityoflosingonthefirstroll.

Ontheotherhand,therearelotsofwaystorolla“7”:1+6,2+5,3+4,4+3,5+2, and 6+1 for a total of 6/36. There are two ways to roll an “11.” Theprobabilityofrollinga“7”oran“11”onthefirstrollisthus6/36+2/36=8/36,or2/9.Thismeans that theprobabilityofwinningon the first roll is twice theprobability of losing on the first roll. This process of calculating probabilitiescanberepeatedforeveryoutcome,soitturnsoutthatthelikelihoodofwinningat craps iswell known and can be found on the Internet and in books. Theselikelihoods,thatisofgamblinganddaytodayactivities,aregenerallyexpressednotasprobabilitiesbutasodds.

ProbabilityCalculationsProbabilities are used both in real life and in simulations to estimate how

likelyeventsare tooccur.Simpleevents, like theflipofacoin,haveasimpleinterpretation in probability terms. More complicated events, especiallycombinations of events, require a degree of calculation. In these cases it issometimesuseful to thinkof aprobabilityasa specialkindofnumber, akindthat requires a special arithmetic.Consider two coin tosses, one after another.Theprobabilityofthefirstcoinshowing“heads”is1/2,andthesecondcoinisthesame.Whatistheprobabilitythatbothcoinsshow“heads”?Theansweris

Page 115: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

1/4,which is the product of the individual probabilities of each coin showingheads.Thisisingeneralthecorrectwaytocalculatetheoverallprobabilityofaseriesofevents—tomultiplytheindividualprobabilitiestogether.

There isasimplealgebrafor this.TheletterPmeans“probabilityof,”andthe expressionP(heads) means the probability of a coin showing heads. Theevent involved is inside the parentheses. We get to invent some of our ownnotationheresolongasitisconsistent,soP(H)willbetheprobabilityofheadstoo,P(H1)willbetheprobabilityofheadsshowingonthefirstcoin,andP(H2)is the same situation for coin2.The situationwhereheads is showingon twotossedcoinswillbewrittenasP(H1andH2),andifthecoinsarefairtherulecanbewritten:

P(H1andH2)=P(H1)×P(H2)

This rule applies to all independent events, and can be expanded to anynumber of them, not just two. The probability of three independently tossedcoinsallshowing“heads,”forexample,is

P(H1andH2andH3)=P(H1)×P(H2)×P(H3)

The rule expands in a logicalway for any number of events. Itworks formixedeventstoo,ofcourse.Thenatureoftheeventisnotatallimportanthere,onlythattheeventsdonotdependononeanotherandhaveknownprobabilities.So,ifP(D=6)istheprobabilityofrollinga6onasingledie,then

P(H1andD=6)=P(H1)×P(D=6)=(1/2)×(1/6)=1/12=0.08333

whichistheprobabilityofbothtossingheadsandrollingasix.

Page 116: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE3.6Thecompletesetofoutcomesforthetossoftwocoins.

Theprobability thatoneor theotherof twoeventswilloccur isa littlebitmore difficult to calculate, but it is not past high school math. The simplestexample is theprobability thatheadswill be thrownonanyoneof twocoins.Using thenotation justdevised, thiscouldbewrittenasP(H1orH2),and theobviousanswer,thatitisP(H1)+P(H2),mustbeincorrect.IfitwerecorrectthenP(H1orH2)=P(H1)+P(H2)=0.5+0.5=1.0.Thiscan’tbecorrectbecauseitmeansthatitiscertainthatoneofthecoinswouldbeheads.

In order to sort out away to calculate the probability of at least one of aspecifiedsetofeventsoccurring, lookatFigure3.6whichshowsadiagramofthepossibleoutcomesof twocoin tosses.The toppartof thefigureshows thetwo resultspossible for the first coin, andbelow that the resultsof the secondcoinare enumeratedbasedon the first toss.There are fourpossibleoutcomes,andeachcanbedescribedasoneofthepathsthroughtheoutcomesinthefigure.Theseoutcomesare:

H1andH2meansthatheadsisvisibleonbothcoin1andcoin2.RecallthatH1isthesymbolthatmeans“headsisshowingoncoin1.”

H1andT2meansthatheadsisvisibleoncoin1andtailsisvisibleoncoin2.T1andH2meansthattailsisvisibleoncoin1andheadsisvisibleoncoin2.T1andT2meansthattailsisvisibleonbothcoin1andcoin2.

Wewanttobeabletocalculatetheprobabilityofatleastoneheadshowingafter tossing two coins.From the figurewe could simply count theoutcomes:therearefourpossible,andthreeofthemhaveatleastoneheadshowing,sotheprobability is3/4 thatat leastonehead isshowing.However,notallsituations

Page 117: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

areaseasilydrawn,andsomeinvolveagreatmanypossibleoutcomes.Asimpleformulawouldbegoodtohave.

Withthisinmind,lookattheoutcomesagain.TheeventH1,whichisheadsshowingoncoin1,is1/2,andarisesthroughtheeitheroftheoutcomes(H1andH2)or(H1andT2).Theprobabilityofthisis:

P(H1)=P(H1andH2)+P(H1andT2)=1/4+1/4=1/2

whichisaswewouldexpect.Inthesameway,theeventH2arisesthrougheither(H1andH2)or(T1andH2).Thisprobabilityis

P(H2)=P(H1andH2)+(T1andH2)=1/4+1/4=1/2

The formula for theprobabilityof eitherH1orH2occurring ina twocointossstartswithP(H1)+P(H2),whichwouldcorrespondtotheevents:

(H1andH2)or(H1andT2)or(H1andH2)or(H1andT2)andhasprobabilityP(H1andH2)+P(H1andT2)+P(H1andH2)+(T1andH2).

Thisiswrong,butnownoticethat(H1andH2)appearstwice!Subtractinggivesusthecorrectformula:

P(H1orH2)=P(H1)+P(H2)–(H1andH2)

Thisformulaiscorrectforallindependentevents,thatis,eventsthatdonotaffect one another.We now have a basic knowledge of how events and theirprobabilitiesarecalculatedandcombined.Tobesure,thisknowledgeisessentialin gambling, and it will come in handy when thinking about randomness ingeneralandsimulationinparticular.

GENERATINGRANDOMVALUES

TheneedforapracticalsourceofrandomnumbersdatesbacktoaphysicistnamedEnricoFermiinthe1930sinthecontextofproblemsinparticlephysicsthat could not be calculated analytically. It was suggested that a simulationinvolving random numbers be created and made to run on an electroniccomputer.Thiswasactuallydoneinthe1940s,andoneresultwasthehydrogenbomb. At that time there was no convenient source of random numbers.

Page 118: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Electronic and physical deviceswere used to create events havingmeasurablerandomproperties,andthosemeasurementswereinturnusedtocreatetablesofrandomnumbers thatcouldbeused repeatedly.Themost famousof thesewascreated by the Rand Corporation using an electronically simulated roulettewheel.The tablewas sold as abook, the relatively famousAMillionRandomDigits(RandCorporation,1955).

Using this book,when youwanted a randomnumber, youwould flip to apage (any page) and read off a set of numbers from any line or column. Thenumbershadbeentestedtoassurerandomnessandwereareliablesourceforalongtime.Theproblemwasthataccesstothenumberswasslow,needingacopyof the book and human intervention.Of course, computersweremuch slowerthentoo,butevenconsideringthattheprocedurewasarduous.

Ofcourse,peoplewhoownedcomputersinthe1940sand1950shadalotofmoney at their disposal, so if they really needed a random number, then theycouldhavetheirownelectronicrandomnumbergeneratorbuiltandconnectedtotheirmachine.Whatwas used as the basis for these deviceswas the essentialunpredictability of noise signals obtained from radio or radioactive sources. Ifyouconnecta radio toadevice thatmeasuresvoltagesand tune the radio toaplace where no station is broadcasting, the human ear would hear a hissingsoundfromtheradio.Thisiswhatrandomsignalssoundlike,andthevoltmeterwilldisplaythisasrandomelectricalvoltagelevels.Thesecanthenbeconvertedintodigitalformandusedbythecomputerasrandomnumbers.Similarly,noisecan be created using a vacuum tube or solid-state device and sampled in thesamewayaswastheradiotoproducerandomnumbers.

PseudorandomNumbersNumbers that satisfy testsof randomnesscanbegeneratedmathematically.

Startingataparticularvaluecalledtheseed,asequence iscreated thatwillbethesameeachtime,butthatisrandomwithrespecttoeachother.Changingtheseedchangesthesequenceofnumbers.

WhenusingPython, themodulenamed random provides a set ofmethodsthatwillgeneratesuchnumbers,andinavarietyofways.Thesimplestcallistothemethodrandom:

random.random()

Thisreturnsarandomnumberbetween0and1,arealnumber.Thiscanbeusedtoimplementanyofthemethodsthatwillbediscussedhere.Forexample,acoinflipcouldbeimplementedas:

Page 119: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

flip=int(random.random()*2)

If the value of a flip is 0, then “heads” has appeared, otherwise “tails.”Another way to accomplish this is to use the method randint (a,b), whichreturnsarandomintegerbetweenaandbinclusive.Thecointosswouldbe:

flip=random.randint(0,1)

Adierollwouldberandom.randint(1,6),andsoon.Themethodchoice(s)returnsarandomselectionfromatupleoralist.Thus:

print(random.choice((1,2,3,4,5,6)))

returnsarandomelementofthetuple(1,2,3,4,5,6),whichwouldamounttoadieroll.Themethodrandom.sample(s,k)returnsalistofkuniquemembersofthesequences.Asanexample,thecall

random.sample([1,2,3,4,5,6],3)

mightresultin[3,1,5]or[5,6,2],butnever[2,1,2].Averyusefulmethodforcardgamesisrandom.shuffle(x),wherexisalist.

Itreturnsapermutationoftheitemsinthelistx.Consider:

cards=[“a”,”k”,”q”,”j”,”10”,”9”,”8”,”7”,”6”,”5”,”4”,”3”,”2”]

random.shuffle(cards)

Theorderof thevalues inx isnowrandom,andcouldbe [“8”,“10”,“k”,“3”,“4”,“6”,“7”,“9”,“q”,“a”,“2”,“5”,“j”]asoneexample.

Setting the seed for the random number generator can be an importantstartingpoint,becauseotherwisethesequencegeneratedwillbethesameeachtime.Therandommoduledoesthisautomaticallywhenitisstarted,butitcanalsobedonebytheprogrammer.Forexample:

random.seed(431)

willsetthesettothenumber421.Settingtheseedtoaknownvaluecanbeimportantwhendebugging. It ishardenough toanalyzeaprogram in the firstplace,butifitbehavesrandomlyitismuchharder.Whendevelopingcodeitcanbeusefultosettheseedtothesamevalueseachtime.

SIMULATINGREALITYANDINTELLIGENCE

Almostallcomputergamesareatypeofsimulation.Theymaynotsimulate

Page 120: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

a real situation, but they certainly have realistic elements. Reality has certaincharacteristicsthatarehardtorepresentconvincingly,andhumanshaveaknackforseeingthesesituationsandevaluatingtheirrealism.Ithasbeensaidthatnotwo snowflakes are alike. They have random characteristics caused by thecomplex,chaoticwaytheyareformed.Treesare like that too.Allsprucetreesseemverysimilarfromadistance,buttheyareallverydifferentatafinerscale,havingdifferentheights,numberandshapesofbranches,colors,barkvariations,andsoon.Peopleseesituationsasrealiftheirassessmentoftherandomnessofthesituationcorrespondswiththatseenintherealworld.

Ifarealistictreeistobecreatedonacomputer,itcouldbedonebyusingadetailedandcomplexsimulationoftheprocessofplantgrowth.Startingfromaseed,theforcesofmoisture,light,temperature,andchemicalgradientscouldbeapplied to the biological processes in the young tree. Over a great deal ofsimulatedtime,atreecouldbe“grown.”Or,asanalternativetothisprocess,thenumberandshapeofbranchesforeach treecouldbeselectedat randomusingknowledgegainedbyexaminingalargenumberofrealtrees.Thislattermethodwouldbemuchfasterandwouldnotrequireadetailedknowledgeofhowtreesgrow.

Games and simulations use randomness to simulate reality for two mainpurposes: as amodifiable abstraction of the objects being simulated; and as awaytorepresentcomplexprocessesthatarenotessentialtothesimulation,butthatlendasenseofreality,complexity,orpresence.Thelatteraspectisusedingames.Wecanuserandomnesstoprovideaccurateambiance.Asapedestrianinthegame,thewaythetrafficlooksisanessentialpartofthebackground,butitmaynotbeaprimarycomponent.Ifthetrafficflowistooregular,tooperfect,itdoes not seem real, and this detracts from the focus of the player/user of thegameitself.

This use of random numbers gives the appearance of reality in a game orsimulation.Whenthescenarioinvolveshumanresponses,itisimportantforthepeopleinvolvedtofeelthatthesituationisnormal,anditisalsoimportantthatsubjects or participants are not distracted by oddities in the simulatedenvironment. Complex situations have some random properties that humanobserverscometoseeas“realistic,”andsorandombehaviorscreatedartificiallycanleadanobservertoseeasimulatedsituationasmorerealisticthanitis.

This seemsobvious,but therearemanyvideogames inwhich, likeanoldBugsBunnycartoon,thesamecarpassesthesamepointrepeatedly.Thesameisoften true of computer-controlled characters in some games, who wander inexactly the same loop forever. These unnatural visuals detract from the mainactivityofthegameorsimulation.

Page 121: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

It is not onlyvisuals or intervals thatmatter, but it is the entire effect thatshouldconveytheillusionofcomplexity.Considerrainfallingonawindow.Thetime at which the next drop strikes the glasswill be random. The location atwhichitstrikeswillberandom.Thesizeofthedropwillberandom.Eventhesound that the impact makes will vary from drop to drop. This soundscomplicated but is really aboutmaking things look or seem right. Looking atFigure3.7,weseeapairofrenderingsofawindowwithrainonit;whichonelooks real?The renderingon the left hasdrops in randompositions and sizes,much as would be seen in a real scene. The rendering on the right looksartificial. It shows the same droplet appearing many times in an orderedformation and would be the cause of some surprise if observed from yourapartmentwindow.

FIGURE3.7Randomandnonrandomraindropsonawindow.

EXERCISES

The following exercises will test your knowledge of the material in thischapterandsometimesrequirethatyoudomoreresearchbeforeyouareabletocompletethem.

1. Modify thebasicbuttoncode,whichwasused tocreateFigure3.3,so thatthetext“Changecolor”appearswithinthebutton,andsothatonlyaclickoftheleftbuttonwillcausethecolortochange.Alsochangeitsothattherightbutton causes the color to change back (to black) and the middle buttoncausestheprogramtoend.

Page 122: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

2. Create a rendering of a fourlane road with vehicles placed in randompositions. It should be a top view and should use at least four differentvehicleimages.

3. Modifythebouncingballprogramsothatthecoloroftheballchangeswitheachbounce,asdoesthespeed.

4. Modify the bouncing ball program so that the speed of the ball increaseswhenthe“w”keyispressedanddecreaseswhenthe“s”keyispressed.

5. Findanimageofatelevisionsetandmakeacopyinafile.Createrandomnoisethatwillfillthescreenandthatchangeseachframe,soitlooksliketheTVisnottunedtoaworkingchannel.

6. Drawarectangleonthedrawingarea.Haveitrotatecounterclockwisewhenthe“a”keyispressedandclockwisewhen“d”ispressed.

7. Addcode toExercise7 so thatwhen the“w”key ispressed, the rectanglemovesinitsforwarddirection(i.e.,whereitispointed),andhaveitslowandstopifthekeyisreleased.

RESOURCES

2DGamegraphicstutorial:http://gamebanana.com/tuts/11225.Intro to 2D Graphics: http://rbwhitaker.wikidot.com/introduction-to-2d-

graphics.Processingdocumentation:http://processing.org/reference/.Techniques for fancy and lightweight 2d graphics (game producer blog):

http://www.gameproducer.net/2008/03/03/techniques-for-fancy-and-lightweight-2d-graphics/.

Sprite Database: http://spritedatabase.net/. Useful information anddownloads.

OpenGameArt:http://opengameart.org/.Downloadablespritesand2Dart.

REFERENCES

1. T.M.CoverandJ.A.Thomas.ElementsofInformationTheory.NewYork,NY:Wiley&Sons.Thisdescribes someof thebasicmathematics involved in randomness and

Page 123: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

probability.2. J. Dwyer. (1995). “Quick and Portable Random Number Generators.” C/

C++UsersJournal13,no.6(June):33–44.A discussion of how to implement random number generators inprogramminglanguages.

3. J. Dwyer and K. B. Williams. (1996). “Testing Random NumberGenerators.”Dr.Dobb’sJournal(June1).Anaccessiblediscussionofhowtotestnumbersforrandomness.

4. G. S. Fishman and L. R. Moore. (1982). “A Statistical Evaluation ofMultiplicativeRandomNumberGeneratorswithModulus231-1.”JournaloftheAmericanStatisticalAssociation77:129–136.Aninterestinglookatacommontypeofrandomnumbergeneratorandhow“good”itis.Thisisvaluablefromtheperspectiveofauserofthegenerator,andasanexampleofhowtotestthesegenerators.

5. T. R. Hopkins. (1983). “A Revised Algorithm for the Spectral Test [inFortran].”AppliedStatistics32,no.3:328–335.Adiscussionofoneofthetestsofrandomness.

6. F. James. (1990). “A Review of Pseudorandom Number Generators.”ComputerPhysicsCommunications60:329–344.Ageneraldiscussionof randomnumbergenerators from theperspectiveofpeopleusingthem.

7. C.Kenny. (2005,April).“RandomNumberGenerators:AnEvaluationandComparison of Random.org and Some Commonly Used Generators.”Dublin, Ireland: The Distributed Systems Group, Computer ScienceDepartment, Trinity College.http://www.random.org/analysis/Analysis2005.pdf.Acomparisonofsomeofthecommonrandomnumbergenerators,basedonexperiments.

8. D. E. Knuth. (1981). The Art of Computer Programming: Volume 2,SeminumericalAlgorithms,2ndedition.Reading,PA:AddisonWesley.Theseminalworkonrandomnumbergenerationandtheirevaluation.

9. W. L. Maier. (1991). “A Fast Pseudo Random Number Generator.” Dr.Dobb’sJournal16no.5(May):152–ff.AdescriptionoftheR250randomnumbergenerator.

10. W.Palubicki,K.Horel,S.Longay,A.Runions,B.Lane,R.Mech,andP.PrzemyslawPrusinkiewicz.(2009).“Self-OrganizingTreeModelsforImageSynthesis.”ACMTransactionsonGraphics28,no.3:1–10.

Page 124: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

A discussion of the simulation of tree growth as a means to creating treeimages.

11. RandCorporation. (1955).AMillionRandomDigitswith100,000NormalDeviates.Glencoe,IL:TheFreePress.TheoriginalRandcorporationsourceforrandomnumbersinthe1950sand1960s.

12. D. Stirzaker. (1999). Probability and Random Variables: A Beginner’sGuide.CambridgeUniversityPress.Cambridge,U.K.Agoodbookfromwhichtolearnmoreaboutprobability.

13. J.vonNeumann.(1963).“VariousTechniquesforUseinConnectionwithRandom Digits.” von Neumann’s Collected Works, Vol. 5, 768–770.Pergamon,Oxford.An early discussion of randomness written by a giant in the world ofcomputing.Ofgreathistoricalinterest.

14. B. Wichmann and D. Hill. (1987). “Building a Random-NumberGenerator.”BYTEMagazine(March),127–128.Abeginnersguidetobuilding(i.e.,programming)yourownrandomnumbergenerator.

Page 125: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER4

GAMEAI:COLLISIONSThe words “artificial intelligence” bring to mind a host of advanced

technology. Often our first exposure to AI, as it has come to be known, isthrough science fiction; the computers on Star Trek can speak fluent English,andtherobotsonStarWarscanservedrinksandpilotspacecraft.Intruth,AIhasnotadvancednearlythisfar,andalthoughcomputerscannowdefeathumansatchess and checkers, this is a far cry from the sceneswe see on television andmovies.

So what is AI really? Historically this subject has been called cognitivesimulation,andthatisprobablyamoredescriptivephraseforwhatishappening.AI is aneffort to simulate theactionsand responsesof an intelligent creature.Whywould a gamewish to have simulated intelligent creatures? To simulateotherintelligentcreatures,alliesandopponents,ofcourse.Atahighlevel,AIisused in games to implement other people performing intelligent tasks. Thesesimulatedpersons,sometimescalledbotsorsimplyopponents,areexpected tobehaveinamannerthatwouldbenormalforaperson.Theydonothavetobeactually intelligent, andadiscussionof thedifferencewouldbe interestingbutnotprofitablehere.

Atalower,morepracticallevel,theAIinagamekeepstrackofthings:cars,people,trees,roads,andsuch.OneofthemostimportanttasksoftheAIsystemistodeterminewhentwothingscollide.Thisisbecausecollisionsareoftenkeypointsinagame.Amissilecollideswithitstarget,andthetargetisdestroyed.Ahockey player collideswith another player and loses the puck.A car collideswithaconcretebridgesupportand takesdamageandchangesdirection.Alloftheserequirethatcollisionsbedetected,andthatthelocationoftheimpactanditsexacttimebeknown.

It is also true that a goodportion of the gameAI system can be occupiedwithperformingphysicscalculations.Afteracollisiontakesplace,theresultisthat something breaks, or changes direction, or falls down. A goodapproximation of real-world physics is essential for a realistic looking game,especiallyasportsordrivinggame,andaccuratelydeterminingthepropertiesof

Page 126: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

collisionsisacrucialfirststepincorrectlysimulatingphysics.A professional programmer or engineering student would have some

knowledgeof “academic”AI,which canbe avery exciting subject.However,thereisveryrarelyenoughtimetousethosemethodsinacomputergame.Yes,theremaybe time touse aneuralnetwork thathasbeen trained inadvance toaccomplish a particular task; therewill not be time to train such a network tohandlechangingsituations.AgameprogrammermusthaveapracticalviewofAI,andinagamethismeansspeedandsimplicity.Mostdecisionsinagamearemadeusingsimplelook-uptablesordecisiontrees.

AllofthepartsoftheAIsystemwillbediscussedheresoonerorlater,andthat includes opponents, collisions, plans, and physics simulation. However,we’llstartwithcollisiondetection,becauseitisthebasicthingthatwemustgetright. If a game includes collisions, then collision detection must be fast andaccurateifthatgameistobeplayable,andwecan’tadditonatthelastminute—itwillbeanintegralpartofthegamefromthestart.Therearepackagesthatwill do thehardwork for us, but it is alwaysdangerous to have code in yourprogramthatyoudon’tunderstandat leastsomewhat,soplease—at leastskimthis part before downloading someone else’s code.Having said this, there areentirebookswrittenonthesubject,andthischapterismerelyastartonsomeofthebasicideas.Youshoulduseanexistingcollisiondetectionsystemuntilyoufeelyouwanttodoitfromscratch.

COLLISIONDETECTION

Attheoutset, thenatureof theproblemneedstobeunderstood.Intherealworld,when twoobjects collide the result is aphysical response: sound,heat,energy transfer, and so on. In a game, objects are not real; they are numbersrepresentinghowanobject looksandwhereit is inavirtualspace.Whentheycollide,itisavirtualcollisionwithnoeffectunlesswedetectthatcollisionandsimulate an effect. This is one way in which computer games are in factsimulations.

There are two major problems associated with collision detection incomputer games. The first is complexity. A small game may have 100 or soobjectsactiveatatime.Iftheyareallmoving,wehavetolookateachpairtoseeiftheywillhiteachother,whichmeansabout100x100,or10,000tests.Wedothiseachtimeinterval,whichisusuallythetimebetweentwoframes—say24times per second. This implies a quarter of a million tests for collision persecondinasmallgame,andoveramillioninafair-sizedone.Anysolutionweimplementmustbefast.

Page 127: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE4.1Collisionsbetweenmovingobjects.Theycanoccurbetweenframes.

Thesecondproblemisthattimeinagameisquantized.Let’ssayweagainhave 24 images per second displayed on the screen, which is the speed of amotion picture. It is possible, even likely, that two objects approaching eachotherfastenoughwillpasseachotherinthetimebetweentwoframes,1/24ofasecond.Sotheywouldhavecollided,butattimeT=0.1theyweresomedistanceapart,andatT=0.2theyhadcrossedpathsanddidnotoverlapatthenewtime.Wecando two things in this case: lookahead (predict the timeatwhich theywillcollide)orlookback(tothepasttimewhentheydidcollide).Evenagamecan’teasily roll timebackward, so the formersolution isbest.Wemust figureoutwhen theywould collide, figure out the results of that collision, anddrawonlytheresultattimeT=0.2.Figure4.1showsanexampleofthissituation.

Just because two objects have changed places does not mean that theycollided.Each occupies an area, and they collide only if the areaswould alsooverlap at some time. This suggests a two-step test: first determine whethercollisionwas possible, then determinewhether it actually happened. In a realgame,mostobjectswillnotbeinvolvedincollisionsduringanyparticulartimeperiod,soafasttestthatrejectsmostpotentialcollisionswouldbeagoodthing.

Page 128: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

PolygonalObjectsIn somecaseswe are concernedwithmovingpolygonson aplane, and in

detectingcollisionsbetweenthese.Let’snametwopolygonsAandB,andgivethempositionsandvelocitiesat timeT.Aposition is a2Dvector, and so is avelocity,andeachcomponentofavelocityvectoristhespeedinadirection,XorY.SinceapolygoncontainsNverticesandallofthemaremovingatthesamespeedanddirection,wecaneasilydefineastraightlinethatcorrespondstothepath takenbyeachvertex in the timebetweenTandT+1.Wecan also easilycompute the position of all of these vertices at both times.A simple rule thatexcludesacollisionbetweenAandBis:IfwecomputealineLthatrepresentsthepathofavertexofA,thenacollisioncannothavetakenplacebetweenthatvertexofAandpolygonBifBisonthesamesideofthatlineatbothtimeTandT+1.

FIGURE4.2PolygonsAandBmoveinthedirectionofthearrowsbetweentimesTandT+1.IfanyoftheverticesofpolygonAareononesideofanyofthelinesL1,L2,orL3attimeTandareontheoppositesideofthesamelineattimeT+1thenacollisionispossible.

That doesn’t sound all that simple, does it? So, take a look at Figure 4.2.Hereweseeacoupleofpolygonsattwopointsintime,andwithanyluckatallthepreviousexplanationwillmakesenseinthecontextofthefigure.

Basically,ifanyoftheverticesofpolygonAcrossanyofthelinesL1toL3,thenacollisionmayhavetakenplace.Thisisthesamebasicmethodweusedforthe1Dsituation,andithasasimilarsolution.

ThelinecalledL1inFigure4.2iscrossedbythetriangleAifanyvertexis

Page 129: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ononesideofthelineattimeTandontheothersideatT+1.Everylinehasanequationthatdefinesit,andthiscantakeoneofmanymathematicalforms.Let’susethestandardnormalform

ax+by+c=0

Apoint(x,y)thatsatisfiesthisequationisontheline,andtherearetwootherpossibilities:ax+by+cisgreaterthanzero,inwhichcasethepoint(x,y)isabovetheline,andax+by+cislessthanzero,meaningthatthepointisbelowtheline.Thus,ifanyvertexisaboveL1attimeTandbelowitatT+1, thentherecouldbeacollision;otherwisetherecannotbe.

This is an example of broad phase collision detection, the elimination ofobjectsthatcannotpossiblycollide.Theideaistodothisquickly,withoutusinguptoomuchCPUtime.Thenextstep,orthenarrowphase,isaboutaccuratelydetectingcollisioneventsanddeterminingthetimeandpositionofthecollision.Breakingtheproblemintothesetwopartsisaboutperformance.Theideaistodo thedetailedand time-consumingnarrowphaseonly if there isachance theobjectscouldcollideinthefirstplace.Thishastheeffectofmakingthewholeprocessmoreflexibletoo.Therearemanywaystosolveeachproblem,andthesolutionsthataredecideduponcanbecombinedalmostarbitrarily.

AnExampleImaginetwotriangularobjects,asinFigure4.2.TriangleAisdefinedbythe

points(100,130),(110,150),(130,95)andhasavelocityof(200,30).TriangleBisdefinedby(300,65),(320,80),(330,65)andhasvelocityvector(-190,200).Question:couldtheycollide?

Step 1: select a polygon (in this case we select A) and determine theequationofthelinesdefinedbyeachvertexandtherespectivemotion.

Let’s take the first point in triangle A. The line it defines will begin at(100,130) and end at (100+200, 130+30) = (300,230) after adding themotionvector.Theslopeofthelineisfounddirectlyfromthevelocityvectorasdy/dx,orinthiscase30/200=.15.

Thepoint-slopeformofthelineequationisy=mx+b,andwecansolveforb:

b=y–m*xforthepoint(100,130)is130–0.15*100=130–15=115

Thismakestheequationy=0.15x+115

Page 130: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

andthestandardformis15x–y+115=0anda=.15,b=1,c=115

Step2:ForeachvertexintriangleB,pluginthexandycoordinatetotheline equationwe just found, before and after themotionof the triangle. If thesignoftheresultchangesforanyvertex,thenacollisionispossible.

Point1:before=(300,65)andafter=(110,265)Before:.15(300)–(65)+115=45–65+115=95After:.15(110)–(265)+115=16.5–265+115=-133.5

Thesignchanges,soacollisionispossible.Noneoftheotherverticesneedtobecheckedafteritisfoundthatacollisioncouldtakeplace.

Note:Whenfindingthecoefficientsforthestandardequation, if thelineisvertical then the slopewill be infinite, and thatwill cause an exception in theprogram.Thisisaspecialcase,andthecoefficientsare:

a=1b=0c=–x

BROADPHASECOLLISIONDETECTION

It is in this phase where the greatest saving of time can be created bycarefully selecting an algorithm and implementing it efficiently. This phase isabout rejecting objects that cannot collide, eliminating collision tests that costtimebutcannotyieldfruit.

“Operational”MethodsThe phrase operational has been used in a similar context with respect to

security. It representsanexaminationofhow the systemoperatesat ageneral,perhaps even superficial level, to see if efficiencies can be created or obviousflaws found. In operational security, for example, they may determine that acomputeroperator’sscreencanbeseenthroughawindow,andsothefirstthingto do in improving system security is to move the monitor away from thewindow.

Inagame,therearemanyobjectsthatcanbecollidingorcollidedwith,andthe general collision problem takes an amount of time to execute that is inproportion to the square of the number of objects (which a computer scientistwould callO(n2)). However, consider that many objects do not move, as has

Page 131: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

been pointed out before. If there are four cars, a hundred trees, and twentybuildings,thatis124objectsandupto15,376collisiontests.

However,testingAforcollisionwithBisthesameastestingBforcollisionwithA,andweneverneedtotestAforcollisionwithA.Thisreducestoatotalof (N2-N)/2 tests,which isa lot fewer thanN2. It is, in fact,7,626 tests in thepreviousexample.

Now consider that the trees do not move and so cannot collide with oneanother.Sameforthebuildings—theyarestaticandcannotcollidewithtreesorotherbuildings.Sothecarsneedtobetestedagainstallotherobjects,butthatisallweneedtodo!Thisrepresents4*3/2testsbetweencars(=6)and4*120=480tests with static objects, for a grand total of 486 tests. Any further efforts atbroadphasedetectionwillalmostcertainlynotyieldsuchsignificantsavingsbutcouldstillfindmoresavings.Similarly,objectsthataremovingawayfromeachothercan’tcollidewitheachother,norcanobjectsthatareveryfarapartrelativetotheirspeeds.

Most games have many classes of objects, and computation time can bereducedsignificantlythisway.Alienmissiles,forexample,neednotbecheckedagainstalienspacecraft,andsometimesasteroidsormeteorsneednotbecheckedagainst each other. It’s not as sexy as advanced code optimization, but a littlegoodsensegivesamuchgreaterbenefitthanalmostanythingelsewecando.

So,youshouldalwayslookverycarefully tomakecertain thatyouarenotmakinganytests thataren’tneeded.Thenyoudothemoredifficult thingsandcombinethetwomethodsforajointtimesavings.

GeometricTests

WhenwecheckedtoseewhichsideofthelinethestartandendpointofapolygonvertexwasonattimesTandT+1,wewereusinggeometrytoeliminatepossiblecollisions.This isaprettyefficientprocess,andwecando it in threedimensions too. In 3D, a line becomes a plane, and the test becomes: is aparticularpolygonornodeononesideofaplaneattimeTandontheotherattimeT+1?Ifso,acollisionispossible,andifnot,onehasbeeneliminated.

Inmoredetail,letusimaginethattwoobjectsinourgamearetobetestedtoseeiftheycollidewitheachother.Weknowthatwe’regoingtodrawobjectsascollectionsofpolygons, since that’showmodelingprogramsdefine them, andit’showgraphicscardsdrawthings.Sothequestionis:doanyofthepolygonsin set A (i.e., objectA) collide with any of those in set B (objectB)? Eachpolygonis, infact,apartofaplane.Amathematicalplaneis infinite inextent

Page 132: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

andapolygonisnot,butinthebroadphaseweextendapolygoninoneobjecttobecometheplaneinwhichitisembeddedandaskwhetheranyoftheverticesorpolygons in another object are on opposite sides at timesT andT+1. If so, acollisionispossible,otherwiseonehasbeeneliminated.

Thiscanbedonequickly,inamannersimilartothatalreadydescribedintheprevioussectionof2Dcollisions.TwotrianglesAandBhaveverticesA0,A1,A2 and B0, B1, and B2. Both belong to different moving objects, and thequestion of collision is at issue. Instead of just plugging coordinates into theequationofaplane,itispossibletousevectormathtodotheequivalentthing,butinamannerthatisfaster.

First, close your eyes and picture a plane—or a triangle or rectangle—floatingaboutin3Dspace.Threepointsdeterminethisplane;thatis,anythreepointsmustbelongtoaplaneinthesamewaythatanytwopointsareonalineandcanbeusedtodefineit.However,consideranypointonthatplaneandalinenot passing through that point; this, too, defines a plane.Most importantly, sodoes a point and thenormal to the plane. normalmeans perpendicular, or 90degrees to the surfaceof theplane,and ifwecanquickly findavector that isnormal to a polygon, and if we have a point on that polygon, we have theequationoftheplane.

It turnsoutthatasimple-to-calculateoperationknownasthecrossproducttakesanytwovectorsandcreatesavectorthatisperpendicular,ornormal,totheplane on which the two input vectors lie. For two vectors h and j, the crossproducthXjisavector:

Ifwehaveatriangle(oraquad,orcourse)thenwehavetwosuchvectors—anyedgeswilldo.

Thedotproduct,anothersimpleoperationonvectors,computesthelengthoftheprojectionofonevectorontoanother;forvectora,a.a=thelengthofa,andifaandbareperpendicularthena.b=0.Thedotproductisdefinedas:

Page 133: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

inn dimensions, and it looks like a simple distance calculation.Theusualformoftheequationofaplaneis:

c0x+c1y+c2z=d

GoingbacktothetrianglesAandB,notethateachvertexofA(i.e.,Ai)hasthreecoordinates,andis thereforea3Dvector.Thus,A0XA1=N isavectorcrossproductthatisanormaltothetriangle(plane)A.ThedotproductbetweenNandanypointintheplaneofA,sayanyvertex,istheequationoftheplane.So,A2.Nis:

d=NxA2x+NyA2y+NzA2z

whichhas the same formas the equationof plane.That’s because it is, ofcourse,anditistheequationoftheplanethatthetriangleAliesin.Thisiswhatwewant.WecanstoretheplaneasNandd,whicharereallyjusttheconstantsfortheequationoftheplane,andwedothisforeverypolygonwemaywanttotestforcollision.Testingisamatterofplugginginthe(x,y,z)valuesofthetarget(i.e.,whatweare testingforcollision, likeanotherpolygonvertex)beforeandaftermotion,andseeingifthetargetisonoppositesidesoftheplane.Ifsoweneedtolookfurther,andifnotwecanignorethistarget.

UsingEnclosingCircles

Twoobjects,let’ssaycars,mayconsistofmultiplepolygonseach.Ifoneofthem isEnzo’s car, and he is clever enough to pass yours in our race, it ispossiblethatmanyofthepolygonsinhiscarwillbecandidatesforcollisionwithpolygonsinyourcar.Thiscouldcostalotoftimeindetailedteststhatarenotneeded.Onewaytoavoidthis is toprocesscollisionsatahigherlevelatfirst,lookingatallofthepolygonsinyourcarasbelongingtoasingleobjectthathasavirtual shape—howabout a circle?So, if the circle that enclosesEnzo’s carneverintersectswiththecirclethatenclosesyours,thentheycan’thavecollided.Wecouldsavehundredsofpolygon-polygoncollisiontests!

Betteryet,theenclosingcirclecanbedefinedalongwiththecar,orwhateverobjectwe’re lookingat,once,when thegame is created.Allweneed todo isfindthecenterofthecircle,whichwouldbethecentroidoftheobject,andtheradius, the distance to themost distant vertex.The centroid of the carwill be

Page 134: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

whatweactuallymove;thecarisdrawnonthescreenrelativetothatpoint,andthecollisiontestsareinitiallyperformedonthecirclecenteredonthatpointtoo.

Thecentroid, or centerofmass, canbe approximatedby finding themeancoordinateofallpolygonsineachdimension.So,in2DtheXcoordinateofthecenterofmassisthesumofallpolygonXcoordinatesfortheobjectdividedbythenumberofpolygons,andinthesamewaytheYcoordinateofthecentroidiscomputed.Thedistancetothemostdistantvertexcanbecalculatedatthesametimeaswecalculatethecentroid,whichistosayatsometimeaftertheobjectiscreatedbutbeforethegameisdistributed.

Sonoweachobjecthasacenterofmassandaradiusassociatedwithit, inadditiontoasetofpolygons.Thequestionthatfacesusnowis:foreachpairofobjects that could possibly collide, is it possible for the enclosing circles tocollide?Ifnot,wecanignoreallofthepolygonsthatarepartofthoseobjects,andthatwillsaveusalargeamountoftime.Ofcourse,ifitispossiblethenwehavealotmorecheckingtodo.Sometimesitismoreusefultokeeptheobjectaspolygons, as in the case of walls and buildings. Covering them with a circlewouldbeawasteoftime,becauseit’seasiertokeeptheirrelativelyfewplanarfacesaslinesorplanes.

Spherevs.PlaneCollision(Circle–Line)

Thefirststepistoseeifthecirclechangessidesofthelineduringthetimeinterval. The situation is diagrammed in Figure 4.3: the circle at time T islabeledST, and its centerS = (Sx,Sy) is a distanceDT from the line and thepositiveside.AttimeT+1thecenterofthecircleisatDT+1,andthefigureisontheopposite(negative)sideoftheline.WemustmakesurethatDT>r,or thesphereisintersectingthelineatthebeginning.

A sphere is not a point; it has volume. For this reason the test concerningwhether a sphere may have collided with a polygon is a little different frombefore:ifDT>r,whereristhesphere’sradius,andDT+1<r,thenacollisionispossible.Asimplewayofcomputingthisis

dT=(ST-Z)·N

forsomepointontheplaneZandplanenormalN.If a collisionwith the plane occurs, when does it happen?We know it is

sometime betweenT andT+1, but exactly when?We can parameterize timebetweenTandT+1tobeoneunitusinganewvariableτ:

Page 135: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE4.3GiventhepositionofthesphereattimeTandT+1,didthespherepassthroughtheplane?

where τ is between 0 and 1. This ratio is the fraction of the distancedifferencebetweenTandT+1thatisrepresentedbythesphere’sradius,anditisthefractionofthedistancetraveledinthattimebythesphere.So,thelocationofthecenterofthesphereatthetimeofthecollisionis

x=SxT+τ(SxT+1-SxT)

y=SyT+τ(SyT+1-SyT)

z=SzT+τ(SzT+1-SzT)

where,asareminder,SxT is theXcoordinateofthecenterofthesphereattimeT,andsimilarlyfortheYandZcoordinatesandtimeT+1.

Circle-CircleCollisions

It is common for objects in a game to consist of polygons, but it is notuniversal.Aspritecouldbeasmallrasterimage,representingacaroraboatoran Italian plumber. In those cases, a collision would involve any pixel in thesprite collidingwith anyotherpixel in anotherobject.There couldbe a lotof

Page 136: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

pixel-pixeltests.Onewaytoaccommodatethiswouldbetoenclosetheimageina polygon, and then test the polygons for collisions. The bounding box orminimally enclosing rectanglewouldwork; sowould a circle, and circles areeasiertoimplement.

Theideaissimple:findthesmallestcirclethatwillencloseallofthepixels.Thetestforastaticcollisionisnowwhetherthecenterofthecirclesforthetwoobjectsiswithinadistanceofthesumoftheradiiofthecircles.Giventhatbothobjectsmaybemoving,thetesthastobeabitmorecomplicated.

TheproblemisdiagrammedinFigure4.4.Temporarilysimplifytheproblemtoassumethatoneobject(A)ismovingandtheother(B)isstationary;nowusethemovementvectorforA,usingthecenterofthecirclearoundA,tofindthepointonthepathoftravelthatisnearestthecenterofthecirclesurroundingB.ThispointislabeledcinFigure4.4.IfthedistanceofthispointtothecenterofB is greater than (or equal to) the sum of the radii of the two circles, then acollisioncan’thappen;otherwise,itcan.

FIGURE4.4Collisionsbetweentwocircles.ThepointcisnearesttothestationaryobjectB.Inthiscasethereisnocollision.

Todothis,itisnecessarytocalculatethepointonalinethatisnearesttoaspecified point. By nearest, we mean “what is the length of the line that isperpendiculartoagivenlineandpassesthroughaspecificpoint.”

FindingtheClosestPointonaLinetoaSpecifiedPointThisisreallyanextensionofthealgorithmthatfindsthepointofintersection

of two lines. Begin with a given point (px, py) and a given line segment,describedbyendpoints(x1,y1)and(x2,y2).

1. Take the endpoints of the line segment and turn it into an equation of theformax+by+c=0.Thiswehavedonebeforeintheprevioussection.

2. Theequationofthelineperpendiculartotheinitiallinesegmentisgivenbythe negative slope to the original line. Have it pass through the specified

Page 137: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

point:Specifically,-bx+ay–d=0.3. Solvethesetwoequationssimultaneously;thatis,findanxandyvaluethat

satisfies both. There aremanyways to do this, and any onewill do. Theresultis:

X=(ac-bd)/(a2+b2)

Y=(ad-bc)/(a2+b2)

If(a2+b2)=0,thenthepointisontheline,andthustheclosestpointonthelinetothepointisthepointitself.

Ifthepoint(X,Y)foundiswithinadistanceofthesumoftheradiiofthetwoenclosingcircles, thenacollisionispossible.IfBisstationarythenacollisionwillhappen.

UsingBoundingBoxesAboundingbox is a rectangleorprism that completelyenclosesallof the

polygonsofanobject.Thesidesareplanes,andthevolumeisrelativelyclosetothatof theobject—generally abetter approximation than is a sphere.AnAxisAligned Bounding Box (AABB) has faces that are parallel to the threecoordinateaxes.Thishastheadvantageofbeingverysimpletocalculate:runaplane through themostdistantpoint ineachcoordinateaxisdirection.That is,find theminimum andmaximumX coordinates in the object and construct aplane though these points that is parallel to the YZ plane; do this for the Ycoordinate (XZ plane) and the Z coordinate (XY plane), thus building arectangularprism.ThisistheAABB.

A really complex calculation is not needed to find theAABB.We simplyscan through all of the polygons for the object and note the minimum andmaximumvaluefoundineachdimension—sixvaluesinall.Ofcourse,thismustbedoneusingthepolygoncoordinatesintheworlddomain—thatis,asdrawninplaceinthescene.Oncewehaveminimumandmaximumvalues,itisasimpletasktousethesetodetectwhetheragivenpointisinsideoroutsideofthebox,and whether two boxes are overlapping. A point is inside the AABB if itscoordinatesaregreaterthantheminimumandlessthanthemaximumineachdimension.TwoAABBsoverlapifanyoftheverticesofeitheroneliesinsideof the other. Another similar test of overlap is: two AABBs overlap if theirextentsoverlapineachoftheaxes.Thisisquitefastandsimpletocompute.

This is, of course, not good enough. The two boxesmay pass completely

Page 138: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

thougheachotherandnottoucheitheratthebeginningortheend.Howdowe,asbefore,determineifacollisionhasoccurredinbetweenthe

startandendofthetimeinterval?Firstconsideraone-dimensionalproblem.Amoving1Dboxcanbe represented as two real numbers, s (start) and e (end),thatdescribethepositionoftheboxattwotimes.ThesetofallintervalscanberepresentedasalistLof(si,ei)values.Itwouldbebesttokeepthislistsortedinascendingorder.Whatweneedtodoisfindallvaluesof(si,ei)and(sj,ej)thatoverlap.

Wecreateafreshlist,initiallyempty,thatwillcontainentriesforallobjectscurrently“active”;callthistheactivelist.AswescanthesortedlistofintervalsL,anewsibeingencounteredresultsintheactivelistbeingoutputasapotentialcollisioninintervali,andtheintervaliisaddedtotheactivelist.WhenaneweiisseenwhilescanningL,intervaliisremovedfromtheactivelist.

FIGURE4.5Axisorientedboundingboxesforthreesimpleshapesinthreeorientations.Ontherightyoucanseetheboxesaloneandcomparetheirsizes.

ThegreatthingaboutAABBsisthis:toexpandthistothethree-dimensionalcase,wesimplyhavealistforeachdimension.Ifallthreedimensionsreportanintersection between AABBi and AABBj, they intersect, and a collision mayhaveoccurred.

AnewAABBmust be determined each time the object changes direction.This isanexpensenot incurredbyusingspheres,butweshallsee if there isacompensating trade-off. Another, more minor, problem is that the AABB cansometimesbeapoorfittotheobject.Consideratriangle,circle,andrectangleasinFigure4.5.AstheobjectsrotatetheAABBsfitmoreorlesswellinthebox.Thecloserthefitthemoreaccuratelythecollisionbetweenboxeswillpredictanactualcollision.

Page 139: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ObjectOrientedBoundingBoxesAn object oriented bounding box (OOBB) is always aligned along the

primaryaxesof theobject.Thisbox isdefinedwhentheobject is firstcreatedandis read inalongwith thepolygoncoordinatesorcomputedas it is read in.Theboxistranslatedandrotatedalongwiththeobject,andsoitshouldbeclearthattheedgesoftheOOBBwillnotnecessarilyalignwithanyaxis.

Whyusethese?Well,theyhuganobjectbetterthananAABBorasphere,ingeneral,asseeninFigure4.6.

Thismeansthatacollisioncanbemoreaccuratelydetermined.Ontheotherhand,ittakesalotmorecodeandtimetodeterminewhethertwoOOBBscollideornot.

FIGURE4.6Objectorientedboundingboxes.(left)Asarectangleisrotated,theboundingboxhasmoreemptyspace.Orientingtotheobject’sorientationreducestheerror.(right)Anaxisorientedboxindicatesacollisionispossiblewhereanobjectorientedboxdoesnot.

In theboat racegame that is theprincipal example in thisbook, there is aneedtodetectcollisionsbetweenboats.

There is an interesting thing here. It is true that a new AABB must becomputed each time the object changes direction, and this can be timeconsuming.However, a nifty idea is to construct theOOBB at the outset androtateand translate theboxwith theobject.Thiswillbedone in theboat racegame.

SpaceSubdivisionThe process of looking at every pair of objects to see if a collision has

Page 140: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

happened is slow, but if the objects are spread out over a large area, we canbreakuptheentireplayingvolumeintosmallpieces,eachlargeenoughsothatmovingobjectswon’tpasscompletelythroughone,butsmallenoughtocontainonly a few objects that could possibly collide. The basic idea is to check forcollisionsonlyamongobjectsthatarewithinthesamepieceofspace.

Thedata structure is simple, like the concept.Space is divided into equal-sizedblocks,andanarraycanbeusedtorepresenteach.Ablockcontainsalistof objects that reside in it, and at the beginning of each frame these are allclearedout.Thelistofobjectsisrunthroughandeachobjectisplacedintotheappropriatelist.Theblocksthatcontainobjectsalsohaveacountofhowmanyobjectsareinthatblock.Now,andfinally,welookthoughthelistofallblocksforthosewithmorethanoneobject—thosearetestedforcollisions.

If a game has a lot of 3D interactions, thismethod could require a lot ofstorage.Agamemostlytakesplaceonthegroundandonaflatishsurface,whichiswhatwecouldcall21/2dimensional.Bythisitismeantthatwewillconsidersquareson the terrainsurfaceandasmallvolumeaboveand ignore therestoftheplayingvolume,whichcan’tbedrivenon.

Thereareavarietyofusesand implementationsof theblockmapmethod,butinthecontextofatypicalgameitcanberestrictedinthefollowingways:

1. Anobjectwillbeinoneblock,asageneralrule.Thiswillbetheblockinwhichresidesthecenterofmass,orthecenteroftheenclosingsphere.

2. Thesizeoftheblockwillbesuchthattheobject,andanyotherobjectwithwhichitcancollide,cannotpassthroughawholeblockinonetimeinterval.Thismeansweonlyhavetocheckthestartingblockandtheendingblockintheworstcase,andinmostcasestheobjectwillstayinoneblock.

3. Wewanta reasonablenumberofblocks, so theymustbebigenough thattherearefewerblocksthanobjects.

4. Theremustnotbemorethanafew(4–5max)objectsinanyblock.

So,let’ssaythattheplayingareais2x2kilometers.Letthemaximumspeedofanyobjectbeahighlyreasonable100km/hr.At24framespersecondaframetakes1/24second,orabout42milliseconds.100km/hris28meters/second,or0.28meterspermillisecond,or1.176meters/frame.Thepreviousrulesgiveusthefollowinglimits:1. Theblockshouldbeatleastthesizeoftheobject.Acarisrarelymorethan

3meters long,andapersonisonly1meter.Let’ssaytheblockmustbeatleast3m.

Page 141: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

2. Inoneframeanobjectwillpass through1.176m,so3mis largeenoughthatitcannotpassthroughablockinoneframeat24fps.Ifwegetto60fps,we’llhavetomakeit2.94m.3misstillbigenough.

3. Therewillbeabout250objects in thegameatmost.3m is toosmall—atthis size therewill be over 100,000 blocks.At 250 objects, the block sizewillbeabout125meters.

4. At a block size of 125meters, we still want there to be fewer than 4–5objects per block that can be interactedwith. In some games an opponentwillsometimesbeveryclose.Ifwearecarefulabouthowweplaceobjects,ablocksizeof100metersshouldbefine.Thissizegivesusalittlelessroom,anditletsusputobjectsclosertogether.

Atablocksizeof100x100meters,afastobjectcanpassthoughinabout4seconds,butobjectscanbeplacedfarenoughapartthatittakesawhiletogettoone.Howmanyblocksare there then?10blocksperkmis20x20blocks,or400blocksalltogether.Thisisabitlargebutsmallenoughtobereasonabletosearch.Most,afterall,willbeempty.

Anotheradvantageofusingablockmapisthatonlythemovingobjectsneedtobeupdatedeveryframe.Everythingelseisplacedinitsblockatthebeginningofthegameanditwillremainthere.Amovingobjectcanbequicklyplacedinablock by mapping the coordinates of the object center onto block map gridcoordinates.Fortheprevious2x2kmmap,wefirstmaptheobject’s(x,y,z)coordinatesontoblockindices.Aneasyway:XcoordinateinKilometers/100=columnindex=JandthesamefortheYcoordinate,whichwewillcallI.

Each block is represented by a structure stored in a 2D array, indexed by(I,J).Eachstructurecontainsthenumberofobjectsinthatblockandindicatorsthatallowaccesstoeachobject.Thesecouldbepointersorindicestoanarrayofobjects.Ifacomplexstructureisusedtostorethem,itwouldbenoworsethanasimplelinearlist.Let’shaveamaximumofsix(6)objectsperblockandhaveafixed-sizearrayofindicesofobjectswithineachblockstructure.Tospeedthingsupevenmore,createagloballistofallblockscontainingmorethanoneobject.This, too,couldbeafixed-sizearray.Wheneveranobjectmoves,wecheck tosee if it stays in the same block. If not, decrease the object count for the oldblockand increase the count for thenewone.Remove theoldblock from thegloballistifithaslessthantwoobjects,andaddthenewoneifithasmorethanone.

Beforestartingcollisiondetection,addtheblocksatwhichobjectswillendupaftermotiontothegloballist.Next,lookingonlyatthegloballist,checkfor

Page 142: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

collisions between objects within every block in that list. Finally, update thegloballisttoremovetheblocksnolongerhavingmorethanoneobject.

NARROWPHASECOLLISIONDETECTION

Oncewedeterminethatacollisionispossible,thenextstageanswers“doesa collision occur?” If one does, at what point on the surface and in whichpolygononthemodel?Thisquestioncanrarelybeansweredasfastaswe’dlike,and never as fast as the broad phase question. And, as always, the moreaccuratelyweneedtheanswer, themoreexpensiveitwillbe.Thehopeis thatthisdetailedandexpensivecalculationwillnothavetobedoneveryoften.

Thereisawidevarietyofnarrowphasealgorithms,andanentirebookcouldbewrittenon this alone.However,wemust restrictwhat isdiscussedhere, soonly the most obvious methods will be examined. When a narrow phasealgorithmis invoked, it isbecauseacollisioncouldoccurbetweentwoobjectsthatconsistofpolygons.Theseobjectswereenclosedbyspheresorboxes,butnowwemustlookatthedetails.Let’sassumethatthepolygonsaretriangles—eachhas threevertices,and if theobjectconsistsof1,000 triangles, then therewillbe300vertices,right?

No,becauseinanobjectmostoftheverticesareshared.Anestimatewouldbe 1,000 distinct vertices in this object. Each vertex will move in a knowndirectionbyaknownamount, the so-calledmovementvector.Thismeans thatthereare1,000rays,ordirectedlinesegments,thatweneedtoexamine.Itcanbeassumedthatthesecondobjectisstill,becauseif itweremovingthenwe’dsubtract itsmovementvector frombothobjects togiveanetmovementvectoron the object being tested, as previously described where we checked forcollisionsusingspheres.

Sowehave1,000raysandasimilarnumberofpolygonsintheotherobjectwe are testing against. This would be a million tests, each ray against eachpolygon. It’spossible toeliminatesomeraysandsomepolygons though.Onlypolygons that are on the side of the object facing the other object need to betested,sowehaveperhaps500x500tests.Thisisstillasignificantnumber,but1/4ofthepreviousvalue.

Ignoringtheback-facingpolygonscanbedoneusingsomethingcalledback-face culling. Each polygon (triangle) has a normal associated with it, or wecould compute one every timewe need it. Now, back-face culling is really avisibilityalgorithm.Thequestionis:canyouseethatpolygonfromwhereyouarenow?Weusethedotproductbetweenthenormaltothetriangleandavectorfromtheviewer’spositiontogettheanglebetweenthesevectors;ifitisbetween

Page 143: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

90and270degrees, then thepolygon is facing theviewer;otherwise, it isnotand can be ignored. In this case, replace the viewer with the centroid of theobjectbeingtestedagainst,andthemethodisthesame.Ofcoursethismustbedone from both objects involved in the collision, each taking turns being theviewpoint.Therearetrickywaystospeedthismethoduptoo.

Ray/TriangleIntersection

The meat of the collision test is determining which polygons intersect,where, and when. From the previous discussion, we have selected somepolygons (perhaps all of them) to test against each other,wehave determinedwhat themovement vector is, andwe know that objectA ismovingwhileBremainsstill,orat leasthasbeenmadestillbycomputingarelativemovementvector.NowwewillselectverticesinAanddeterminetheirpositionsbeforeandaftermovement,thenseeifthatlinesegmentorrayintersectsapolygoninB.Ifso,itissimpletodeterminewhenandwherethishappens.So,stepbystephereiswhatwemustdo.1.Themovementvectorexpressesrelativemovement,sobyaddingittoapointwe find where the point moves. Vertices inA will be namedVA. They arenumbered from 0 to n, so they areVA0 toVAn; finally they havex, y, and zcoordinatesnamedVA0x,VA0y,VA0z,andsoon.ThepointV’isthesamepointasV,butitisapositionafterthemotioniscomplete.

TherayassociatedwithavertexVAi,giventhemovementvectorM,wouldbeavectorRfromVAitoVAi+M.Thisistosaythat

Rx=VAix+Mx

Ry=VAiy+My

Rz=VAix+Mz

ThelinethatneedstobetestedrunsfromVAitoR.CallthislineL,anditis:

Lx=VAix+(tRx)

Ly=VAiy+(tRy)

Lz=VAiz+(tRz)

Page 144: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

wheretrunsfrom0to1togiveanypointonthelinesegment.2.NowcomputetheequationoftheplaneinwhichtheselectedtriangleinobjectBresides.RecallthatweneedthenormalNandapointintheplanePtogettheplane:

Nx(x-P0x)+Ny(y-P0y)+Nz(z-P0z)=0

3.SubstitutethelineLintotheplaneequationfor(x,y,z)tosolvefort,thetimeatwhichthecollisionwilloccur.4.Usethevalueoftfoundin3toplugintothelineequationstofindthepoint(x,y,z)atwhichthecollisionwilloccur.5. Finally, determinewhether the point found in 4 resides inside the triangle.Thiscanbedoneinafewsimpleways.

Theinteriorangletest:compute theanglebetween thepointandall threetrianglevertices,inorder.Thesumoftheanglesshouldbe360degrees,withinroundingerror,ifthepointisinsidethetriangle.

The odd intersections test: draw a line from the point being tested to afarawaypoint.Ifthislineintersectsexactlyoneedgeexactlyonce,thenitis inside the triangle. If through some bad luck the intersection is avertex, then select a new direction and draw another line—a vertex ispartoftwoedgesandcan’tbeusedinthistest.

Areatest:Makealltrianglesbetweenthepointbeingtestedandconsecutivepointson the triangle—thereare three. If the sumof theareasof thesetrianglesequalstheareaofthebigtriangle,thepointisinside.Thistestisapproximate,partlyagainduetovagariesoffloatingpointarithmetic.

FIGURE4.7Thethreetestsfordeterminingwhetherapointisinsideapolygon.

Page 145: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

All of the five previous steps can be accomplished in a remarkably smalltimeperiodandareactuallydoneinmanygames.Youcanimplementanyorallofthecollisiondetectionschemesthathavebeendescribedusingwhathasbeensaidhere,combinedwithafewdetailsfoundontheWeb.

Or,youcouldusesomeoneelse’scode.TherearequiteafewpackagesthatcanbedownloadedfromtheInternetinafewminutes,andalmostanyofthemwill save you a huge amount of time, but they will require a degree ofadaptation.Aparticulargamemightnotbeabletousejustanysuchpackage.

COLLISIONDETECTIONINTHEBOATRACE

TheJetBoatRacepresentsa fewdifficulties thathavenotbeendiscussed,themainonebeing that the boats are raster sprites andnot polygonal objects.Imaginetwosmallimagesofboatsmovingatknownangles—theobjectorientedboundingboxcanbecreatedbyknowingthesizeoftheimageanddrawinglinesaroundit.Theselinesmustbedrawnatananglethatisrelatedtotheorientationoftheboat.

ConsiderthattheboatsarerasterimagesthatareNxMpixelsinsize,andthattheanglethattheboatisfacingisθ(tothehorizontal,whichis0degrees,facingright). Then the boat and the associated bounding box has to be rotated by θdegrees.Theboundingboxforthebasicimageiseasytofind,startingfromtheupperleftas(0,0),thento(width,0),(width,height),and(0,height).Whenthisbox is rotated by θ degrees, it can be seen as four line segments that are notnecessarilyoriented in theXorYaxis.Eachboathas suchanobjectorientedboundingbox.

Noweveryboathasavelocityvector,whichisaddedtothecurrentpositiontoyield thenextposition.Thisvector,whenextended in length,givesa ray(alinesegment) in thedirection that theboat is facing. If that ray intersectswithanotherboat’sboundingbox,thenacollisioncouldoccur.Itmeansthattheboatshouldchangedirectiontoavoidacollision.

If any of the sides of the bounding boxes of any two boats intersect, thenthoseboatshavecollided.ThismeanscheckingeachofthelinesegmentsoftheboundingboxofboatAagainsteachofthelinesegmentsoftheboundingboxofboat B. An intersection means a collision (Figure 4.8). This means testingsixteenlinesegmentstoseeiftheyintersect.

Theboundingboxesarefoundbylocatingthecornersoftheboatimageandthenrotatingthosetocorrespondwiththeorientationoftheboat.Theupperleft(ul),upperright(ur),lowerright(lr),andlowerleft(ll)cornersforboatsare:

Page 146: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE4.8Intersectingaxisorientedboundingboxesindicateacollision.

ul=rotate((boats[i].x,boats[i].y),

(boats[i].x-42,boats[i].y-13),-boats[i].angle)

ur=rotate((boats[i].x,boats[i].y),

(boats[i].x+42,boats[i].y-13),-boats[i].angle)

lr=rotate((boats[i].x,boats[i].y),

(boats[i].x+42,boats[i].y+13),-boats[i].angle)

ll=rotate((boats[i].x,boats[i].y),

(boats[i].x-42,boats[i].y+13),-boats[i].angle)

Thesepoints(eachisapointhavinganXandaYcomponentasatuple)nowhavetobeconvertedtoscreencoordinates:

ul=terrain_to_screen(ul)

ur=terrain_to_screen(ur)

lr=terrain_to_screen(lr)

ll=terrain_to_screen(ll)

Aboxconsistsoffourpoints,specificallythesepoints:

box.append([ul,ur,lr,ll,ul])

Afunctionnamedbox_intersect(b1,b2)checksfor the intersectionof thetwo boxes passed as parameters. It does so by doing the sixteen intersectiontests,eachofwhichisdeterminedbythefunctionline_intersect(a,b,c,d),where

Page 147: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

eachparameterisapointand(a,b)and(c,d)arelinesspecifiedbyendpoints.Afastmethod for determiningwhether two segments intersect has been devisedthatwarrantsexposure[1].

Thesegments(a,b)and(c,d)intersectifthepointsaandbareseparatedbythesegmentcdandalsocanddareseparatedbythesegmentab.Ifthatistrue,thenthethreepointsacdshouldhaveadifferentorientationthanthepointsbcd,whereorientationisdefinedasclockwiseorcounterclockwise.ThisisshowninFigure4.9.Thus,determiningtheintersectionisamatterof:

defline_intersect(p1,p2,p3,p4):

r1=ccw(p1,p3,p4)!=ccw(p2,p3,p4)

r2=ccw(p1,p2,p3)!=ccw(p1,p2,p4)

ifr1andr2:

returnTrue

returnFalse

wheretheccwfunctionreturnsTrueifthepointspassedasparametershavea counterclockwise orientation with respect to each other. This is remarkablyfast.Bytheway,thefunctionccwis:

defccw(a,b,c):

return(c[1]-a[1])*(b[0]-a[0])>(b[1]-a[1])*(c[0]-a[0])

FIGURE4.9Theideabehindthefastlinesegmentintersectionmethod([1]).

RayCasting

Page 148: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

If it can be assumed that each object that moves is associated with amovementvector(dx,dy),thenthisvectorcanbeusedtoprojectmotionintothefuture.Avectoror raycanbedrawnfromtheobject’scenter forward,and thegreater the length of this ray, the greater the amount of time that is beingexamined. The ray looks into the future to where the object might be. If ithappensthatthisrayintersectssomeotherobject,thenitwouldseemacollisionis possible, and perhaps the object should alter its trajectory to avoid theobstacle.

GivenamovementvectorV,thefirststepinbuildingaraythatpointsinthemovementdirectionisnormalizingit,whichmeansscalingitsoitslengthis1.ThelengthofVisL= sothenormalizedvectorV’is .Giventhat we want to look ahead by a distance D, nowmultiply this vector by D,givingthevectorR= .Therayis(x,y)toR,where(x,y)isthepositionoftheobjectconcerned.Ifthisrayintersectsanyobject’sboundingbox,thenacollision is possible in the future and action should be taken, such as steeringawayfromtheobstacleinvolved.

IftheobjectislocatedatP=(x,y),thentherayisthelinesegmentfromPtoP+R.Thefunctionline_intersectdefinedintheprevioussectioncanbeusedtodeterminewhether theray intersectswithsomeotherobject, like theboundingboxofanNPC.

Rayscanbeusedformorethingsthanthisthough.Itiscommontouseraycastingtoensurethatanobjectisincontactwiththeground,forexample.Castaraythatis1/2oftheheightofthetargetobjectdownfromtheobject’scenter.Itshould intersectwith thegroundor a supportingplatform. Indrivinggames, avehiclecouldleavethegroundforafewmoments,renderingitunabletobrakeorsteer; inplatformers,characters leapfromplatformtoplatform.Raycastingcanbeasimplewaytodealwiththeseissues.

EXERCISES

Thefollowingproblemswillexerciseyourknowledgeofthematerialinthischapter,andtheywillsometimesrequirethatyoudomoreresearchbeforeyouareabletocompletethem.1. In circle-circle collision detection, the distance between the two circles is

calculated, and if it is less than the sumof the radii, then a collision is inprogress.Simplecodewouldbe:

d=sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0))

if(d<(radius1+radius))//Collision

Page 149: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

where (x0,y0) and (x1,y1) are the coordinates of the sphere centers.A squarerootcalculation isexpensive—what is thecode thatdoes thiswithoutacall tosqrt?2. Writeaprogramthathastwoballs(circles)bouncinginabox.Usethecode

inexercise1 todeterminewhentheballscollidewitheachother,andhavethemreacttothecollision.

3. Writecode thatwillcheck foracollisionbetween twomovingcubes ina3Dspace.

4. Usethecode inExercise3 tocreateastackoffourcubesandhurla fifthcubeatthestack.Thesketchshoulddetectcollisionsbetweenthecubesandhavethemrespond.ApproximatebouncesareOK.

5. Some games, like snooker, are all about collisions. Write a sketch thatallowsawhite (cue)ball tobe shot inanydirectionona tableandcollidewithoneofasetof(atleast)twootherballs.Thecollisionsshouldresultincorrectseemingbounces.

Idea:When themouse is pressed, draw a line from the cue ball to themousecoordinates.When released, the cue ballwill follow the line at a fixed speeduntilitcollideswithacushionoranotherball.6. Using a circle for a ball and a line for a bat, construct a bat and ball

simulation.The batwill be rotating, notmoving linearly, and the ballwillmovetowardthebat.Youneedonlydeterminethepointofcollisionandtimeandneednotdeterminethelinealongwhichtheballwillmove.

Note: The point to line distance is key here, but the line is a segment, and aboundstestisimportant.

REFERENCES

1. Bryce Boe. (2006). Line Segment Intersection Algorithm.http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/.

2. A.BowyerandJ.Woodwark.(1983).AProgrammer’sGeometry.Newton,MA: Butterworth-Heinemann. https://www.amazon.com/Programmers-Geometry-Adrian-Bowyer/dp/0408012420.

3. E.G.Gilbert,D.W.Johnson,andS.S.Keerthi.(1988).“AFastProcedureforComputingtheDistancebetweenComplexObjectsinThree-DimensionalSpace.”IEEEJournalofRoboticsandAutomation4:193–203.

4. Gino van den Bergen. (2004). Collision Detection in Interactive 3DEnvironments.Morgan-Kaufman/Elsevier.

Page 150: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

5. M.LinandJ.Canny.(1992).EfficientCollisionDetectionforAnimation.ThirdEurographicsWorkshop.

6. Brian Mirtich. (1998). “V-Clip: Fast and Robust Polyhedral CollisionDetection.”ACMTrans.Graph.17,no.3(July):177–208.

7. Jeff Erickson, Leonidas J. Guibas, Jorge Stolfi, and Li Zhang. (1999).Separation-SensitiveCollisionDetection forConvexObjects. ProceedingsoftheTenthAnnualACM-SIAMSymposiumonDiscreteAlgorithms,327–336.

8. JulienBasch,JeffErickson,LeonidasJ.Guibas,JohnHershberger,andLiZhang.(1999).KineticCollisionDetectionbetweenTwoSimplePolygons.Proceedings of the Tenth Annual ACM-SIAM Symposium on DiscreteAlgorithms,102–111.

9. JoevandenHeuvelandMiles Jackson. (2002). “PoolHallLessons:Fast,Accurate Collisions between Circles or Spheres.”Gamasutra, January 18,2002.

10. Wolfram Research. (n.d.). Point-Line Distance, 3-Dimensional.http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html.

Page 151: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER5

NAVIGATIONANDCONTROLForthepurposesofthisdiscussion,navigationwillbedefinedastheprocess

ofgetting fromone location inagame toanother.Therearemanydifferencesbetween navigating the real world versus a virtual world, but a basic rule ofgameAI programming is: cheat! Remember that it is only important that thesimulatedcharacters(we’llcallthemnon-playercharactersorNPCs)appeartobehavemoreorlesslikearealperson.Theprogramthatcontrolstheopponentsdoes not have to navigate using vision, and it has advance knowledge ofeverythingthatisinthegame.Inaddition,therearemarkersthatcanbeplacedallthroughtheterrainthattheAIcanusetoguidetheNPCs.Thesemarkersarenot visible to the players because they are not rendered as objects—they aremerelypointsin3Dspacethatareusedtocreateapath.

Theopponentswill,infact,eithertakethesamepathatthesamespeedeachtime througha courseorwill atmosthavea finitenumberofvariations, eachonetakenwithaparticularprobabilitywhenencountered.Wecanevenchangethoseprobabilitieseachtimeachoiceismade,butthattooisprogrammedandwelldefined.Mostopponentsdonotactinanintelligentwaybutareguidedbyquitesimpleandquickalgorithms.

BASICAUTONOMOUSCONTROL

Thewordautonomousimpliesindependentoralone.Autonomouscontrolofopponentcharactersinagameisessentialformakingthegamefunandexciting,partly because it gives a sense of competition, and partly because othercharactersorobjectsareobstaclesandhavetobeavoided,thuscreatingamorecomplex problem to solve. If the opponents are autonomous, then they arecontrolledbysoftware,andsowetreat theproblemasoneofsoftwaredesign.Thefirstquestionis:whatistheproblem?

Anotherwayof asking this iswhat is thegoal?This is a questionwe canansweringeneral,atleastpartly.Thegoalofaplayerinagameistohavefun,andthismeanswinning,doesn’tit?Oddly,theansweris“no.”Winningagame

Page 152: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

regularly amounts to beating it, which frequently means that it is time topurchaseanothergame!Theentertainmentvalueisinthegameplay,thepuzzle,or the contest; beating a game too easily is the kiss of death, at least for acommercialgame.Wordwillgetout,andthegamewillnotsell.

On the other hand, if a game is impossible to beat, then it is just as bad.Playerssimplygiveup,andagainwordgetsoutthatthegameisimpossible.Westarttofindthemingaragesales.

Thus,wewillstateacarefullywordedhigh-levelgoalfortheopponentinagame:

Goal1-Sinceamaingoalofagameistoprovideentertainmentand engagement, the opponents should provide a challenge totheplayerwithoutbeingimpossibletodefeat.

This goal is vague enough to be a guide for any game, but too vague toimplement as is. However, it leads to a logical set of sub-goals that can beimplemented:

Goal1.aIfatallpossible,thehumanplayershouldbeatsomeopponentsifthere aremany. The player should not be humiliated by a computer iftheyarestillactuallyplaying.

Goal 1.b Some opponents should decrease their skill level as they get adistanceaheadoftheplayer,allowingachancetocatchup.

Goal1.cThegoalofanopponentisnottowin,buttoprovideentertainingcompetition. If the game involves objects, like weapons, the opponentmust be able to use them. It should play the game much as a humanwould.

Goal1.dWhentherearemanyopponents, theyshouldnotallbe thesame.Theyshouldhavevariableskilllevelsandshouldinsomesenserespondtothedisplayedskilloftheplayer.

Goal1.eTheplayershouldbeofferedachoiceofdifficultywhenstartingthegame,sothateasyopponentsareavailableaswellashardones.Theycanfindtheirskilllevelandstrivetoimproveit.

Most of these rules or goals are probably not a big surprise.Youmay notknowthattheAIsystemactually“dumbsdown”toletyouhaveabetterchance,but you probably suspected asmuch.Wewill add to this set of goals, but fornowwehaveenoughtogetstarted.Sincetheprecisenatureofthegamewearediscussingisunknown,we’llkeepthingsatahighlevelforthemoment.

Page 153: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

HowtoControlaCarLet’susetheexampleofacarinthediscussion.Therearesimilarmovement

controls and navigation features for cars and other NPCs, but vehicles havenavigation as one of the principal issues. The user controls a car using thekeyboardormouseorgamepad.Basically,thereissomethingthatcanbetreatedascharacter input and that canbe interpretedby thegameasacommand; leftarrowmeansturnleft,forwardarrowmeansgoforwardfaster,forinstance.Wecould control an opponent in the same basic way, except that we don’t needinput.So,wecouldhaveafunction

defturnLeft(CHARACTERx)

thatwouldturntheopponentrepresentedbyxleftbythestandardturnangle,inthesamewaythattheplayer’scarwouldturnbyangularincrements.Or,wecouldenhancetheopponentsbyallowingarbitraryrelativeangles

defturnRelative(CHARACTERx,floatdelta)

andevenabsoluteangles,forinstance:

defturnAbsolute(CHARACTERx,floatangle)

The idea is that a car is controlled using a set of very obvious primitiveoperationsthatcanbecombinedintohigherandhigherleveloperations.Wealsoneed accessor functions that return key values to the AI system, like a car’scurrentspeed,position,anddirection,sothatahigh-levelgoalcanbespecifiedintermsoflow-leveloperationsandcurrentparameters.

FIGURE5.1Thesimplesettrackandasetoflinesegmentsthatallowdrivingbehaviorsto

Page 154: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

bedefined.

Thehigh-levelgoalswillbeexpressedintermsofminorgoals,whichmayinturnbeexpressedintermsoflocalgoals,andsoonuntilatsomelevelthegoalis“go left,”which can be donewith a primitive. The designwould be from thehigh level downward, keeping in mind that the lowest level is pretty muchdefined at the outset. Let’s take a detailed look at one of the possibleintermediategoals:somethingcalledcruisingbehavior.

CruisingBehaviorThe goal of this behavior is to maintain a set speed, more or less, while

followingasettracktowardsageometricgoal.Itmayalsobeimportanttoavoidcollisionstoo.The“settrack”mentionedisapiecewiselinearpathdrawnalongthegame’sterrain,perhapsalongthemiddleoftheroadorracetrack.Figure5.1showsanexampleofthisandlabelsacoupleofinterestingobjectsandlocations.

The track can be identified as a connected sequence of straight linesegments,AB,BC,CD...FG.PointsAandBarepointsin3Dspace(Ax,Ay,Az)and (Bx,By,Bz) that define the ends of a line segment. The vehicle beingcontrolled is at a known position P=(x,y,z). It is, in the figure, the vehicle ismovingtowardthepointB;itisatadistancedfromthetrackandhasaknownspeedSanddesiredspeedSAB.Howdowekeepthecarontrack?

So long as the vehicle is moving in a straight line, things are relativelysimple.Theprogrammusttrytokeepthecarasneartothelineaspossible,anditwillattempttokeepthespeedasneartoSABaspossible.

s=getSpeed(THISCHARACTER)

if(s<Sab):#vehiclegoingtooslow

a=fmin(amax,k*(Sab-S))

elif(s>Sab):#vehiclegoingtoofast

a=fmax(amin,k*(Sab-S))

else:

a=0.0

s=a*dt+s

d=linePointDist(A,B,P)

if(d<RIGHTTHESHOLD):

turnLeft(THISCAR)

elif(d>LEFTTHRESHOLD)

turnRight(THISCAR)

This code does the following: there is a maximum and minimum

Page 155: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

acceleration,andifwearegoingtooslow,weincreasetheaccelerationalittle,uptothemax;ifwearegoingtoofast,wedecreasetheacceleration(increasethedeceleration)withthelimitbeingtheminimum.Wethencomputeanewvelocitybased on the calculated acceleration and the time since we last did this. Theconstantkisusedtoapportionaccelerationbetweentimeframes,anditshouldbedeterminedbyexperiment.

Thenwepayattentiontothesteering.Ifwearerightofthecenterlinebyalargeenoughdistance,thecaristurnedbyoneunittotheleft.Ifweareleftofthe center lineby a large enoughdistance,we turn to the right by aunit.Thesystemwillstraightenthesteeringangleautomaticallyoverthenextfewframes,butthereisariskofoversteer.Wecouldfixthatbyonlyadjustingthesteeringangleeveryfewframes.

AvoidanceBehaviorWhilecruisingitispossibletoencounteranobstacle.Inaraceitwouldnot

usuallybeawallor treeor the like,because theset trackwouldnotbeplacedwheretherewerenaturalhazardslikethis,butinanurbandrivinggameorwhenusingcharacterswhoarewalkingitwouldbecommon.Anobstacleonthetrackwill usually be another vehicle on the track ahead, presumably notmoving asquickly.AvoidancebehavioriswhattheAIvehicledoeswhenitcomesuponthissituation.

Thefirst thing tonote is thatotherAIvehicleswillbefollowingthe track,moreorless.That’sareasonthatthere’soneinyourway.So,thefirstsolutionistocreateanotherset tracktobefollowedinorder topassacarontheexistingtrack—let’scall theoriginalset tracktheA-trackandthenewonetheB-track.Somegamedeveloperswouldcall theA-track thedriving lineand theB-tracktheovertakingline.Figure5.2showsthisarrangement.

So,asavehicleV1approachesanothervehicleV0frombehind,itdetectsthepotential collision, notby traditional collisiondetection, butbynoting anothervehicleaheadonthedrivingline.V1switchestotheovertakinglineandsteerstowardthatline,thusavoidingthevehicleV0.IfanotherAIvehicleisalreadyontheB-track, thenwe simply slowdownuntil it is gone. In a game likeMarioKartwecouldalsosimplyspeedupandhittheothercar,lettingthecollisionsortthingsout—unlessV0istheplayer’scar,ofcourse.

Page 156: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE5.2SectionABoftheroaddefinedinFigure5.1,showingthedrivinglineandtheovertakingline.

IfV0istheplayer’scar,thenitsbehaviorisnotpredictable.IfV1changestotheovertakingline, theplayermayjustmoveovertoblock,but itcouldspeedup,slowdown,orhitsomething.Ratherthanhavingafixedovertakinglineinthiscase,wecouldcreateanewlinebyplacingatargetpoint inthemiddleofthelargestgap,eitherleftorright,betweentheplayer’scarandtheboundariesoftheroad.Thispointwillmovefromframetoframe,butitdoespresentatargettosteeratuntilV1getsveryclose.

ThespeedofV1needstobecontrolledtoo.InprincipleV1mustslowdownabituntilagapopensupthatisbigenoughtotakeadvantageof.TheAIcouldcomputethetrajectoryoftheplayerbasedonthecurrentparametersandfigureoutwhere theplayerwouldbe in3–5 frames. If thegap isbig enoughat thattime,V1couldspeeduptofillthatgapandforcetheplayertodecidewhethertocollidewithitortoavoidit.

ThisispartlyillustratedinFigure5.3.The use of the nodes or points that connect to create a path is generally

referredtoaswaypointpathfinding.Thewaypointscanbesavedascoordinatesina special structure, inwhich there isanextandapreviouswaypoint.Everyvehiclesavesthecurrentwaypointthatitisusing,theoneimmediatelyahead,initsownstructuresothatwedon’thavetosearchforthepointclosesttoit.Whenthe vehicle passes that waypoint, the next one becomes current. The use of

Page 157: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

waypoints eliminates the need for pathfinding algorithms in general, and itsimplifies the taskofkeeping theAIcarson the roadandmoving in the rightdirection.

FIGURE5.3Howtoreactifyoucomeupontheplayer’scarfrombehind.(a)Thenewovertakinglineusesthelargestgapbetweentheplayerandthesideoftheroad.(b)Iftheplayermovesovertoblock,itmerelychangeswheretheovertakinglineis.

In fact, there are a few ways to determine the path that an autonomousvehiclewill use to traverse the race course.One is to create a driving and anovertakinglineaswehavedescribed.Theotheris tocreateadifferent lineforeach AI car that can be on the track at the same time. Each car then has arelativelysimpletask—tokeepasneartoitsdrivinglineaspossible.Ifanothercarisinitsway,theysimplycollide,andthecollisionresolvestheproblem.Thecreationofmanydrivinglinesrequiressomeeffortupfront,butitsimplifiesthegameasitplays; thecars justdon’thavetobeassmart,becausethedesignershavedone thework.Mostgameplayersdon’t recognize that there isonlyonelinepercar,especiallyifthelinesareassignedatrandomatthebeginningoftherace.

Also,thedrivinglinescanbeassociatedwithotherinformation,likespeedateachpoint.Asaresult,thelinethatisassignedtoacardetermineshowwellthecar will do in the race. This practically eliminates the need for advancedcomputationswhilethegameisgoingon.

WaypointRepresentationandImplementationThefirstthingtorememberaboutwaypointsisthattheyare,basically,points

in 3D space. So the first thingwe need to keep track of is theirX,Y, and Zcoordinates.We also need a previous and next point, which can be stored aswaypoints.Oh,andingeneralwemayhavemultiplepreviousandnextpoints.

Page 158: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Let’sassumethatwewillhaveatmosttwoofeach;thiswillbeexplainedlater.Ithasbeenpointedoutthatwemaywanttospecifyaspeed.Thiswillbethe

desiredspeedatthatspecificwaypoint.Ifthepointisapproachingaturn,itwillbeinadecreasingsequence,anditwillincreaseonstraightsections.Itshouldbementioned that the actualAI vehiclemay not travel at that exact speedwhenpassingthoughthatwaypoint.Thespecifiedspeedisagoal.

Aclassstructurethatcouldholdthisinformationis:

classwaypoint:

floatingpointvariablesx,y,z,3Dposition

floatpointvariablespeed

listofwaypointsnext

listofwaypointsprevious

listoffloatsDnextholdingthedesiredspeedatthewaypoints.

Thesimplestway tousewaypoints is todirect thevehicles towardstraightlinesthatrunthroughthem.Ifwedo,thenthecarswillalwayspassthroughthewaypoints,andwillturnsharplywhenevereachoneisencountered.

Adifferentwaytomanagewaypointtrafficistoapproximateapathbetweenthemandtolookaheadmorethanonepoint.

FINITESTATEMACHINES

TheideathatanNPCcanbecruising,chasing,oravoidingisnotespeciallyprofound,andclearlydifferentbehaviorcanbeassignedtoeachmodeorstate.Itis also convenient from the perspective of design to be able to break up thedifferent behaviors into distinct parts, which can then be implementedindependently.Theuseof the traditionalcomputerscience tool, the finitestatemachine, isaprettynaturalwaytodealwith thiskindofsituation.Finitestatemachines,alsocalledFSAs,areusedinprogramminglanguages,computability,control systems, andartificial intelligence, andbecause theyhavebeenwidelyused,theirpropertiesarewellknownandefficientimplementationsabound.

WehaveseenthebasicideaofanFSAwhenimplementingthegamestatesinHockeyPong,forexample.ThebasicideaofanFSAisacollectionofstatesandoftransitionsbetweenthesestatesuponsomeinputorcalculation.Thestateshavenumbers,usedintheimplementation,andnames,usedbythedesignersandprogrammersasmeaningsofthestates.Inthesituationdescribedintheprevioussection,theAIvehiclestartsoutinthecruisingstate.IfitencountersanotherAIcar on the road ahead, it enters theovertake_AI state, and if it encounters theplayer’scar,itenterstheovertake_playerstate.ThebehavioroftheAIisquite

Page 159: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

differentineachstate,anditsgoalsandmethodsofachievingthemaredistinct.Figure5.4showsadiagrammaticrepresentationofanFSA,specificallyonefortheprevious three states. It is essential tohave a clearmechanism formovingbetweenstatesandaclearplanforwhattodowhileineachstate.

Mathematically,anFSAisasimulatedmachineormathematicalconstructionconsistingofasetofstates,whichareusuallyintegers,aspecialstatecalledthestartstate,acollectionofinputsymbolsorevents,andatransitionfunctionthattakesaninputsymbolandthecurrentstateanddecideswhatthenextstatewillbe.TheFSAbeginsacomputation in thestart stateandenters statesbasedoninput symbols/events and the transition function. There can be a special statecalled the accept state that can be used to decide when the calculation iscomplete.

So,ifweareinthecruisingstate(state0)andanAIvehicleappearsinfrontofus,weentertheovertake_AIstate(1);ifweareinthecruisingstateandtheplayer’scarappearsinfrontofusweentertheovertake_playerstate(2).Thesearetheonlystatetransitionsoutofstate0inFigure5.4.

Whileintheovertake_AIstate, thereareacoupleofevents thatcould takeplace.WecouldpasstheAIcar,orwecouldbeblockedfurther.Ifwepassthecar,wecangobacktothecruisingstateagain.Ifweareblocked—well,perhapsweneedanotherstatecalleddelayinwhichweslowdownandlookforachangeinthesituation.Thedelaystatewillbestate3.

Thedelaystatecanmeandifferentthingstodifferentvehicles,ifwechoose.Some carswill in fact slowdown and look for a gap throughwhich they cansneak.Otherinstancesofcarsmightaggressivelytrytopushtheirwaythrough,collidingwiththeiropponentsiftheyrefusetomove.Stillothersmightleavetheroad, if thatwere allowed, to try to find away around.Any of these optionscouldbeassociatedwiththesamestate,dependingontheactualvehicle.

FSAInPracticeImplementing a Finite StateMachine is a simplematter, so here are some

goodideasaboutstyleandconvention.Figure5.4willbeusedasanexample,asitissimpleandonthetopic.

First thing to notice is that the states are integers, from zero to somemaximum. They also have meanings and so can be given names. Thus, onegenerallydefinesstatesasintegervalues.Forexample:

Page 160: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE5.4AfinitestatemachineforAIvehicles.

STATE_CRUISE=0

STATE_OVERTAKE_AI=1

STATE_OVERTAKE_PLAYER=2

STATE_DELAY=3

Now we can define a state transition function. This function takes twoparameters:thecurrentstateandastatetransitionevent.ItresultsinthecurrentstatechangingasdefinedbythisparticularFSA.Thisnormallymeansthatstatetransitionevents,howevercomplexdetectingonemightbe,needtobeassignedintegerlabelsandnames,justlikestates:

TE_AI_CAR_AHEAD=0

TE_PASSED_AI_CAR=1

TE_2_CARS_AHEAD=2

TE_PASSED_PLAYER=3

TE_PLAYER_AHEAD=4

TE_ERROR_XXX=9

The error stateTE_ERROR_XXX is representative ofmanypossible errorstates, for example TE_ERROR_103, which means that some transitions areactually illegal and result in some remedial actionon thepart of theprogram.Also notice that the transitions are context sensitive; the eventTE_PASSED_AI_CARdoesdifferentthingsdependingonwhatstateyouarein.

Page 161: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Theactualmachinecanbeimplementedinanumberofways.Aparticularlygoodway,fromthepointofviewofefficiency,modularity,andportability,istouseatable.Transitionsareintegers,andthesecanbeusedtoindexintoanarray.Statesareintegerstooandcanalsobeusedasindices.So,astatetransitiontablefortheFSAinFigure5.4couldbe:

State0 1 2 3

0 11 0 2

Transition 2 3 3Event 3 0 1

4 2

Thistablecontainsstatenumbers,anditisindexedbyboththecurrentstateandatransitionevent.Soifweareinstate1(Overtake_AI)andwepasstheAIcar (event 1=PASS_AI_CAR), then we enter state 0 (Cruise), that is, anassignmentoftheform:

new_state=transition_table[TE_PASSED_AI_CAR][STATE_OVERTAKE_AI]

Themissingentriesinthetablewouldbefilledwitheithererrorstatesoranulltransitionmeaning“don’tchangethestate.”

This is an effective implementation of an FSA, but it relies on a correctinitializationofthetable.Ifthetableisreadinfromafile,itconsistsofintegersthat have no symbolic form, and this is somewhat error prone. If the table isinitializedfromadeclaration,itislesssimpletomodify,butwecannowusethedeclared state names. Either way we do it, the code is less clear than someoptionsandneedsgooddocumentation.

Anotherway to implement anFSA is to do so in discrete code.Theusualsituation is to just use if and switch statements. The first two columns of theprevioustransitiontablecouldbeimplementedinthefollowingway:

switch(state)

{

ifstate==STATE_CRUISE:

if(transition_event==TE_AI_CAR_AHEAD):

new_state=TE_PASSED_AI_CAR

elif(transition_event==TE_PLAYER_AHEAD):

new_state=STATE_OVERTAKE_PLAYER

elifstate==STATE_OVERTAKE_AI:

Page 162: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

if(transition_event==TE_PASSED_AI_CAR:

new_state=STATE_CRUISE

elif(transition_event==TE_2_CARS_AHEAD)

new_state=STATE_DELAY

elifstate==STATE_OVERTAKE_PLAYER:

if(transition_event==TE_2_CARS_AHEAD:

new_state=STATE_DELAY

elif(transition_event==TE_PASSED_PLAYER):

new_state=STATE_CRUISE

elifstate==STATE_DELAY:

if(transition_event==TE_PASSED_AI_CAR):

new_state=STATE_OVERTAKE_PLAYER

elif(transition_event==TE_PASSED_PLAYER):

new_state=TE_PASSED_AI_CAR

else:

error()

In this case there are no anonymous integers being used. All names aresymbolic, and it is a simple matter to read through the code to see what thetransitionsare.Thisimprovesthemaintainabilityofthecodeandallowsittobemoreeasilycheckedforcorrectnessonacasualbasis.

Bothofthepreviousimplementationscouldbeencapsulatedwithinasimplefunctionlike:

deftransition(intstate,intevent)

whichwouldreturnthenext(new)stategiventhecurrentstateandthenatureofthelasteventthatoccurred.Theimplicitassumptionis,bytheway,thattwoevents cannot occur within the relatively small time interval between twoconsecutiveframes.Thisisprettystandard,andwhathappensinpracticeisthatwesometimesgettwostatetransitionsinquicksuccessioniftwoeventshappenmoreorlessatthesametime.

Stateandthe“WhatDoWeDoNow”ProblemWenowknowhow tomove fromone state to another, how to implement

this,andwhatthestatesmean.Whatdowedowheninaparticularstate?Well,this is not a matter for the FSA to deal with. What needs to be done is todetermine what kinds of activities are associated with each state and thenexecutecodethatperformsthoseactivitieswheninthecorrectstate.Oh,andweneedalso toexecutecode thatdetermineswhetheranyof the transitioneventshasoccurred.

HereisageneralsketchofhowtheFSA-basedAIwouldfunction:

Page 163: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ifstate==STATE_CRUISE:

cruise()

elifstate==STATE_OVERTAKE_AI:

overtake_AI()

elifstate==STATE_OVERTAKE_PLAYER:

overtake_player()

elifstate==STATE_DELAY:

delay()

event=test_all_transition_events(state)

state=transition(state,event)

This program causes the game to change between the feasible states ascontrolledbytheeventsthathavebeendefinedbythedesignersandtestedforinthe function test_all_transition_events. By the way, this function can bequitecomplex,anditwouldprobablybeagoodideatotestonlyforthoseeventsthataresignificantfromthecurrentstate.Thisiswhythestateisaparameter.

OtherUsefulStatesItisimpossibletodescribethestatesthatadrivinggamecanbeinwithout

knowing thedetailedcontextof thegamebeingdiscussed.However, there arecertain options that can be seen to be commonly useful. This includes thefollowingstates:

Start:

In driving games, it is common to have a race beginwith all of the cars in predetermined startpositions.Thecarsarenotmoving,andinfactmaynotmoveuntilthestarterfiresagunorwavesaflag.Theythenacceleratetothedesiredspeedandselectadrivingtrack.ThisdescribesastatewecouldcalltheStartstate.Insomegamesthereisanactualcountdowntothestart,andiftheplayerstartswithinaspecifiedtimeoftheactualstarttime,hegetsaspeedboostforafewmoments.ThiscanbedoneforAIcarsaswell, but because theAI systemknows exactlywhen the startwill take place it could easilycheat—actually, it’shardnot to.So,a random time isgeneratedat the start, andanyAIvehiclewithastarttimebelowthethresholdisgivenaboost.Normally the Start state would change to Cruise when a certain speed had been achieved or aspecifictimeintervalhadexpiredandthecarhadbeenassignedatrack.

Air:Acarthathitsabigbumporcrestsahillatahighspeedmayactuallyleavethegroundforafewseconds. This has a few consequences: the engine usually revs up to a high value, causing theenginesound tochange.Theacceleratorpedalhasnopracticaleffect—thecarcannotaccelerateforward nor brake. The car cannot change direction, as the wheels are not in contact with theground,anditcannotbesteered.ThiscouldbedescribedastheAirstate.There should be a specific sound that is playedwhen leaving the Air state, that of the wheelshittingthepavementwhilespinning—acombinationbumpandscreech.ThenweenterthestatewewereinbeforeenteringtheAirstate.

Damaged:Vehiclescanbecomedamagedinmanyways.Thesimplestwayistocol-lidewithanothercarorwithastationaryobject,butsomegamesinvolveweaponsthatcaninflictdamageorprocessesthat

Page 164: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

cancausethevehicletodeteriorate.Damagecanresultinaninabilitytoperformnormaltasks,likesteeringorbraking. It can reduce the top speedor the ability to switch tracks.So theremaybemanydamagedstates,perhapsevenoneforeveryother“undamaged”state.Thatis,thereshouldinsomecasesbeacruisestateandacruise_damagedstate,anAirandanAir_damagedstate,andsoon.Inthecruise_damagedstatethecarmaynotbeabletoreachtheprescribedspeed,butitshouldstillbehaveinthesamebasicwayasinthecruisestate.Beingdamagedmay also restrict the states that thevehicle can change into.For example, fromcruise_damageditmaynotbepossibletomoveintotheovertake_aiorovertake_playerstatesortheirdamagedequivalents.Perhapsadamagedcarshouldnottrytopassanothervehicleintheraceoratleastonethatisnotalsodamaged.From a damaged state the car should change into the equivalent non-damaged state when it isrepaired;so,wegofromcruise_damagedtocruise,forexample.Attacking:In combat or combat driving games, an attack can take a number of forms, from simply firingmissilestoanintentionalcollisionoranattempttopushanothercaroffoftheroad.TheattackingstatecorrespondstotheAI’sefforttodamageanothercar,perhapsanotherAIcarortheplayer.Thedifferenceinbehaviorbetweenattackingandcruisecanbeprofound,sincetheattackingcarhasaquitespecificgoal—todestroyanopponent.Theattackingstatemayrequirethatavehicleactuallychaseacar,beittheplayeroranotherAIcar.ThisisquiteadistinctchangefromtheusualcruiseorOvertake_AIstateinwhichthegoalsaresimplytomakegeometricprogress.Defending:IfanAI realizes that it isbeingattackedorchased,and theremustbeacarefullydefinedsetofcircumstancesthatdeterminewhenthatis, thenitscarcanadoptastrategyofavoidance,hiding,andperhapshigh-speedescape.Theseactionscharacterizedefendingmodeinthosegameswheresuch conflicts are possible. The goal is obviously to hide from or destroy the attacker, and thepreviousgoalindicatedbythepreviousstateistemporarilyforgotten.So,whentheconflictisresolved,thevehicleshouldreturntoitspreviousstate.Unfortunately,thechasecouldresultinthevehiclebeingquitealargedistancefromwherethechasebegan,movinginthewrongdirectionfortheoriginalgoal.So,itmaybebesttomovefromdefendingtocruiseandthenhavethesystemmovebetweenstatesbasedonthenewlocalconditions.Searching:Somegameshaveobjectsthatmustberetrievedduringthecourseofthegame,andinothercasestheopponentsaremovingaboutandyoumust find them.Searchingbehavior is like thatof thecruisestate,but thegoalsareabitdifferent.Thereisoftennogeographicgoal in thesearchingstate,onlyanobjectiveone—tolocatesomething.Thus,thedrivingbehaviorwouldresultinlargeareasbeingcoveredandaminimumofbacktrackingorrevisiting.Itwouldbereasonabletodefinesearchingtracksasadesignfeatureofthegame.Likeadrivingtrack,thesewouldbedefinedbywaypointsandwouldhavethegoalsofthesearchbuiltintothelayoutofthosewaypoints.TheAIwouldthenhaveless“thinking”todo,needingonlytofollowthewaypointsblindly.Patrolling:Patrolling behavior is very much like searching; indeed, patrolling can be called searching fortrouble.Thinkofapolicecaronwatch,drivingthecityatnight.Thisispatrolling,anorganizedrandom route through an area. It should be random in practice so that bad guys cannot predictwhereyouwillbe,ofcourse.Whetheritistrulyrandominthegameisuptoyou,thegamecreator.Thenatureofwhatisbeingsoughtisalsoabitdifferentfromthatseeninsearchingbehavior.Itispossiblethatapatrolisseekingaparticularperson,inwhichcaseitmaybethesameassearching.Itmayalsobe that thepatrolseekscomplexbehaviors that indicateacrimeinprogressorsomeformof enemy activity.This is harder to identify, and it requires some careful definition of thegoalsinadvance.Forexample,speedingissimpletospotsincetheAIalwaysknowshowfastallobjectsaremoving.Anillegallanechangebytheplayermaybemoredifficulttospot.

Page 165: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Skidding:Whenacartriestoturnacornertoofast,thewheelsslideontheroad.TheytrytokeepmovingintheiroriginaldirectionasindicatedbyNewton’slaw.Wecallthisaskid,anditmaybeusefultodefine a skidding state. This state is characterized by a lack of control, so steering will workdifferentlythaninotherstates.Turningintotheskidmaytendtoaligntheaxisofthecarwiththedirectionofmotion,butthecarcontinuesinmuchthesamedirectionasbefore.Turningawayfromthedirectionoftheskidwilltendtogivethecararotationalvelocityaboutitscenter,againwithoutchanging the direction ofmotion of the car verymuch.Brakingmaymake the skidworse, butslowingdownwouldpermitthewheelstograbthepavementandgivecontrolback.Itisacomplexsituation, but anyonewho has been in a skid knows one thing—the original driving plan, be itgoingtothestoreorgettingtowork,goesoutthewindowinfavorofjuststayingoutoftheditchandgettingcontrolback.

Stopping:TheAImightneedtostopthecarfromtimetotime,perhapstopickuppassengersortocollectanobject.Acarcannotstopinstantly,anditmaybenecessarytopullovertothesideoftheroadtoavoidbeingsmashedinto.Thisstoppingbehavior iscertainlyneeded insomegames, includingtheonewearegoingtodiscussandbuildlater.Itisnecessarytoenterthestoppingstatewellaheadofthepointwherethecarwishestostop.Thegoalistostopataparticularplacetoconductanactivity,andsothatplacemustbeidentifiedinadvance, and the car needs time and space inwhich to slow down.Again, we’ll need rules todictatehowfarawaytochangestatesgiventhecurrentvelocityanddirection.

PATHFINDING

Until this point the assumption has been that an NPC exhibits a specificbehaviorbasedonwhatishappeninginthegame,butsometimesanNPChasaspecificdestination,andsometimestheNPCbehaviorisexpressedintermsofadestination. Patrolling behavior, for example, may well consist of a set ofwaypoints tobevisited insequence. Instaticsituations thiscanbehandledbyfixedwaypoints, but if obstacles can be placed in the way, then the situationbecomesmorecomplex.

AfullAIsolutionwouldbe todiscoverapath to thenextwaypointon theNPC’spath.Therearemanysuchpath-findingalgorithms,includingthefamousA* algorithm that we’ll mention soon. If the NPC is blocked by a movableobjectbutisstillrelativelynearitspath,itmightbepossibletosimplymovetoanearbylocationandthenbacktothepath.A*attemptstofindthe“best”routeaccordingtosomeheuristic,usuallybasedontheshortestdistance.Asaresult,A*canbemoretime-consumingthanwemightlike,giventhatagameexecutesinrealtimeandhasratheralottodo.Whatwouldbeacceptableisalessthanoptimalbutstillfeasibleroutethattakeslesstime.

Onepracticalideaistouseapredefinedgridofdirections,indexedbyusingthe vehicle’s current position. This grid could be relatively coarse, containingperhapsafewthousandentries,anditshouldmapontotheterrainofthegame.Entries in this grid, easily implemented as a two-dimensional array,would be

Page 166: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

directions: eithervectorsor simply compass angles.Thegamedesignerwouldhavetofillinthevaluesateachlocationinthegridwiththedirectiontosteertoget back to the road or path.This is the usual trade-off: tomake themachineseemclever, a personhas todo a lot ofwork in advance, just aswedidwithwaypoints. The other traditional trade-off in computer work is that of spaceversustime,andthatcanbeseenheretoo.Inordertospeedupthepathfindinginthissituation,abunchofextrastoragespaceisused(thegrid).

FIGURE5.5Useofadirectionalgridtofindaroutebacktoaroad.

Ifthismethodisused,thesequenceofstepsis:

1. Findthegridelementthatcorrespondstothecurrentlocationofthevehicle.Iftheplayingareais1000x1000yards,forexample,wecouldbreakupthisarea into 25 x 25 grid elements, each being 40 yards square.Locating thegridisamatterofdividingthe(x,z)coordinatesby40andtruncating.

2. Steer in thedirectionsaved in thegridentry.Thiscouldbeabytevalue tosavespaceandcouldbe in fairlycrude terms,sincewesimplyhave togetbacktothepath,notfindthebestroute.

3. Usea lowspeed, sincewe’reoutof the race for themomentanyhow.Theonly obstacles that are a problem aremoving ones, since the gridwill bedesignedtoavoidstationaryobjects.Wecouldstoreasuggestedspeedalongwiththedirection,againcrudelyquantized.

4. GridelementsthatarenearapathcouldcontainaspecialvaluetoindicatetotheAIthatthecarshouldnowbeallowedtocontinueinitsusualmode.

Page 167: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Figure5.5showssuchagridinasmallexample,andthisexampleactuallyhasobstaclessothatitiseasytoseehowthegridisbuilt—directionsarechosentosteerthecartowardthepath,notalwaysdirectlyatit,butsometimesaroundstaticobjects.Asthecarmovesfromonegridtoanother, itadjustsitssteeringdirectiontothenewgriddirection.

Thus, anywhere that the vehicle ends up after a collisionwill have a gridentrythatdirectstheAIhowtocontrolthecar.

A*SEARCH

TheA*algorithmisamethodforsearchingthroughasetofstatesforagoodone, one that should lead to the solution of a problem.This is a pretty vaguestatement,butA*canbeusedforquiteafewdistinctkindsofprobleminAI,soitmakessensetobevague.Intermsoffindingapath,astatewillbeasituationthat has a position identified that is unique and is associatedwith a positionalgoal,atargetpositionwearetryingtogetto.Wealsoneedawaytodetermineacostassociatedwithpositions;intermsofpaths,acostmaybehowlongitwilltaketogettothegoal,orhowmuchfuelitwilltake.Thecostofmovingfromone position to another may well be connected to the terrain. Mud will costmore,andsowillsteepinclines,whilepavedroadswillprobablycosttheleast.TheideabehindA*istocreateamethodfordeterminingwhichroutecostsleastwithoutexploringallofthepossibilities,whichcouldbequiteexpensive.

It is important to realize that inorder touse theA*algorithm, theplayingareamustbedividedupintoagrid,likewedidbeforewhenusingthedirectionalgrid.Eachgrid element corresponds to a discrete state andhas a value that isrelatedtothestartandgoalstates.EachofthesegridelementsiscalledanodeinA*terms.Eachnodehasacostassociatedwithit,whichisrelatedtohowfaritisfromthegoalorhowexpensivetherouteisfromthatpoint.

Thereareacoupleofobviousthingstonoticebeforewegettoofarintothedescriptionofthemethod.Thefirstthingisthatitislogicaltoreducetheamountofcomputationthatisdonebyrememberingthecostassociatedwitheachnode,and not recomputing it. Next, wewish to keep a collection of nodes that arecandidatesforthenextoneinapath.Agoodwaytodothisistohaveasetofnodeswhicharepossiblenextones:thisistheopenlistoropenset.Wewillalsohave a list of nodes that do not need to be considered, possibly because theyhavealreadybeenexamined.Thisistheclosedset.

TheA*algorithmisimportantenoughingamesandAItospendafewpageson,andapicturecanbeveryvaluableinexplaininghowthingswork.So,let’swalkthroughanexamplethatillustratesthemethod.Hereisthegridthatgives

Page 168: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

thesituation:Thefirst thingtodoistoaddthenodeS totheopenlist,sinceweneedto

consideritasthe0thstepinthepathtothegoal.Theopenlistshouldbesortedsothatthenodewiththesmallestvalueofthetotalcostfunction(whichwewillcallF)isfirst.ThefunctionFisascoretraditionallycomposedofthesumofthefunctionG,whichishowmuchitcosttogettothisnode,andH,theestimatedcost for the remaining nodes between here and the goal. SoF=G+H, and itseemsasifHisimpossibletocalculate.

FIGURE5.6InitialsituationintheA*example.

Giseasy—eachtimewemovehorizontallyorverticallytogettoanodeweadd 1 to the value of H for that route, and we add the square root of 2 fordiagonal steps if they are allowed. To make the calculations a bit faster, wemultiplyby10andconvert to integers, since integermath ismuch faster thanfloatingpointmath—sohorizontalorvertical steps cost10anddiagonal stepscost14.

How do we determine H? A common way is to use the 4-distance orManhattandistancebetweenthatnodeandthegoal.Thisissimplythenumberofrowsbetweenthenodesaddedtothenumberofcolumnsbetweenthem.

AfterShasbeenaddedtotheopenlistandFiscomputed,hereistheresult:

Page 169: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE5.7Initializationforstep1ofA*.

Next:wetakeoneofthenodesfromtheopenlist—theonewiththesmallestFvalue.Rightnowthere’sonlyonenodeintheopenlist,S,sonoproblem.NowaddallofthenodesthatneighborStotheopenlistandmoveStotheclosedlist.ComputeFforallofthenewopenlistentries.

Remember, left-right and up-down neighbors are a distance of 10 fromS,anddiagonalneighborsareadistanceof14.AsamplecalculationofF for thenodeatB7is:

H=distancetogoal=10*(6+7)=130G=accumulateddistancefromS=10F=G+H=130+10=140

Wedothisforalleightneighborsintheopenlisttoarriveat:

FIGURE5.8Afterstep1ofA*.

Onemorething.Wheneveranodeisaddedtotheopenlist,wemakeanote

Page 170: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ofhowwegotthere—itistheneighborofanodethatwasonthepath,andthatnodeistheparent.Wealwaysremembertheparentofanode,becausethat’showwetracetheroutebacktothestartwhenthemethodisdone.

Let’sdothenextstep.WepickthenodeintheopenlistthathasthesmallestvalueofF—inthiscasetheC7node—andputitintotheclosedlist.Thewestartexaminingitsneighbors.Wemustignoresquaresthatcan’tbetraveledon,sotheblackonesthatrepresentanobstacleareignored.Alsoignorenodesintheclosedlist.ClearlytherearejustfournodesthatarelegalneighborsofC7:C8,B7,B6,andD8.Addthesetotheopen listiftheyarenotalreadythere.C8andB7arealreadythere,sowedon’taddthen,butwedochecktoseeifthevalueofFforthesenodesissmallerthanitwasbefore;thatis,isthepaththatgoesthroughthenodeC7betterthantheonethathasbeencomputedalready?Ifso,changetheirparent toC7 and theirFvalue to thenewone; otherwise, donothing.For thenewnodesB6andD8,addthemtotheopenlistandcomputeFvalues.

FIGURE5.9Step2ofA*.

Nowdoitagain.ThenodeintheopenlistwiththesmallestFisB7.Moveittotheclosedlistandplaceitseligibleneighborsintotheopenlist.Thereareonlytwonodesof interesthere:nodeA6 isnewand is added to theopen list.ThenodeatB6isonethatisalreadyintheopenlist,buttheexcitingthingaboutitisthat the value of F computed through the new parent is smaller than the old.Therefore,wechangeparentstoB7andadjustitsFvaluetothenewone,140.Thenewsituationis:

Page 171: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE5.10Step3.

Andsowecontinue,pullingouttheopennodewiththesmallestF,puttingitintotheclosedlist,andputtingitsneighborsintotheopenlist.

Whendowe stop?First,when theopen list is empty.Thismeans that thegoalcannotbereached.Theotherterminationconditionisthatweaddthegoalnode to theopen list.We trace thepathofparentsback from thegoalnode toreadoffthesequenceofnodesinthe“optimal”route.

Thealgorithm,insummary,is:

1. Createstartandgoalnodes.2. Placethestartnodeintotheopenlist.3. Repeatwhiletherearenodesintheopenlist.4. SelectthenodePfromtheopenlistwithsmallestFvalue.

PlacePintheclosedlist.5. ifP=goalthenwequitwiththesolution.6. foreachneighborNiofP7. ifNiisunusableorintheclosedlistthencontinuefrom6.8. LetthecostofNi=H(Ni)+distancetoP.9. IfNiisnotintheopenlistthenaddit10. elseifNiisontheopenlistandthepathhasalowerF11. thenchangeFtothenewvalue,changetheparentofNitoP.12. endofFOR13. endofrepeat14. Iftheopenlistisempty,thereisnopathtothegoal.

Did you forget what we were doing? Now we have a path from the AIvehiclethatwasknockedfaroffofitspathbyacollisiontoawaypointthatison

Page 172: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

theoriginalpath the carwas following. Inotherwords,wehave away togetbacktothe“normal”situationafterbeingknockedoffthepath.Thepathfoundintheexampleis:

Thecellsmarked“.”wereneverused.Thepathrunsfromthecellmarked0totheonemarked158andfollowsthelightergreyvalues.

STOCHASTICNAVIGATION

Theword“stochastic”means“havingarandomcomponentorelement,”andthat’sreallywhatiswantedfromambienttraffic.Ifyoulookattrafficfromthetopofabuilding,theindividualvehiclesbehavebothpredictablyandrandomly—theypredictablyobeytrafficrulesbutfollowwhatlookslikearandomroute.That’s because we don’t know where the cars are going. They all have adestination,butwithoutknowingwhatitiswedon’treallyknowwhatacarwilldoatthenextintersection,andespeciallyattheintersectionthreeblocksdown.Wewantthetraffictolooknatural,andwedonotwantallcarstoturnleftat5thstreetorhavethesamecarsgoaroundthesameblockforthewholegame.

So,eachcarshouldhaveaplanforatleastthenextchoice.Ifacarisgoingto turn left, it makes sense that it should get into the left lane before theintersection. Each vehicle in traffic should have a shortterm plan which isupdatedeverytimeitexecutesaplannedmovelikeaturn.Theplanisrandom,so it is basedon the drawingof randomnumbers.Themost likely event is todrive straight through an intersection, but left or right turnshave a finite non-

Page 173: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

zeroprobability.Forexample,wecouldhave:

Straightthrough 80%chanceLeftturn 9%chanceRightturn 9%chanceRightnextalley 1%chanceTurnintonextaccess 1%chance

Now draw a random number x between 0.0 and 1.0. The code for thepreviousis:

if(x<0.8):

plan=GO_STRAIGHT

elif(x<0.89):

plan=TURN_LEFT

elif(x<0.98):

plan=TURN_LEFT

elif(x<0.99):

plan=NEXT_ALLEY

else:

plan=NEXT_ACCESS

Ifthecarentersaparkinglot,itshouldpark.Thisactivityislikelyinitiatedbyafinitemachinestatechange.

Itisimportanttorealizethatthetrafficneedsonlytobehaveproperlysolongastheplayeriswatching.Indeed,it takestimefortheAItomovethevehiclessensibly,andifwecanavoidtakingthistimeitwouldbegood.Shouldwecreatetrafficwhenitbecomesvisible?Thatis,whentheplayer’scarturnsacorner,doweneedtoinventsomecarsandplansforthem?

Thatiscertainlyanoption,butitwouldcauseaproblemincaseswheretheplayerchoosestoexploretheenvironment,especiallyifhedoessobyfollowingambienttraffic.Imagineturningacornertofindthatthecarsyoujustsawhavevanished.No, it is probablybetter to havemoreof the traffic be inactive (notmoving) until iswithin a specific radius of the player.Naturally, if the playerstays inoneplace too long, the traffic inhisneighborhoodcouldvanish—asitleavestheactiveradiusitstops,andnothingcanstartupuntiltheplayermovescloser.

Things are getting complicated. So, whatmaywork is to give someCPUtimetomovingambienttrafficonceinawhile,eachfewframes.Iftheplayerisidle, there isgoing tobea lotof free time togive to this task.So, if traffic is

Page 174: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

withinaradiusof,say,fiveblocksoftheplayer’scar,itwillgeta“turn”(afewcycles)eachframeformovementcontrol.Otherwise,itwillgetaturnbasedonitspositioninaqueueandthenumberoffreecycles.Astheframerateincreases,wehaveextratimetogivetothetraffic,unlesstheplayerisengagedincombatorsomething.So,thedistantvehiclesareplacesinaqueue,andthefrontfewaregivenmovementcontroleachframeandarethenplacedattheendofthequeue.This is fair, and it will automatically give as much spare time as possible totrafficmotion.

Navigationistheprocessofgettingfromonelocationtoanother.Sometimesthereisafinaldestinationwhichisarrivedatinstages,andsometimestherearepredefinedroutestoknowndestinationsthataredefinedbythegamedeveloper.Awaypointisanintermediatedestinationalongaroute,anditisdefinedbyasetof3Dcoordinatesandactionstotakeuponarriving.Acharactermovesfromonewaypointtoanotheronitswaytoitsfinaldestination.Forcharactersthatdon’thavepredefineddestinations,weusepathfindingmethodsliketheA*algorithm.

Characters may have a set of states that control their movement andnavigationalbehaviorasafunctionofwhatisgoingonatthemoment(currentstate). It is also common to have characters simply moving around to createsomeformoftraffic,essentiallyprovidingambiance.

EXERCISES

Thefollowingproblemswillexerciseyourknowledgeofthematerialinthischapter,andtheywillsometimesrequirethatyoudomoreresearchbeforeyouareabletocompletethem.1. Create a simple elliptical track on an 800 x 600 image and use it to

implementabasicdrivingsimulation.Onecarshoulddrivearoundthetrackcompleting at least five laps before stopping. Use no fewer than eightwaypointstoguidethevehicle.

ForthenextexercisesuseFigure5.11,whichshowsan800x600imagethatisto be used in pathfinding. Presume that a character’s avatar, represented by asmallbluecircle,istomovefromthesmallhouseintheupperrightoftheimageto the larger house in the lower left. Presume also that this dotmay not passthroughtheriverorthroughthebrickbarriers.2. Markpassibleandimpassiblesquaresontheimage,creatingwhatwecalla

mask.Havetheavatarmovetowardthedestinationwhenpossibleandbackupandtryanewpathwhennot.Turnatrandomwhenadecisionhastobemade,towardthedestinationwhenpossible.Doestheavatarfindapath?If

Page 175: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

so,howlongdoesittake?3. Find a set of paths to the destinationmanually andmark them either in a

same-sizedimageorasarraysofindividualpixelxandymovements.Createat least four paths that branch from the starting point and are selected atrandom.Doesthebehaviorlookrealistic?

Idea:Aprogramhasbeenwrittenthatallowsthedevelopertousethewasdkeystomovefromthesourcetodestinationandrecordthepath.Thepathwaswrittentoafileandreadinandusedbytheproblemsolution.Youcouldwritesuchaprogramtooorusetheoneprovided.4. RepeatExercise3usingwaypoints.Inwhatwaysisthissolutionbetterand

inwhatwaysisitnotbetterthantheonespreviouslytried?5. AddanewNPCavatartothesolutionofExercise4,aredcircle,whichwill

try toprevent theplayer’sblueavatarfromreachingthedestination.Itwillstartintheupperleftandmovetowardtheblueavatarwhenit“sees”it;thatis,when there is a clear lineof sightbetween the redandbluecircles thatdoesnotpassthroughabrickwall.Iftheredavatargetstowithin12pixelsoftheblueone,thenitsucceedsandredwins.Iftheblueavatargetstothedestination, then blue wins. Who wins this game and under whatcircumstances?

6. Navigationisnotonlyconnectedwithexistingpathsandphysicalobstaclesbut sometimesbymoreabstract things like traffic rules.Describe the rulesforbehaviorwhenacararrivesatastopsignonatypicalcitystreet.Sketchaplanforthebehaviorofavehiclefromtheapproachtoastopsignuntilthemomentthatitisdecidedthevehiclecanproceed.

7. Streetwisenavigationcanbecomplicatedbyroadclosures,one-waystreets,and other features of modern life. In computer science terms, streetintersectionscanbeconsideredtobenodesonagraph.Anentitycalledanadjacencymatrix is used to representwhichnodes are connected towhichothers.Anelementjinrowiofthematrixisa1ifthereisawaytogettonodejfromiinonestep.Hereisanexample:

Page 176: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

There is analgorithm todetermine if apathexistsbetweenany twonodesandhowlongthatpathis—itisreferredtovariouslyasWarshall’salgorithm,theFloyd-Warshall algorithm, or theWFI algorithm. Look up this algorithm anddescribeit;thendiscussitsusefulnessinfindingroutesinurbancontexts.Howisaone-waystreetrepresented?

Page 177: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE5.11Sample2Dpathfindingimagefortheexercises.

RESOURCES

PathFindingTutorial:http://wiki.gamegardens.com/Path_Finding_Tutorial.UsefultutorialdescriptionofA*.Gamasutra tutorial on realistic pathfinding:

http://www.gamasutra.com/view/feature/3096/toward_more_realistic_pathfinding.phpVerygoodvideogamecontext.Video demonstration of Dijkstra’s algorithm:

http://www.youtube.com/watch?v=8Ls1RqHCOPw.Pathfinding concept, the basics (Michael Grenier):

http://mgrenier.me/2011/06/pathfinding-concept-the-basics/.

REFERENCES

1. E.G.Gilbert,D.W.Johnson,andS.S.Keerthi. (1988).“AFastProcedureforComputingtheDistancebetweenComplexObjectsinThree-DimensionalSpace.”IEEEJournalofRoboticsandAutomation4:193–203.

2. Dan Higgins. (2002). Generic A* Pathfinding. AI Game ProgrammingWisdom,CharlesRiverMedia.Hingham,Mass

3. James Matthews. (2002). Basic A* Pathfinding Made Simple. AI GameProgramming Wisdom, Charles River Media. AI Game ProgrammingWisdom,CharlesRiverMedia.Hingham,Mass

4. J. Pearl. (1984). Heuristics: Intelligent Search Strategies for ComputerProblemSolving.Addison&Wesley,Boston,MA,USA.

5. Anthony Stentz. (1996). Map-Based Strategies for Robot Navigation inUnknownEnvironments. Proceedings of the AAAI Spring Symposium onPlanning with Incomplete Information for Robot Problems.http://www.aaai.org/Press/Reports/Symposia/Spring/ss-96-04.php.

Page 178: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER6

SOUNDHereisaninterestingexperiment:playafirst-personshooter,suchasHaloor

Half-Life, with the sound off. It is amazing how much of the energy andemotional content is contained in the audio part of a game.The tempo of themusic gets the blood racing, and the sounds of weapon fire and nearbyexplosionscanguideyouawayfromtroubleorintosituationswherepointscanbewon.It’snotjustshooters:playanyofyourfavoritegameswiththesoundoffifyouneedconvincing.

1. Computergamesusesoundforfourbasicthings:2. Music.A great deal of emotional content is contained in themusic alone.

AlfredHitchcockknewthisverywell.3. Soundeffects.Ifacarcrashesoragunfires,weexpecttohearthat.4. Speech. Many games tell a story by allowing you to listen in on

conversationsorevenparticipate.Yoursideisoftentypedinandisnotreallyunderstood,butthecharactersinthegamespeakandexpecttobeheard.

5. Ambientsound.Thisisbackgroundnoise,suchasariver,orrain,oreventhesoundofcoffeeshop.

It is interesting that many programmers, even those with many years ofexperienceandwhoknowgraphicsandevent-basedprogramming,knowalmostnothingabouthowtomanipulateandplaysoundsonacomputer.Itisespeciallyinteresting because sound programming is in many ways much like graphicsprogramming: thegoal is todisplay something, there isobjectpositioningandrenderingtobedone,thelistener’s(viewer)positionaffectstheresult,therearecolors (fre-quencies) to be handled, and a special device is at the heart ofeverything(soundcard/videocard).

So it iswithsomeexcitement thatwebegina trek into thedark,unknownworldof computer audio.Likegraphics, there canbe a lot ofmath associatedwithsound;unlikegraphics,someofitisnotnecessarytoperformsimplerepro-ductionofsoundusingacomputer.Yousee,mostgamesdonotcreatesoundson

Page 179: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

the fly, but merely read sounds from files and play them at an appropriatemoment.Gameswouldbeverydullindeediftheapproachtographicswasthesame.Graphicalobjectsneedtobemoved,rotated, transformed,andtestedforvisibility and collisions.Audioobjectsbasically turnon andoff, get louderorsofter, and perhapsmove from the left to the right stereo channel.Display ofsoundsisinfactsimplerthandisplayofgraphics.Expectthistochangeasmoreoptionspresentthemselves.

Processing has no built-in scheme for audio display; that is done by adownloadableadd-on.ThefactthatProcessingisbasedonJavameansthattheadd-on is coded inJava anduses theJavaSoundAPI, and couldbeusedwithotherpurelyJavacode.Thisalsomeansthatlateron,whenwediscussHTML5,we’ll have to revise the audio display scheme. Additionally, there are a fewchoicesforaudiosystems,andyoumightbeinterestedintryingsomeofthem.For the purposes of this book we’re going to useMinim, the most commonoption.

BASICAUDIOCONCEPTS

Althoughtherearesimilaritiesbetweenoursenseofvisionandoursenseofhearing, the differences are significant. Most important is the concept thatobjects that are seen normally reflect light from another source, rather thangenerating light on their own. Thus, we see by reflected light. Audio, on theother hand, is usually produced by the object that is being sensed; that is, anobjectthatwehearisgeneratingthesound,notreflectingit.

Of course sound reflections can be important, and they contribute to theambiance of the sounds.The idea that sound sources are spatially localized iskey to positional audio generation, but it is less important in stereo andweb-basedgames.Ingraphics,whatwoulditlooklikeifwecouldonlyobservelightsources and not reflections? Things would be much simpler and vastly lessinteresting. Also, we don’t really have an audio image, a two-dimensionalpatternthatcanbeinterpreted.Instead,wehavetwosoundreceptors(ears),eachof which perceives the sum of the sounds that reach them at any particularmoment.Thiscanalsobethoughtofasanotherwaythataudioissimpler thangraphics.

Soundsareessentiallyvibrationsoftheair.Theintensityofthevibrationsiscalled the volume or loudness of the sound. The duration between twoconsecutivepeaksofthevibratorymotioniscalledtheperiod,andthenumberofpeaksthatoccurinasecondiscalledthefrequencyorpitch1(Figure6.1).

Page 180: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE6.1AsoundwaveviewedasagraphofintensityVStime.ThewavelengthWisthedistancebetweentwopeaks;theperiodisthetimebetweentwopeaks.TheamplitudeAisthedistancebetweenthepeakandthetrough(lowestpoint).Thefrequencyisthenumberofpeaksthatpassbyastationarypointinonesecond.High-pitchedsoundshaveahigherfrequencythandolowerpitchedones.

TheunitoffrequencyisHertz(shortenedasHz),whichwasnamedafteraperson.This namewill sound familiar; your computer has an execution speedthat is also measured in Hertz—well, megahertz (MHz = million cycles) orgigahertz(GHz=Billioncycles)—andthisreferstothenumberofclockcyclespersecond.

Atypicalhumancanhearsoundsthathavefrequenciesbetween40Hzand15,000Hz(1,000=1kiloHertzorKHz).Somepeoplecanhear20KHzsoundsand even higher, but as we get older our ability to hear high-pitched soundsdeclines. In any case, frequencies above 15 KHz are not as important as thelowerones incomputergames,ascomputer speakersaregenerallynotable toreproducethesesounds,andmanypeoplecannothearthem.

Wehave twoears, andnormallyanysoundpresents itself atbothof them.Therewillnormallybeaslighttimedifferencebetweenthearrivalattheleftandright ears caused by the distance to the object and the distance between yourears. Essentially, it takes time for the sound to travel the short distancerepresented by thewidth of your skull.This is howyou locate a sound.Mostpeoplecandetermineafairlyprecise locationforasoundevenwith theireyesclosed,butonlyifbothearsfunctionproperly.Thisfactisimportantinagame,becauseanobject that looks like it isat the left sideof the screenshouldalsosoundlikeitistoourleft.

Inday-to-day lifeweare surroundedby sound, andwecanactuallydetectmuchofit.Whatwehearisreallythesumofallofthesoundsthatreachusat

Page 181: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

eachmomentintime.Thismakesaudiorenderingsimplerthangraphicalrender-ing,becausethescreenrequiresthatwecomputetheintensityand/orcolorofatleast640x480pixels(places).Foraudio,weneedtocomputeonlytwoaudio“pixels,” one for each ear. However, we need to compute these audio pointsmore often than graphical ones. Twenty-four frames per second is usuallyenough to realistically representmoving objects on a screen. To render audiorealistically,weneed togenerateanewintensityvalueata rate that isat leasttwicethefrequencybeingcreated,orupto30,000timespersecond!Fortunately,thesoundcardcandoalotofthework.

Inordertostoreasoundonacomputer,ithastobedigitized,orsampled.Astandardsoundcardcandothisifyouplugamicrophoneorothersoundsourceinto it. Sound is represented as electrical signals,which can actually look likeFigure6.1whenviewedonanoscilloscope.Samplingasignalinvolvesmakinga measurement at a regular and frequent interval. An electrical signal can bemeasured as voltages, for example, so to store a soundwe couldmeasure thevoltagebeingsenttothespeakerseverymillisecondandstorethismeasurementasabinarynumberonafile.Playingthesoundbackrequiresthatwecanconvertbinarynumbersintovoltagesagainandsendthemtoanoutputdevice.

Withoutgetting into toomuchdetail, because signalprocessing is awholesubjectuntoitself,weneedtosampleasoundataratethatisatleasttwicethehighestfrequencythatwewanttoreproduce.Forexample,ifwewanttobeabletohear15KHzsounds,wehavetosamplethesignal30,000timespersecond.Ifasampleisaninteger(16bits),thismeansthatafour-minutesongrequires4*60*30000*4bytestostore(28MB),and56MBifthesongisstereo.Ofcourse,therearecompressionschemesandsuchtoreducethesizeassavedondisk.Inanycase,whatweneedistostorethesesamplesasnumbers,eitherintegersorfloats,andhaveameanstosendthemtothesoundcard.

AstandardPCsoundcardcanperformsamplingatahighrate,anditdoessofromboththelineinputandthemicrophoneinput.Thedevicethatdoesthisiscalledananalog todigital (A toD)converterorADC,and thesoundcardhassomeofthese.ThewaytheADCworksismuchlessrelevantthanistheresultandtheimplications.Figure6.2showsanexampleofthesamplingprocessforthesinewaveofFigure6.1.Aftereachsample interval thesound isconvertedinto a voltage measurement and converted into a binary number for storage.Sincethesenumbersaredigital,theycan’tbesavedperfectlyandsoareroundedto the nearest integer, which necessarily creates a small error in each sample(samplingerror).

The sound card can reverse the process too, taking a sequence of digitalsamples and converting them into voltages that can be sent to speakers or an

Page 182: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

amplifier for playback. Sounds in numeric form can be, and most often are,stored on files, retrieved, and played back as needed. The sound card is acomplex and clumsy thing to program directly, and so a software library thatdoesthisisessentialwhendevelopingagame.

FIGURE6.2Samplingofasinewavebyananalogtodigitalconverter.Aftereachfixedintervalsthesoundismeasuredasavoltageandconvertedintoanumberforstorage.Numbersatthebottomshowthenumericvaluesofthesoundateachsamplepoint.

This is where Pygame comes in. We can create reasonable sounds for atypicalgamewithoutneedingtoknowtoomuchofthemathorphysicsofsound.Wealsowon’tneedtoknowtoomuchaboutoursoundcard.WhatwedoneedtodoisunderstandtheparadigmusedbythedevelopersofPygame.

INTRODUCTIONTOSOUNDINPYGAME

ThekeymoduleinPygamefordisplayingaudioismixer.Itdefinesobjectsthat represent soundsandallows theprogrammer to load themandplay them.Within themixermodule is a class namedSound,which is an essential audiointerface for Pygame, and another called channel which is equally important.Themixer module is designed to allow multiple sound sources to be mixed(combinedatvariouslevelsofintensity)intoastereoormonooutput,possibly

Page 183: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

for real-time playback. By default, it permits eight channels, but complicatedcodecancreatemoresophisticatedoutput.TheSoundclassisthesoundobjectinPygame,associatingasoundwithafileandallowingittobeloadedandplayed,andcontrollingvolume,pan,andotherproperties.

Thesimplest thing todowith sounds is to loadandplay them.Aprogramthat does thiswould first initializePygameand create a display.Thismust bedone even if the display will not be used for displaying anything. Then theSoundclassisusedtocreateanobject,specifyingthenameofthesoundfiletobeassociatedwiththeobject:

m=pygame.mixer.Sound(“song.wav”)

Thevariablemisahandleoraccessvariabletothesound.Toplayit,usetheplaymethod:

m.play()

NowthestandardPygameloopmustbeenteredorthesoundwillnotplay:

whileTrue:

pygame.display.update()

ThisprogramisabasicWAVfileplayer.PygamedoesnotplayMP3filesbydefault,but it ispossibleusingothermodules.Theentirepreviouslydescribedprogramis(sound.py):

importpygame

pygame.init()

canvas=pygame.display.set_mode((200,100))

m=pygame.mixer.Sound(“song.wav”)

m.play()

whileTrue:

pygame.display.update()

SoundOptionsIn the real audioworld, amixer is a device that accepts some number of

inputsoundsandcombinesthemintoasinglesoundthatisacombinationofalloftheinputs(Figure6.3).TheinputsoundscouldbefrommicrophonesorCDs,tapes, or vinyl. The degree to which each sound will be a part of the finalmixtureissetbyusingavolumecontrol,sometimesaslidingoneorsometimesarotatingone.Eachsoundisassignedtoachannel,which isasinglepath thesoundtakesfromtheinputtotheoutput.Achannelcanbemonoorstereo,with

Page 184: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

stereochannelscountingastwo.ThemixerinFigure6.3haseightchannels,twomonoandthreestereo.

Pygamehasamixerclassthatsimulatesarealmixertosomedegree.WithinthatclassthereisaSoundclassthatrepresentsasound,asstoredonafile,andPygamehasachannelclass.Whenusingthemixerclass,therearesomecontrolsfortheoverallsound,andinadditioneachchannelandSoundhavecontrolsthatapply to them. By default, a Pygamemixer has eight channels. The previousexample did not explicitly use channels, and that is completely acceptable ifthere are only a few sounds and control of them is simple. The sound beingplayedwasassignedachannelbydefault.Ifaprogrammerstatesm.play()wheremisasoundobject,thenthemixercanperformthefollowingoperations:

FIGURE6.3Aten-channelaudiomixer.

m.play()–Startplayingthesoundm.stop()–Stopplayingthesoundm.pause()–Temporarilystopplaybackofallchannels

Thereareothercontrols,butwhatshouldbeunderstoodisthatthepreviousoperations are not normally available on a realmixer.Assume that the actualsound being played is a song from a CD player. The player can be started,stopped,paused,andsoon.Themixerdoesnotdothesethings;itacceptssoundintoitwhenthesoundisplayingandmanipulatesit.Eachsoundhasavolume,whichintheexampleisthevolumeoftheCDplayer.ThePygamemixerclass

Page 185: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

doeshaveaglobalstopoperationthatstopsallsoundsenteringthemixer.Soundsareassignedtochannels,andthechannelhasavolumecontroltoo,

whichistherelativelevelofthespecificsoundwithintheoverallmixeroutput(usuallyjustcalledthemix).

SoundVolumeEachsoundcanhave itsvolumeset toavaluebetween0(off) to1.0 (Full

volume).Moreover,thevolumesettingoneachsoundcanberetrieved,andthelengthof thesoundinsecondscanbefound.The length isknownbecause thesoundisactuallyasoundfile,andthelengthcanbecalculatedfromthesizeofthefileandthesamplerate.

TheessentialmethodsfromSoundare:

set_volume(v)Setthevolumelevel,between0and1

get_volume()Returnthecurrentvolumesetting

get_length()Returnthelengthofthesoundinseconds.

A program that plays a sound and allows the user to control the volumespends most of the code handling the keyboard events. Let’s say that the uparrow key turns the volume louder and the down arrow key turns the volumelower. The initialization is the same as before, but the main loop is morecomplicated because the key presses need to be captured and parsed. Let thevolume be set to a level controlled by the variable v,which can take a valuebetween0.0and1.0.Theprogram(sound0.py)is:

#Volumeset

importpygame

pygame.init()#Initialization

canvas=pygame.display.set_mode((200,100))

m=pygame.mixer.Sound(“song.wav”)#Readthesoundfile

m.play()#Beginplayingthesound

v=1.0#Initialvolumeismaximum(1.0)

whileTrue:

foreventinpygame.event.get():

ifevent.type==pygame.KEYUP:

ifevent.key==pygame.K_DOWN:#Downkeylowersthevolume

v=v-0.1#Decreasethevolumebythestandardamount

ifv<0:#Checkbounds

v=0

m.set_volume(v)#Setthevolumetov

ifevent.key==pygame.K_UP:#TheUpkeyincreasesthevolume

Page 186: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

v=v+0.1#Increasethevolumebythestandardamount

ifv>1:#Checkbounds

v=1

m.set_volume(v)#Setthevolumetov

print(v,m.get_volume(),m.get_length())

pygame.display.update()

Eachtimeakeyispressed,thisprogramalsoprintsthevolumelevelandthelengthofthesound.

ChannelsAchannelisassignedusingacalltothefind_channel()methodofthemixer

object. This locates a free (unassigned) channel and returns it. When usingchannels, instead of playing theSound, one assigns aSound to a channel andplaysthechannel.So,ifmrepresentsaSoundthen:

chan=pygame.mixer.find_channel()#Getachannelthat’snotbeingused

chan.play(m)#PlaytheSoundmonthechannel

Each channel has a volume control too.A channel can bemono or stereothough.Ifitisstereothenitisreallytwochannels,andsettingthevolumewouldmean setting thevolumeof each channel.This allows the ideaof panning thesound, setting a different volume level on each of the left and right stereochannels, thus positioning it in space. Setting the volume is done using thechannel:

chan.set_volume(1,1)

Thiscallsetsthevolumetothemaximumonboththeleftandright.Panningisa littlemorecomplicated.Assuming that,asbefore, thevariablev holds thecurrentoverallvolume(between0and1),let’saddanewvariablea thatis1.0forfullvolumeontherightchanneland0fornovolumeontheright.Theleftchannel volume will be 1-a, and a is a positioning of the sound betweenchannels:1forfullrightand0forfullleft.Afunctionpan(a)canbewrittenasfollows:

defpan(a):

globalleftAmp,rightAmp,chan,v

ifa<0:a=0

ifa>1:a=1

leftAmp=(1-a)*v

rightAmp=a*v

Page 187: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

chan.set_volume(leftAmp,rightAmp)

Nowtheprogramsound0.pycanbemodifiedtoalsoallowtheusertochangethepanvalueusingtheleftandrightkeys.Themainloopwouldbe(sound1.py):

whileTrue:

foreventinpygame.event.get():

ifevent.type==pygame.KEYUP:

ifevent.key==pygame.K_DOWN:

v=v-0.1

ifv<0:v=0

pan(p)

ifevent.key==pygame.K_UP:

v=v+0.1

ifv>1:v=1

pan(p)

ifevent.key==pygame.K_LEFT:

p=p-.1

ifp<0:p=0

pan(p)

ifevent.key==pygame.K_RIGHT:

p=p+.1

if(p>1):p=1

pan(p)

print(leftAmp,rightAmp,p)

pygame.display.update()</CODE>

CreatingYourOwnSoundsSounds,especiallypiecesofmusic,areprotectedinformation.Ifyouwishto

usethepropertyofsomeoneelse,youaregenerallyexpectedtopayforit.That’sperfectlyreasonable.Afterall,peopleareexpectedtopayforgames,right?Asisthe case with art, sounds that someone else creates and posts on the Internetwouldhaveavalue,andagamedeveloperisexpectedtopayforsuchresources.

Ontheotherhand,itispossibletocreateyourownsoundeffects,voices,andambientsoundsinmanyinstances.Musicmaybeamoresignificantproblem,asitrequirescompositionandplayingskillsthatnoteveryonehas.It’simportanttounderstandthatmusicusedinagamemustattributeandpayboththecomposerandtheartist.Theonlyexceptionsaremusicthathasbeenplacedintothepublicdomainbytheartistandmusicthatisoldenoughthatthecopyrighthasexpired.Onemustmakequitecertain that theassetsbeingused,music in this instance,havebeengiventheproperlegalconsideration.

Havingsaidthat,manysoundeffectscanberecordedusingequipmentthatmanypeoplealreadypossess. In thatcase thesoundsareyourproperty,unless

Page 188: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

you record someone singing a proprietary song, of course. Recording is verysimpleusingaPC,withsomeverygoodsoftwareavailableforfreeorlittlecost.Recordingscanbedoneusingcellularphonesandmostmp3players.Ofcourse,there are dedicated high-quality recording devices available for professionalqualitywork.

RecordingUsingCellPhonesandMP3Devices

Android IPhoneUsethevoicerecorderappintheToolsfolder.Opentheappandpresstheredbuttontorecordandthebluesquaretostoprecording.

Usethevoicememosapp.

SoundfileswillbesavedintheMyFiles/Audiofolder.

Opentheappandbeginrecordingbypressingtheredbutton.Pressthesamebuttontostoprecording.

Thequalityachievedbyacellphoneisgoodenoughformostsoundeffects,but not for voiceormusic.Theproblem is themicrophone,which is tiny andcheap. It’s possible to connect a bettermic to some phones, and that is to berecommended.

MP3 players usually have a record mode, which is intended for voicememos. They suffer from the same problem as telephoneswith respect to themicrophone.ForiPodsorSonyplayers,selectthesettingsmodeandthenrecord.

ASmallStudioThe small mixer shown in Figure 6.3 is sufficient for many small game

developers and costs around $100. A sound studio would require fourmicrophones,anddecent(butnotbrilliant)micscanbepurchasedfor$100each.Standsforthemicrophonesare$35,andcablesare$12–$20.Thecomputerwillbetherecordingdevice,andalaptopwillwork,buttoproperlyrecordoutdoorsounds,aportablerecorderisvaluable.TheZoomH1andsimilarrecordersrunabout$100.

Page 189: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Figure6.4TheZoomH1recorder.

Thetotalcostof thesoundstudiodescribedherewouldbeabout$700.Donotskimponquality;manyaudioenthusiastswouldclaimthatyoucan’tgetagoodmicrophonefor$100,andwhile that’snot really trueand technologyhasgottena lotbetter in thepast twentyyears, it’sbetter tohavefewergoodmicsthanalotofbadones.

Theremay be other bits and pieces that would be useful—a CD or DVDplayer,maybeaturntable,andothersourcesofsound.Alloftheseareconnectedto their own channel of the mixer, and the main outputs of the mixer areconnectedtothecomputerlineinput.Youcanmonitorthemixfromthemixerorthecomputerusingheadphones.

Somespecialpurposesoftwareisneedednowtocapturethesoundandstoreit.

AudioSoftware

TheCDthatcomeswiththisbookprovidesacopyofthemusiceditornamedAudacity.Formostsmallgamesthisistheonlysoftwarethatisneededtorecordandeditsoundsforagame.

Page 190: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE6.5AtypicalscreenfromAudacity.

Likemost sound editors,Audacity shows the sound as a graphic. Inmostcases a left and right channel are shown,oneatop theother.Simple editing isdoneusingthemouse,wheresectionsofthesoundcanbeselectedwithaclickand drag. The section selected will appear in a different color, and can bedeleted,copied,orboth.Oncecopieditcanbeinsertedinanotherlocation.

Audacityhasan impressive setofoperations it canperformona sound. Itcanchangevolume, filterby frequency, fade in andout, crossfade, reverbandtremolo,reducenoise,echo,andperformdozensofotheroperations.Itcanalsoloadmultipletracksandmixthemasdesired.

Ratherthansimplydescribethisprogram,let’suseittocreateasoundeffect.Considerthattheboatracegamewillneedanenginenoisesoundforeachboat.Anengineisaconstantlow-frequencynoisethathassomevariationinvolume.Itcan’tbetooregularthough.Asinewavewouldnotsoundright.Butitmaybeastart.

UsingAudacitywithno trackspresent, select“Generate”and then“Tone.”Select75Hzand“OK.”Anewstereotrackwillappearcontaininga75Hzsinewave.Audacitylookslikethis:

Page 191: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE6.6Audacityshowingagenerated75Hztone.

Whenplayed (thegreen trianglebutton) it sounds likea lowmusicalnote.Nowweneedtoaddsomerandomchanges.Select“Generate”and“Noise.”Thedrop-downmenuwill offer a noise type (select “Pink”) and amplitude (select0.8).Clickon“OK”andasecondstereotrackwillappearcontainingthenoise.TheAudacitywindowwilllooklikethis:

FIGURE6.7The75Hztoneononetrackandapinknoisesoundonasecondtrack.

Playing these two together now sounds more like an engine. Select bothtracks(Shiftandclick)andthenchoose“Tracks”and“MixandRendertoNewTrack.”The two trackswill be combined into a third.Youcannowdelete theothertwotracks(clickonthe“x”intheupperleftofthetrackdisplay).Wecan

Page 192: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

nowseethemixedtrack.Asa laststep,select“Effect”and“Tremolo.”Choose theparameters:sine,

Wet level = 30%, frequency = 8.7, then OK. We now have a passable boatengine sound. Obviously, one should experiment with the parameters of theeffects so as to get a feel forwhat they do, and to permit better effects to becreated.

This activity is very much like creating art from scratch with Paint orPhotoshop. It is also possible to record sounds and incorporate them into theeffects.Forexample,onecouldrecordthesoundofaflowingwatertapintotheenginesound.Afingersnaporthumponatablecouldberecordedandsloweddowntosoundlikeanexplosion.

Ofcourse,anotheroptionistopurchasesoundeffectsfromproducers,eitherasCDsordownloadableMP3files.

FIGURE6.8Thetoneandthenoisetrackmixedtoonestereotrack.

PositionalAudioThe concept of positional audio is relatively simple, although the

implementationisnot.You,asahuman,almostcertainlyhavetwoears.Soundfromanysourcereachesthematslightlydifferenttimes,becauseyourearsareafewinchesapart.Thattimedifferentialcanbeusedtoroughlylocatethesoundsourceinspace:ifthesourceistoyourleft,thenthesoundreachesyourleftearfirst, for example. This can be simulated in systems that have stereo sounddisplaycapability.

Page 193: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

It’salsotruethatasoundthatoccursnearbyseemslouderthanoneoccurringadistanceaway,allotherthingsbeingequal.Weusethisfactinstinctivelywhenjudgingthedistancesinreallife,anditshouldbetrueingamesaswell.Thisisabasic aspect of positional audio, one that everyone perceives on a daily basis,anditrequiresonlydistancetothesourceandnotthepreciseposition.

What is needed for positional sound to be possible is the posi-tion of thesoundevent,whichistosaythelocationwithinthegamespaceofthethingthatgenerates thesound.Collisions, forexample,happenataprecise location.Thepositionandfacingdirectionoftheplayer,ortheavataratleast,isalsoknown,and the relative intensities of the sound at each ear can be calculated anddisplayed at each speaker. It is clear thatwhat’s needed is the position of thesound,thepositionoftheplayer(listener),andthedirectiontheplayerisfacinginthegame.

Wecanassumethattheplayer’spositionisknown,sinceitisbeingupdatedbythegameeachframe.Thesoundpositionisalsoknown,asmosteventshaveaknownpositionwithinthegame.Theplayer’sfacingdirectioncanbeassumedtobe thedirectionofmotion, or if stationary then the last knowndirectionofmotion.

Example:DistanceAttenuationIncomputergraphics,clippingistheactofremovinglinesandpolygonsthat

are outside of the viewing volume. This includes lines that are too near thecamera and lines that are too far away. The near and far clipping planes aredefinedasdistances;weshalldothesamewithsounds.Atsomesufficientlyfardistanced,asoundcannolongerbeheardandwillbeattenuated(i.e.,reducedin intensity) completely (100%).At some sufficiently near distance the soundwill be attenuatednot at all (0%), and at everydistance in between the soundwill be attenuated by some function of distance. In real life the function isrelatedto1/d2;thatis,thesoundgetsfainterasthesquareofthedistancetoit.The important thing in a game is that things seem correct rather than beingcorrect,andthisdegreeofattenuationmaybetoogreat.Alinearfunctionmayseemmorerealistic.

Let’sdefinevariablesmaxSoundDistanceandminSoundDistancetobethe100% and the 0% attenuation distances re-spectively. Then, ifd is the actualdistancetothesound,theattenuationacanbecalculatedas:

where a will have a value between 0.0 and 1.0. Every sound will have anatural or intrinsic volume at which it is played, as well as a minimum andmaximum, and this intrinsic volume will be modified by multiplying by the

Page 194: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

attenuationbeforeitisplayed.

a=(d-minSoundDistance)/(minSoundDistance-minSoundDistance)

In Pygame, each Sound/channel has a predetermined volume setting thatapplies to it. The attenuationwill be used to set the gain to the proper valuebetween these twopoints.Volumehasaminimumvalueof0andamaximumvalue of 1. The volume setting would be some value between 0 and 1 asdeterminedbythedistancebetweenthelistenerandthesound-creatingobject.IfavariablemaxSoundDistancewas thedistanceatwhichasoundcouldnotbeheard,thenthevolumesettingforthechanneldisplayingthatsoundwouldbe:

g=distance/maxSoundDistance

Setting the volume could be done as follows for a listener at (lx,ly) and asourceat(x,y):

#(x,y)issoundposition;(lx,ly)isavatarposition

defplayDistance(intx,inty,intlx,intly,channelplayer):

globalmaxSoundDistance

d=sqrt((x-lx)*(x-lx)+(y-ly)*(y-ly))#Distance

a=d/maxSoundDistance#Attenuation

v=1-a#Volume

ifv>1:

v=1

player.setVolume(v)

Example:2DPositionalSoundHumanshave theability toapproximately locate thephysical locationofa

sound.Mostpeopleknowthisandbelievethat ithassomethingtodowith thevolume at each ear. It does, somewhat, but it’s reallymore about the time atwhichthesoundarrivesateachear—thetimedifference, that is.Yourearsareabouteight inchesapart,orabout0.6millisecondsat thespeedofsound.Yourbrain combines the time difference between the two ears with any volumedifference,takesintoaccounttheattenuationduetoyourheadandtheshapeofthepinnae(theshapedpartofyourexternalear),andcalculatesthepositionofthesound.

A computer game does not have to do that. The game knows where thesound source is, andwhat it attempts to calculate is how that should sound atyour ears. It then sends those sounds to the left and right channelsof a stereosound system (or theN speakers of a 5 or 7 channel sound system, butwe’ll

Page 195: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

stickwithstereohere).Thegamesoundsystemdependsonthespatialseparationoftheelectronicsoundsystemandtheabilitytosetvolumelevelsontheleftandright channels to simulate how the event should sound.We have to calculatethose two sound levels. It is not possible to use time as a positional factor,because it is not possible to know where the player is with respect to thespeakers(unlessheadphonesareused).

To figure out how to do a positional sound calculation,weneed to decidehow to tellwhere the sound location is relative to the player’s avatar and thedirection that it is facing.We will find the angle between the player and thesoundandusethattoadjustthepancontrol.Theplayer’slocationisknown;thefacing direction must be known too, and it will be an angle in the samecoordinate system.Recall that thePythonmath class uses a system that has 0radians/degrees as screen right, and π/2 radians (90 degrees) as the screen updirection.Withtheplayeratposition(X,Y),we’lldefineapoint(faceX,faceY)thatcorrespondstoanimaginarypointtowhichtheplayerisfacing.Thispointwillbe:

faceX=(int)(X+cos(facingDirection)*d)faceY=(int)(Y+sin(facingDirection)*d)

The value of d is a distance from the player, and it can be anything thatprovidesalongdistance;thevalued=1000worksprettywell.

Figure6.9showssomethingofthegeometryofthesituation.TheleftpartofFigure6.9 showsadiagramof aplayer in twoextreme situations—onewherethesoundispreciselytotheright,theotherwherethesoundisdirectlyahead.Inthe first case the sound is at maximum loudness in the right ear and theminimumintheleft,andinthesecondtheloudnessshouldbethesameinbothears.As thesoundmovesalongan imaginarycurve from the firstpoint to thesecond,thepanbetweentherightandleftchannelalsochanges.Thisdescribeswhatwewant todo.Figure6.9(right)showsamoreabstractgeometry,wheretheplayerandthefacingdirectionareusedtodeterminetherelativeangletothesound.

Themathandtheprogrammingisabitcomplicated(SeeAppendixAfortherelevantmathematics),butthebasicstepsfordeterminingapanvaluefromthepositionsofthesoundsourceandthelistenerare:1. Calculatetheanglebetweenthefacingpoint,thelistener,andthesource.In

thecodeprovidedonthewebsiteforthischapter,thefunctionthatdoesthisis

Page 196: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

floatangle_3pt(x1,y1,x2,y2,x3,y3);

Itispassedthecoordinatesofthethreepointsthatdefinetheangle,withthelistenerbeingthecenter,andreturnsanangleindegrees.

2. Determinewhatsideofthelineisdefinedbythelistenerandthefacingpointthesoundsourceison.Thisisdoneusingthelineequationandplugginginthex,yvaluesofthesource:iftheresultispositiveit’sononeside,negativeandit’sontheother.Thefunctionthatdoesthisiscalled:

intwhichSide(x1,y1,x2,y2,x3,y3);

Itreturns+1ifthesourceisontheleft,-1ifontheright.Theproductofthesetwovaluestellseverythingweneedtoknowaboutthe

orientationofthelistenerwithrespecttothesource.Thisvaluehastobemappedontoapanvaluebetween-1and+1;asourceAnglevalueof-90isapanvalueof-1;asourceAnglevalueof0isapanof0;sourceAnglevalueof180isapanof1;andsourceAnglevalueof360isapanof0again.Valuesinbetweencanbeinterpolated, but the use of a pre-computed table can eliminate repeatedcalculation(thecomputationisdonemanytimesasecond).

The table of left and right channel volumes can be built by starting at 0degrees,whereboth sideswillbe inbalance (equal)withavalueof1.As theangleincreases, thesoundshouldmovetotheleftchanneluntilanangleof90degrees,wheretheleftisatamediumvolume(0.6)andtherightisatminimum.Minimumshouldneverbequite0,asitisalwayspossibletohearthesoundfromboth ears.The table is indexedbyangle andneednothave a largenumberofelements.Breakingtheanglebetween0and90degreesinto10partsyields20volume levels for that range (10 per channel) and a total of 80 for the entiretable. Interpolation is done to find the volume levels at any particular angle,assumingthatthechangeinvolumeislinear.Asanexample:

Index Angle Left Right0 0 0.6 0.61 9 0.64 0.552 18 0.68 0.503 27 0.72 0.454 36 0.76 0.405 45 0.80 0.356 54 0.84 0.307 63 0.88 0.258 72 0.92 0.20

Page 197: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

9 81 0.96 0.1510 90 1.0 0.111 99 0.96 0.1512 108 0.92 0.2013 117 0.88 0.2514 126 0.84 0.3015 135 0.80 0.3516 144 0.76 0.4017 153 0.72 0.4518 162 0.68 0.5019 171 0.64 0.5520 180 0.6 0.6

Note that theprocessreversesaswemovefrom90degrees to180degrees(facing away). From 180 degrees back to 0, the left and right volume levelsexchangeplacesinthetable,sotherightchannelbecomestheloudest.Theval-ueschangeinthesameratio.

Index Angle Left Right20 180 0.6 0.621 189 0.55 0.6422 198 0.50 0.6823 207 0.45 0.7224 216 0.40 0.7625 225 0.35 0.826 234 0.30 0.8427 243 0.25 0.8828 252 0.20 0.9229 267 0.15 0.9630 270 0.1 1.031 279 0.15 0.9632 288 0.20 0.9233 297 0.25 0.8834 306 0.30 0.8435 315 0.35 0.8036 324 0.40 0.7637 333 0.45 0.7238 342 0.50 0.6839 351 0.55 0.64

Page 198: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

40 360 0.60 0.60

Using the table involves first computing the angle between the source andthe listener (using angle_3pt()). Make sure this angle is between 0 and 360degrees,andchangeitintothatrangeifneedbe.Forexample,iftheangleis-40degrees,thenadd360togiveapositiveangleof320withintherange0to360.Dividethisangleby9togettheindexintothetable.

TheprogramnamedsoundPositional.pyisanillustrationofhowthisworks.Itdisplaysagreencircle,whichisthesourceofashortjazzpianopiecewrittenfor inclusion in this book by Nigel Gebert. It also displays a white circle,indicatingthepositionofthelistener,andabluelinethatshowsthedirectionthelistener is facing. Clicking the mouse in the window changes the listener’sposition,andpressing“a”or“d”rotatesthelistenertofaceanewdirection.Itisbesttolistentothesounddisplayedbythisprogramusingheadphones.Itclearlydisplaysthesoundpositionedin2Dspaceasthegraphicindicates.Italsoshowsattenuationbydistance.

FIGURE6.9(left)Thelistenergeometryofpositionalsound.Theearthatfacesthesourcemostdirectlygetsalargerfractionofthesound.(right)Themoretechnicalgeometryofthatsituation.Weneedtodeterminetheangle-andneedtoknowwhatside(leftorright)thesourceison.

Page 199: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE6.10DemoprogramsoundPositional.py.

EXERCISES

Thefollowingproblemswillexerciseyourknowledgeofthematerialinthischapter,andtheywillsometimesrequirethatyoudomoreresearchbe-foreyouareabletocompletethem.1. Youhave5minutesofstereorecording,sampledat11025KHzand16bits

persample,uncompressed.Howbigisthefile?2. Givenanymp3file,Writeaprogramthatwillreadandplaythefile.Display

thetimeplayedsofaronthescreen.3. ImplementapancontrolforthesolutiontoExercise2:whenthemouseison

theleftsideofthescreen,thesoundwillplayonlyontheleftspeaker,andasthemouse ismoved to the right, the sound is sharedbetween the speakersandthenmovesright.

4. Createa simplekeyboard thatplays thebasicnotes startingatA (440Hz).Eachnotewillbeplayedwhenanappropriatekeyispressed:a,b,c,andsoon.Thenotefrequenciesare:A(440)B(493.9)C(523.3)D(587.3)E(659.3)F(698.5)G(784.0).

5. Finish the sound recorder example. When the “r” key is pressed, beginrecording,andwhenpressedagain,stoprecording.Savetherecordedsoundtoafilewhenthe“s”keyispressed.Indicatethatrecordingistakingplacewithamessageorotherobvioussign.

Page 200: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

6. Construct a visual/auditory demo of distance attenuation. Let the soundsource be represented by a circle and the position of the listener berepresented by a second circle, drawn at the current mouse position. Thevolumewithwhich the soundwill be played (any file you like) is to be afunctionofthedistancebetweenthetwocircles.

7. Construct build a sketch similar to that of exercise 6, but now have twosound sources indicated by two circles drawn a few hundred pixels apart.Bothsoundsareplayingsimultaneously,andthevolumeofeachisafunctionof thedistancebetween themousepositionand thecircle representing thatsound.Youcan“mix”thesoundlevelsrelativetoeachotherbymovingthemouseabout.

8. (Sound editing) Locate a recording of a hockey game on the Internet orrecord the sound from your television. Using Audacity, GoldWave, or asimilar sound editor, locate a clean instance of a puck hitting the boards.Extract this into its own file, and clean it up using whatever filters youchoosesothatyouthinkitsoundsgood.Editthebeginningandendsothatthesoundclipplays immediatelywhen the file is started.Save this file fortheproblemsinthenextchapter.

RESOURCES

WheretodownloadMinim:http://code.compartmental.net/tools/minim/http://processing.org/reference/libraries/Top-levelMinimdocumentation:http://code.compartmental.net/minim/javadoc/JavasoundDocumentation:http://docs.oracle.com/javase/6/docs/technotes/guides/sound/programmer_guide/contents.htmlMinimaudiosignaldocumentation:http://code.compartmental.net/minim/javadoc/ddf/minim/AudioSignal.html

Audacity:http://audacity.sourceforge.net/download/

GoldWave:http://www.goldwave.ca/Freesoundeffects:http://www.grsites.com/archive/sounds/

REFERENCES

Page 201: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

1. K.Collins.(2008).GameSound:AnIntroductiontotheHistory,Theory,andPractice of Video GameMusic and Sound Design. Cambridge, MA:MITPress.

2. C. Crawford. (1984). The Art of Computer Game Design. Berkeley, CA:McGraw-Hill/Osborne Media [out of print but available as an eBook ordownload athttp://www.vic20.vaxxine.com/wiki/images/9/96/Art_of_Game_Design.pdf].

3. Johnny Friberg and Dan Gärdenfors. (2004). Audio Games: NewPerspectives on Game Audio. ACE ’04 Proceedings of the 2004 ACMSIGCHI InternationalConferenceonAdvances inComputerEntertainmentTechnology.

4. 4.J.HeeremaandJ.R.Parker. (2013).MusicasaGameController. IEEEInternational Games Innovation Conference 2013, Vancouver, BC,September23–25.

5. Ben Long. The Insiders Guide to Music and Sound for Mobile Games[eBook]. http://www.amazon.com/Insiders-Guide-Music-Sound-Mobile-ebook/dp/B0077QMKNU.

6. J. R. Parker and John Heerema. (2008). “Audio Interaction in ComputerMediatedGames.”InternationalJournalofComputerGameTechnology.Pp1-8

7. RichardStevens andDaveRaybould. (2011).TheGameAudioTutorial:APracticalGuidetoSoundandMusicforInteractiveGames.Burlington,MA:FocalPress(Elsevier).

8. Nigel Gebert (2018) Keys for Jim, musical composition.https://soundcloud.com/seeking-satellites/keys-for-jim

1Frequencyandpitcharenotpreciselythesamething.Pitchisasubjectivepsychoacousticcharacteristicofsound,orhowafrequencyisperceivedbytheauditorysystemandbrain.

Page 202: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER7

C2H6OJETBOATRACEHavinglookedattheinternalstructureofagame,somebasicgraphics,and

audio,wenowhavethetoolsatourdisposaltobuildacomplete2Dgame.Webegan a game design document for the Jet Boat Race in Chapter 1, so let’scompletethatgameasanexample.Oneshouldneverjumprightintocodingattheveryonset of a project, becausewedon’t knowat that timewherewe aregoing.Ontheotherhand,adegreeoforganizationanddisciplineareneeded,anditerativeprototypingisagoodwaytostructureaprojectingamedevelopment:create a playable game as soon as possible and then play it, taking note ofdeficiencies and exciting parts. Then use that information to make a secondimprovedversionandplayitagain,repeatinguntilitisexcellentoruntilyourunoutoftime.

Game developers work from documents. The high concept was a salesdevice,notaworkingdevelopmentdocument.Themostimportantthingtohavewhenbuilding a game is thegamedesigndocument (GDD),which is really ablueprintofwhattheproposedgamewillbe.TherearemanyformsofGDDbutall have some basic things in common. It must describe the game in enoughdetail to implement it unambiguously. In most game development companiesthere is a teambuilding a game, and that teamwill eachwork from the sameGDD.Itdefinesthegoal.

So,weshouldnowadd to theGDDforJetBoat and then stick to itwhenbuilding the game, just as is done in real life. This is a simple game and thedocumentwillbeshort,buttheGDDforamajorgamecanbehundredsofpageslong.

IMPLEMENTINGTHEGAME:PROTOTYPES

Intraditionalsoftwaredevelopmentitisnotuncommontohaveacompletedesigndocumentbeforestartingthecodingpartoftheproject.“Don’twriteanycode until you have a spec” iswhat they teach at school.When developing agame,itcanbeveryusefultohaveamalleablesetofexecutableprototypesright

Page 203: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

at the very beginning. These are executable but not functional, if that makessense;thegameimplementedisaprimitiveonethathasonlythemainfeatureortwoworking.Thepurposeismanyfold,butfirstitallowstheclient,thepersoncontractingforthegame,togetavisualfeelforwhatisbeingproposed.It’sverywelltosaythatwe’rebuildingaMarioKartvariantinthestyleofaboatrace,butitisquiteanothertoseeitonthescreen.

Next, it gives us an idea of how complex the project is.Many developershave the ability, after decades of practice, to conceptualize this in their heads.However,seeingthegamesurface,thesizeoftheparts,thespeedoftheobjects,thecolors—thiscangivenewideas,canidentifyplaceswherethingscouldgetdifficult,andgenerallyhelpsgettheprojectofftoagoodstart.Laterprototypesallowtestingofnewideas,addressingefficiencymatters,andtryingoutnewartandmusic.Finalversionsareplaytestedsoastoensurethatthefinalproductisasmuchfunaspossible.

Prototype0Thisfirsttentativeversionismainlyforaninitialevaluationin-house.Inthis

particular case the basic code only required about thirty minutes to create. Itgivesonlyabasicfeel:thegameplayareaisdisplayed,

Doesthislooklikewhatwewant?Isthewindowbigenough?Theboat,isittoosmall?Thereisnosoundyet,nointeraction.

Thisisprettyimpressive,really.InCorevenJavaitwouldhavebeenverydifficulttocreatethisinunderanhour,andthenumberoflinesofcodewouldgrow enormously.The things thatpygame gives us are the things that are notinteresting to codeand that takea lotof time:windowmanagement,graphics,animation,andinteraction.

Prototype 0 only displays the terrain and a boat. The terrainmoves as the“wasd”keysareused,withtheboatstayinginthesamerelativepositioninthewindow.Fromthisprototype,itwasnoticedthatthebackgroundimagewastoosmallortheboatsweretoolarge(Figure7.1).Asaresult,thebackgroundimagewasincreasedinsize,andtheriverswerewidened.

Page 204: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE7.1Thefirstprototypegamescreen.

Prototype1This is the prototype thatwas first shown to the client. It has the suite of

screens thatwillbeused in the finalgame, ifnot theactualart thatwillbe inplace.Ithasboatsthatcanbedrawnandsomeintermediategraphics.Thisisabetter example of how the game will look, and it can be given to someoneoutsideofthedevelopmentgroupforcomments.

The art for the screens exists, even if it is preliminary.Thebuttonson thescreenswork,sotransitionsbetweenscreenscanbeillustrated.Thegameitselfhasnotprogressedmuch,buttheentiresystemseemsmorefinished.Theamountofcodeneededtoimplementthescreensandthebuttonsissignificant:prototype1hasabouteleventimestheamountofcodeasdidthepreviousversion.Ittookovereighteenhourstobuild,includingtheart.Itturnsoutthattheartworkandpositioningbuttonstookthelion’sshareofthetimeinvolved.

ScreensAccording to the game design document, there are to be four different

screensusedinthegame:astartscreen,anoptionsscreen,aplayscreen,andanexitscreen.Theconsequencesforthecodearethateachscreencorrespondstoadifferent state in the display and enables distinct activities in the game codeitself.Thekeyboard,forinstance,hasnoeffectonanyofthescreensexcepttheplayscreen,whereitcontrolsthepaddles.Themousehasnoimpactontheplayscreen,butitisusedontheotherscreenstoselectanoptionorscreentransition.

Page 205: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Andofcourse,quitedifferentgraphicsaredisplayedineachscreen.Asimplefinitestatemachinecanbeusedtokeeptrackofthings.Thestateis

thescreenbeingdisplayed,andthetransitionsarecontrolledbythemouseandthe game play itself. The start screen takes you to theoptions, end, or playscreen.Fromeachofthoseyoucanreturntothestartscreen.

So, the screens canbenumbered: startState=0,optionState=1,playState=2,andendState=3.Thesearestatenumbers,andthefunctionweusetodrawthescreenuses thestatenumber todisplay thecorrect screen.Eachscreenwillbedisplayedbyadistinct function (startScreen(),optionScreen(), etc.) so thebodyofthemainloopwilllooklikethis:

whileTrue:

foreventinpygame.event.get():

ifscreenState==STARTSTATE:

startScreen(event)

elifscreenState==OPTIONSTATE:

optionScreen(event)

elifscreenState==PLAYSTATE:

playScreen(event)

elifscreenState==ENDSTATE:

endScreen(event)

else:

print(“ERROR:Badstateinmainloop.”)

exit()

pygame.display.update()

In thisway the statewe’re in is used to draw the screen each time a newframe is drawn. Screen transitions are done in the mouse handlermouseReleased, and the code looks verymuch like the previous code. If themouseisclickedinabuttononascreen,thevalueofscreenStateischanged.

ButtonsA“button”isnotathingthatpygamegivesus,sowehavetoimplementit

ourselves. It’s really just a region, usually rectangular, that responds in aparticularwaytoamouseclick.Thebuttonhasalabelthatreflectsitsfunction,sowespeakof“start”or“play”buttons.Whenthemouseispressedorreleased,pygamecallsafunctionnamedmousePressedormouseReleased respectively,if those functions are defined. So, if mouseReleased is called and thecoordinatesofthemousearewithintheboundsof therectangledefinedbythebutton,thenthebuttonwassaidtohavebeenpressed.

The start screen has three buttons—“Options,” “Play,” and “Quit.” The“Options” button has upper leftwindow coordinates (300,250) andwidth and

Page 206: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

height (100, 30). ThePython/pygame code that implements a button is bestimplementedasaclassbutton,whichcanbeusedgenerallytocreatebuttonsonanygamescreen.Thisclasshasthede-scription:

classbutton:

def__init__(self,x,y,w,h):

self.posx=x#Coordinatesofupperleft

self.posy=y

self.width=w#Widthandheight

self.height=h

self.text=“”#Textdisplayedinthebutton

self.size=34#Textsize

self.font=None#Textfont

self.color=(255,255,0)#Normalcolor(Yellow)

self.col=self.color#Currentcolor

self.armed=(255,0,0)#Armedcolor

self.family=None#Fontfamily

defsetText(self,t):

defisArmed(self):

defdraw(self):

defsetfont(s):

deftextsize(self,n):

defdrawText(self,s,x,y):

defsetcolor(r,g=1000,b=1000,a=255):

defsetarmed(r,g=1000,b=1000,a=255):

Creatingabuttoninvolvesaninitializationthatmainlyspecifiesthelocationand size of the rectangle the button contains.Creating a button is amatter ofusingtheconstructor.FortheOptionsbuttononthestartpage:

optionButton=button(300,250,100,30)

Thisplacestheupperleftcornerofthebuttonat(300,250)andmakesit100pixelswideby30pixelshigh.Nextsometextisplacedinthebutton:

optionButton.setText(“Options”)

Thedefault color for the text iscolor = (255,255,0),which is yellow.Thecolorchangestothearmedcolorof(255,0,0)orredwhenthemouseisoverthebutton region. Releasing the mouse button when the button is armed shouldcausetheactionindicatedbythemousetobeperformed.

Displaying the button is accomplished by calling thedraw method of thebutton. The Options button is displayed only on the start screen, so in thefunctionstartScreenofthegameprogramweplacethecode:

Page 207: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

optionButton.draw()

ifevent.type==pygame.MOUSEBUTTONUPandoptionButton.isArmed():

screenState=OPTIONSTATE

optionScreen(event)

return

This draws the button and checks to see if themouse buttonwas releasedwhile thebuttonwasarmed; ifso, itchanges thecurrentscreen to theOptionsscreen.ThentheOptionsscreenisdisplayed.ThemethodisArmedreturnsTrueif thebutton iscurrentlyarmed.ThestartScreen functionmustalsodrawandactivatethePlayandQuitbuttons.SettingthevariablescreenStatetothevalueOPTION-STATE means that the next time the main loop is executed, theOptionsscreenwillberedrawn.

StartScreenWhenaplayerstartsrunningthegame,theStartscreenappears.Thisscreen

is illustrated inFigure7.2. It showsagraphicbackgroundand three“buttons”that allow transitions to the other screens. Many games and other interactivesoftwarethathavebuttonsdisplaywhenthebuttonisarmed (i.e., themouseisoverthebuttonandaclickwillactivateit)bychangingthecolororthefont,orby showing the fact graphically somehow. In order to accomplish that, thebuttons should be small images rather than simple text drawn on the screen.Eachbuttonhastwoimagestorepresentit—oneforthenormalbutton,andoneforthearmedbutton.InFigure7.2,nobuttonisarmed.

Page 208: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE7.2TheStartscreen.https://commons.wikimedia.org/wiki/File:Shotover_Jet,_Jet_Boating_the_Shotover_River_Canyons,_Queenstown,_New_Zealand.jpg

When themouse button is pressedwhile the coordinates of the cursor areinsideofoneofthesebuttons,atransitionismadetoanotherwindowsimplybyassigninganewvaluetothescreenStatevariable.

OptionsScreenWhen the player selects Options, the game makes the transition to the

Options screen (screenState == optionState). This screen presents the playerwith the set of user selected parameters that can be chosen. This includes theability to turn the sound off, but in other games there could bemore options,suchasachoiceofaone-or two-playergame,or theability to select ahometeamortheavatarfortheplayer.

Again, the buttons that allow a choice are small rectangular regionsimplementedasimages.Whentheuserclicksonthe“SinglePlayer”button,itisreplacedby“2Players”andbackifclickedagain,sothatthecurrentselectionisvisible on the screen at all times. This does notwork in the case of the teamselection,becauseallteamshavetobevisibletomakeachoice,sotheselectedteam’slogowillbe thefirstonein the list.Clickingthebuttonlabeled“Back”takestheplayerbacktotheStartscreen(screenState==startState).

Page 209: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE7.3TheOptionsscreen.https://commons.wikimedia.org/wiki/File:Fjordn_surface_wave_boat.jpg.

Whenthesoundisturnedoff,anotherflagisset(tofalse),whichmeansthatallcallstofunctionsthatplaysoundsaredisabled.Inthisprototypetherearenosoundsyet,sonoactualimplementationdetailsareavailable.

PlayScreenThePlay screen isprettymuchas shown inFigure7.1.Novisible change

hasbeenmadetotheplayofthegameasimplementedeventhoughthedesignhasadvanced,becausethechangeshavetakenplaceinthesubsidiaryaspects—artandscreensforthemostpart.However,thisisthescreenthatdisplayswhenthePlaybuttonisselected,whereitwastheonlyscreenavailableintheinitialprototype.

EndScreenThe End screen is simply informative, giving game credits and contact

information.Aclickanywhereinthiswindowwillterminatethegameprogram(Figure7.4).

Page 210: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE7.4TheEndscreen,showinggamecredits.

Prototype2Afterprototype1hasbeenassessedandagreedtobytheclientorthedesign

team,thennextstepistodevelopthegamefeaturesindetail.Thismeansthatthescreendevelopment isconsidered tobecomplete,andallchangeswillbeseenon the game screen only.There are threemajor issues to be addressed in thisprototype:usercontrol,sound(includingscore),andthegameAI.

Usually therewillbe intermediatebenchmarks that theproducerwill insiston,andatthosepointsinthedevelopmentaplaytestordemowillbeconductedtoensurethatsufficientprogressisbeingmade.Itisessentialatallpointsinthedevelopment thatacurrentworkingversionof thegame isalwaysmaintained,andthatademoofthemorerecentversioncanbeconductedatanytime.

ThePlayScreenTheplayareaismuchlargerthantheviewingarea,orthedisplaysurfacein

pygameterms.Theplayareais3200x2700pixels(seeFigure7.1)whereasthesurface is500x400.Thinkof thesurfaceasawindowinto thecompleteplayarea.Therearethreeimportantcoordinatesystemsthathavetoberec-onciledifwewish to only display the smallerwindow and always have the boat in thescene.

Page 211: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

The first coordinate system involves the play area, the 3200 x 2700 pixelbackground image. The window and the boats will all have (x,y) coordinateswithin this area. Specifically, the player’s boatwill be at coordinate (bx, by).Simplisticallythiswouldseemtosolvealloftheotherproblems:theupperleftcorneroftheviewingareais(x,y)=(bx-250,by-200)becausetheboatshouldbecenteredinthisarea.Thebackgroundimagemustbetranslatedby(-x,-y)sothattheviewingareaisdrawnproperly.Thatis,thecodewouldbe:

display.blit(background,(-x,-y))

where display is the display surface and background is the backgroundimage.Whereistheboatdrawninthisexample?It’ssupposedtobeinthecenteroftheviewingarea,orat(250,200)incoordinatesrelativetothatsystem.Thatisinidealcircumstances.

FIGURE7.5(Left)Theentireplayingarea(terrain)showingthesizeofthedisplayarea.(Right)Close-upofthedisplayarea.

The values of x and y should never become smaller than zero; otherwise,therewillbepartsofthedisplayareathatdonothaveaterrainimagecoveringthem.Thesewillbedisplayedinabackgroundcolor,andit looksbad.It takesawayfromthefantasyofthegame.Thereisasimilarproblemattherightsideandbottomof theplayarea.Thedisplay is500pixelswide, soxmustnotbelarger than 3200 – 500, or 2700; otherwise, it will exhaust the backgroundimage.Intheydirectionthelimitis2700–400=2300.

Thecodethatdoesthisis:

#(bx,by)arethegamespacecoordinatesoftheboat

x=bx–250#Upperleftxofwindow

ifx<0:#Can’tbelessthat0

x=0

Page 212: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

elifx>2700:#Can’tbelargerthan2700

x=2699

y=by-200#UpperleftYofwindow

ify<0:#Again,mustbepositive

y=0

elify>2300:#ycan’tbelargerthan2300

y=2299

xx=250#Boatwillbedrawatscreen(250,200)

yy=200#Whichisthecenterofthescreen

#Drawterrainimage,shiftedsothatupperleftisat(x,y)

display.blit(background,(-x,-y))

#Drawtheboatat(xx,yy)atapproximatelyitscentre

display.blit(pygame.transform.rotate(boat2,angle),

(xx-boat2.get_width()/2,yy-boat2.get_height()/2))

Theresultisthattheplayer’sboatcannevergetcloserthan250pixelstoaleft or right boundary, or closer than 200 pixels to the top and bottom. Thisworksfineiftheterrainwouldalsoforbidthis,thatis,iftherearenowaterareasinthoseboundaryregionsoftheterrain.That’snottruehere.Thatmeansthatinsome cases the boat will either not be able to reach all of the reasonablelocationsonthemap,orwe’llhavetomodifythepositioningoftheboatinsomespecificcases.

Consider a casewhere the boat is at location (250, 200), as in Figure 7.6.Here,x=bx-250,whichis0.Thebackgroundcan’tbedrawnanyfurthertotheright,ordownfor thatmatter.Allowing theboat tobedrawnin thecorrectionpositionmeansrepositioningitwithinthewindow.Ifitmovesonemorepixeltotheleft,thevalueofxmuststayat250,bxdecreasesby1,andsotheboatmustberedrawnonepixeltotheleft(smallerx)withinthewindow.Thevariablexxwould be 250 – 1. Doing it again draws the boat at 250 – 2, and so on. Ingeneral,itisdrawnat250–-dxfordxequaltothenumberofpixelssmallerbxisthan250,orinotherwords,dx=250-bx.Thereisagloballimitthatbxcanneverbesmallerthan0;otherwise,itwouldvanishoffofthescreen.Thesameschemeworksfortheycoordinate.

Page 213: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE7.6Theboatcannotmoveanyfurthertotheupperleftinthiscasebecauseitisat(250,200).

As the boatmoves to the right, the x coordinates increase until a value of2700isreached.Thisisthemaximumvalueforx,sinceitisonewindowwidthtotheleftoftherightedge,or3200–500.Intheydirectionthemaximumvalueis2300.Whenx is2700,becausex=bx-250, itmeans thatbxmustbe2950.Theboatwillnowmovewithinthewindowtotherightby1pixeleachtimebxincreases,ordx=2900–bx.Similarlyfory,dy=2500–byafterybecomesgreaterthan2300.

Finally,acheckismadetoensurethat(bx,by)iswithintheplayarea.Allofthiscanbeencompassedwithinafunctionmove():

defmove():globalspeed,angle,x,y,xx,yy,

bx,by,background,boat2speed=speed-0.001#Slowdownifspeed<0:#Can’tmovebackward

Page 214: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

speed=0dx=0dy=0

else:dx=speed*math.cos(math.radians(angle))dy=-speed*math.sin(math.radians(angle))

bx=bx+dx#Newboatposition

#onmapis(bx,by)ifbx>3200:#Keeptheboat

#ontheplayareabx=3199speed=0

elifbx<0:bx=1speed=0

by=by+dyifby>2700:by=2699speed=0

elifby<0:by=1speed=0

dx=0dy=0

x=bx-250#Boatisfarleft.ifx<0:x=0dx=250-bx#dxisoffsetfrom

#centreofwindowelifx>2700:#3200-500is2700x=2700dx=2950-bx

y=by-200

Page 215: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ify<0:y=0dy=200-by

elify>2300:y=2300dy=2500-by

xx=250-dxyy=200-dy

display.blit(background,(-x,-y))display.blit(pygame.transform.rotate(boat2,angle),(xx-boat2.get_width()/2,

yy-boat2.get_height()/2))

Thiswilldealwithanyboatpositionspecifiedby(bx,by).Togeneralizethisfor usewithmultiple boats,we can create two lists, boats_x andboats_y, thatholdthecoordinatesofallboats,andalwayshavetheplayer’sboatasthezeroindex.Thatmeansthatbx=boats_x[0].Nowwe’lllookathowthatpositioniscontrolledbytheuser.

UserControlUser control involves making the software connection between the key

pressesandthepositionof theboat. Itappears tobeasimplematter,but thereareimportantissuestoresolve.Specifically:whatdokeypressesmean,howfastcantheboatmove,andhowquicklycanitaccelerate?

Themotionisimplementedusingtheeventpygame.KEYDOWN.Pressingthe “w” key, for instance, begins moving the user’s boat forward, essentiallyincreasingspeed;the“s”keywillslowtheboat,butwillnotmoveitbackward.Thedirectionthatamountstoforwardisindicatedbyanangle,where0degreesis increasingx.Pressing the“a”keywill increase theangleby5degrees, andpressingthe“d”keywilldecreasetheanglebythesameamount.

Program control of the player’s boat uses two variables: speed andangle.Eachtimethe“w”keyispressed,thespeedincreasesuptoalimit,andwhen“s”is pressed it decreases. If theboat ismoving andnokey is beingpressed, theboatwillslowdownandstopduetofrictionwiththewater.Thus:

ifevent.type==pygame.KEYDOWN:

Page 216: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

k=pygame.key.get_pressed()

ifk[pygame.K_s]:

speeds[0]=speeds[0]-.1

ifk[pygame.K_w]:

speeds[0]=speeds[0]+.1

Whynotuse:

ifevent.key==pygame.K_s:

speed=speed-.1

becausetheplayermaywishtoholddownthe“w”andthe“a”keysat thesame time. The get_pressed method returns all of the keys that are beingpressed.

Thevariableanglereferstotheboat’sdirectionoftravel.Zerodegreesistotheright,90degreesisup,andsoon.Eachtimethe“a”keyispressed,theangleincreasesby5degrees,andwhenthe“d”keyispressed,theangledecreasesby5 degrees. Thismeans that “a” rotates the boat counterclockwise. This angle-speed control scheme is typical of driving games, where “forward” alwaysmeans “in the direction you are facing,” and player control involves changingthe facing direction and the speed of the avatar. The control of the angle isaccomplishedby:

ifk[pygame.K_a]:

angles[0]=angles[0]+5

ifk[pygame.K_d]:

angles[0]=angles[0]-5

Giventhespeedandtheangle,achangeispositioniscomputed.Theboatisnowat(bx,by). Itschangeinpositionisgoingtobe(dx,dy), so that thenewpositionissimply(bx+dx,by+dy).Somesimpletrigonometrygivestheanswer:

dx=speed*math.cos(math.radians(angle))

dy=-speed*math.sin(math.radians(angle))

Thevariabledyhasasignreversalbecause“up” is the-ydirection,unlikeonamathematicalcoordinateaxis.Displayingtheboatinitsrotatedorientationuses the function pygame.transform.rotate(boat, angle), where boat is animageof theboatpointing right (zerodegrees).Hence thecode fordisplayingtheboatcouldbe:

display.blit(pygame.transform.rotate(boat2,angle),

(xx-boat2.get_width()/2,yy-boat2.get_height()/2))

TheBoatClass

Page 217: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Therewillbe threeboats in thisgame: theplayer’sboat and twoNPCs. Itseemedclearfromtheoutset thataboatshouldbeimplementedasaclass,butuntil theusercontrolandAIsectionsweredesigned, thestructureof thatclasswasfuzzy.Nowitisfairlyobvious.Allboats,includingtheplayer’sboat,havethesamestructure.

First, the important parameters of the boat upon creation are: the (x,y)position, the speed, and the course or angle.Variables local to each boatwillinclude:thesoundtobeplayedfortheengine,thecurrentvolumefortheenginesound, thesprite tobedrawntorepresent thisboat, the targetspeed, the targetangle(i.e.,whentheboatchangescourse,thesedefinetheendpoint),thecurrentdestinationonthemap,andanamefortheboatfordebuggingpurposes.

classnpc:

def__init__(self,x,y,sprite,speed,angle):

self.x=x

self.y=y

self.speed=speed

self.angle=angle

self.index=1

self.sound=False#Enginesound.

self.volume=0

self.targetSpeed=0#Howfastdoestheboatwanttogo?

self.targetAngle=90#Whatisthecoursesetting?

self.sprite=sprite#Theimageoftheboat

self.wpt=None#Nextwaypoint

self.name=“NPC1”</CODE>

Theclasshasthefollowingmethodsatthispointinitsdevelopment:

defsetSpeed(self,s):#Changethespeedtos

defsetCourse(self,a):#Changethecourse(angle)toa

defsetWaypoint(self,w):#Changethecurrentwaypointtow

#(seebelow–AIsection

defsetName(self,s):#Changethenameoftheboattos

defadjustAngle(self):#Makeanothersteptowardsthetargetangle

defadjustSpeed(self):#Makeanothersteptowardsthetargetspeed

defdistance(self,a,b):#Distancebetweentwopoints

defnextStep(self):#Makeonestep:movetheboatanddraw.

Notethatthecodewrittenpreviouslyusesanarrayspeeds[i],angles[i],andsoon.Usingaclassthiswillbeboats[i].angleandboats[i]].speed,whereboatsisatupleofallboats.Theitemboats[0]istheplayer’sboat.Wherebxandbywereused,thevaluesarenowboats[0].xandboats[0].y.

Aftereachiterationofthegameloop,themethodnextStepforeachboatiscalled.Itmovestheboat,andifachangeofdirectionorspeedhasbeencalled

Page 218: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

for, then a step is made to achieve that goal. Each change is broken intoindividualstepssothataboatcannotacceleratetooquickly.Speed,forin-stance,canincreaseby0.1unitsperiterationandtheangleby1degree.Changingtheangleby20degreeswill thusneed20 steps, as implementedbyadjustAngle,whichiscalledbynextStepifneeded.

The boat class will be modified further as required, to add sound andanimationsandothernewfeatures.

ArtificialIntelligenceThe artificial intelligence portion of this game determines collisions and

controlsthenon-playerboatsinasingleplayergame.

CollisionsThereareonlytwokindsofcollisionthatcanhappeninthisgamesofar,and

both can be determined using simple geometry rather than needing morecomplexcollision-detectionmethods.Theboatcancollidewiththeshore,whichistheeffectiveboundaryofthegame,ortheboatcancollidewithasecondboat.

Collisionswith theshore involvean irregularcollisionsurface that followstheshoreline,whichcanbedifficulttodealwith.Onewaytodealwiththisistocreateasetofboundariesasconnectedlinesegmentsthatfollowtheshorelines,beyondwhich theboundingboxof anyboat cannotpass throughanyof theseline segments and should in fact bounce off of them. This is a very generalsolution, but it is pretty complex andmay take a lot of time.For this game itshould be sufficient to use the background to determine whether the boat isgroundingornot.

Iftheboatisinthewater,thenthecolorbeneathitwillbeblue;thatis,thecolor on the terrainmap at the boat locationwill be blue. The simpleway todetectgroundingistoseeifthecoloratthefrontoftheboatandoneachsideisthe color of water. If so, no grounding has taken place; otherwise, it has. AfunctionshoreCollidewilldotheworkandwillreturnTrueorFalseastheboatisgroundedornot.Itworksasfollows:obtainthethepixel(color)valueatthefourpointsthatdefinetheboundingboxfortheboat.Waterhasaredcomponentof33.Ifanyofthethreesampledpointsdoesnot,thentheboathascollidedwithsomethingthatisnotwater.

ThemethodnextStep in theNPC class updates the screen position of theboundingboxateachgamestep.Thesearestoredinfourtuples:ul,ur,ll,andlr.This is the object oriented bounding box, of course, and it is exactlywhat is

Page 219: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

neededforthepurpose.TheshoreCollidefunctiontakesoneparameter,theindexoftheboatbeing

tested. It could have been a part of the NPC class, in which case the indexparameter would not be needed. The first step is to convert the screen coor-dinates of the bounding box into terrain coordinates (functionscreen_to_terrain).

Now we use the corners of the box to retrieve the terrain pixel at thosepoints.The redcomponentmustbe33or thatpoint isovera shorepixel.ThefunctionsetsacorrespondingBooleanvariabletoTrueeachtimesuchapixelisfound, and the function returnsTrue if anyof thosevariables are true.Other-wise,itreturnsFalse.

Thisseemslikemoreworkthanneeded,butitwouldbepossibletodefineanew target angle for the boat knowingwhich of the four corners is grounded.Thegamedoesnotdo this rightnow,but it is ona list of improvements.Thefollowing code simply returns as soon as it becomes aware of any groundedpoint:

defshoreCollide(i):

globalbackground

boat=boats[i]

ulx,uly=screen_to_terrain(boat.ul)

lrx,lry=screen_to_terrain(boat.lr)

urx,ury=screen_to_terrain(boat.ur)

llx,lly=screen_to_terrain(boat.ll)

pygame.draw.line(display,(0,255,0),(boat.ul[0],boat.ul[1]),

(boat.ur[0],boat.ur[1]),3)

pygame.draw.line(display,(255,0,0),(boat.ur[0],boat.ur[1]),

(boat.lr[0],boat.lr[1]),3)

c=background.get_at((int(ulx),int(uly)))

ifc[0]!=33:

returnTrue

c=background.get_at((int(llx),int(lly)))

ifc[0]!=33:

returnTrue

c=background.get_at((int(urx),int(ury)))

ifc[0]!=33:

returnTrue

c=background.get_at((int(lrx),int(lry)))

ifc[0]!=33:

returnTrue

returnFalse

Notethattwolinesaredrawnbythisfunction.Thesecorrespondtotheupper

Page 220: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

edgeoftheboundingbox,drawningreen,andtherightedge,whichisdrawnasred.Itisinterestingtoseethisbecausetheboatimageintheoriginalfileshowstheboatfacingright.Thismeansthattheleftsideoftheboatisreallytheupperedgeoftheboundingbox.Thisisclearfromascreencaptureoftheboatinthetestprogram.

FIGURE7.7Theupperedgeoftheboundingboxisthelonglineontheleftsideoftheboat(Greeninthecolorimage)andtherightedgeoftheboxistheshortlinenearthefrontoftheboat(Redinthecolorimage).

NavigationInthisgametherewillbetwootherboatsagainstwhichtheplayercanrace.

If thegame is tobeentertaining, theseboatshave toputupachallenge to theplayer.Theycan’tsimplywanderthelakeaimlesslybutmustcompletethesameroute as the player does, avoid the shore and other boats, and cross the finishline. Also, because the point of an NPC is to be entertaining, the NPC boatsshouldnotbesogoodthattheyalwayswin.Theplayermusthaveachance.

The NPCs will use waypoint navigation, as explained in Chapter 5. Thismeans building a system of waypoints and associated data manually, a time-consumingprocess.Onlysomeofthisprocesswillbeexplained,becausemuchofitisrepetitive.

Boat1,asshowninFigure7.8,has15waypoints.Eachspecifiesthelocationofthenextwaypointandgivesaspeedanddirectiontomaintain.Thedirection

Page 221: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

canchange,ofcourse,basedoncollisionsandavoidingobstacles.

FIGURE7.8Theinitialpositionsofallboats,andthefirstwaypoint.

Initially, boat 1 is destined for waypoint 1. When it arrives, it will beassignedwaypoint3andanewspeed.Boat1usestheodd-numberedwaypointsonly,andboat2usestheeven-numberedones.Ifaboatisknockedoffcourse,itwill try to reach itsassignedwaypoint.Thewaypointpathsassigned toboat1areshowninFigure7.8.

Aboatcanchangecourse(facingangle)bytwomeans.First,aboattriestoavoid other boats. It will change angle to avoid either of the other two. Inaddition,ifaboatcollideswiththeshore,itwillchangeangleagainsoastogetbackontrack.

Page 222: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE7.9Thecoursefollowedbyaboat,connectingthewaypoints.

Let’sexaminethisnavigationissueinaverypracticalanddetailedmanner.

WaypointsAsadatastructure,awaypointisatupleholdingthedataneededtocomplete

the next phase of the boat’s journey.When the boat arrives at awaypoint, asindicatedby thedistanceof theboat to thewaypointbeingsuf-ficiently small,then the newwaypoint becomes the next one.Eachpost has a nextwaypoint,whichisanintermediatedestination.Everywaypointholdsthefollowingdata:

Coordinatesofthiswaypoint(x,y).Thenumber(index)ofthenextwaypoint.Thespeedthattheboatshouldtrytomaintainalongthispath.

InPythonthiscouldbeatuple:(x,y,index,speed)

Page 223: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Eachboatsteerstothecoordinates(x,y)ofthenextwaypoint,whoseangleissimpletocalculate.Thecourse(angle)tothenextwaypointisagoodstart,andit is stored in thewaypoint itself.Twoconsecutivewaypointsdefine a course,and if nothing interferes it is all that’s needed. The coordinates of the nextwaypoint can be used in the case where the boat collides with something oravoidsanotherboat.

Thewaypointdatawascreatedbyusingtheterrainmapandplottingcourseson it as line segments, with each segment starting and ending at a waypoint.Thesedataarestoredinafilenamedparams.txt,whichtheprogramreadsatthebeginningofthegame.

Within the program, a waypoint is implemented as a small class so as toavoidtheuseofalistoftuples,somethingsomepeoplefindawkward:

classwaypoint:

def__init__(self,x,y,index,speed):

self.posx=x

self.posy=y

self.index=index

self.speed=speed

Thecollectionofallwaypointsisatuplewaypointsconsistingoftheseclassobjects.NowconsideranNPCboatasitexecutesfromthestarttotheendoftherace. Initially itswaypoint is#1 ifwe’reusingboat1.When thegamebeginsthisboatmustbegivenacourse(angle)thatwilltakeittowaypoint1at(432,2391).Whentheracebeginsthespeedis0andtheangleis90degrees,becausethatisitsinitialstate.Thegameloopcallsthemovefunction,whichmovestheplayer’sbotandthenultimatelycallsotherBoats,whichmovestheNPCboats.It first calls the nextStep method of theNPC class, the one that moves theNPCs,andthendrawstheboatsintheirnewlocations.ThenextStepfunctionisthefocushere.

Awaypointisadestinationandspecifiesaspeed.ThemethodnextStepfirstadjusts itsspeed toaccountforfriction.Thenitdetermineswhat thenew(x,y)positionontheterrainwillbe,givenitsspeedandcourse,andmovestheboattothatlocation.Itchecksforashorecollision,aswasdonewiththeplayer’sboat.

Now it checks to see if it has reached thewaypoint. If so, it changes thetarget to thenextwaypoint in thepath.The itadjusts thespeed(adjustSpeed)anditscourse(adjustAngle)tomakesureitistravelingatthecorrectspeedandcourseforthewaypoint.Itsteerstothenextwaypointusingthecode:

self.targetAngle=math.degrees(math.atan2

(self.wpt.posy-self.y,self.x-self.wpt.posx)+math.pi)

Page 224: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Itthendrawstheboatifitislocatedwithinthewindow.

AvoidingaBoatDetecting collisions between boats ismore critical, because such an event

willdestroybothboats.Abroadphasedetectioncouldbedoneusingenclosingcircles.Theboatsaremuchlongerthantheyarewide,though,andthiswillbemisleadingmuch of the time.Using bounding boxes is better, but theywouldhavetobealignedwiththeaxesoftheboats.

Theboatimagesare84x26pixels,andthebaseimagehastheboatfacingright (0 degrees). Finding an axis-oriented bounding box starts with thebounding box of the base image, which consists of four points in the terrainimagecoordinatesystem.Nowrotatethesepointsbythesameangleastheboatisfacing.Afunctionrotateisgiventhatdoesthisforapointandreturnsanewpoint. The rotation should be done about the center of the boat.Now convertthesepointsfromtheterrainsystemtothescreencoordinatesystem,forwhichafunctionterrain_to_screenhasbeenprovided.Theboundingboxisdefinedbytheoriginalfourboundingboxpoints,rotatedandconvertedinthisway.

FIGURE7.10Therayprojectedbytheblackboatintersectstheboundingboxoftheother(left)causingittochangecoursetoavoidit,inthisinstancebyrotatingclockwise.

Twoboatshavecollided if the rayprojectedbyoneof theboats intersectswith theboundingboxof theother. InFigure7.10, thesimulatedblackboat isshowing the ray that isused todetermineapotential collision,which is repre-sented by the green line.The potential collision results in amovement by theblackboatawayfromtheother.

Page 225: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

defavoid(self,i,ddx,ddy):

self.state=self.AVOID

zangle=math.degrees(math.atan2(ddy-self.y,ddx-self.x)-

math.radians(180.0))

ifzangle<0:

zangle=zangle+360.0

elifzangle>350:

zangle=zangle-360

ifself.angle<zangle*1.3:

self.angle=self.angle+1

else:

self.angle=self.angle-1

return

The variable zangle is the angle between the two boats. It is used todeterminethedirectioninwhichtheavoidingboatwillturn.Alsonotethattheboatthathasdecidedtoavoidtheotherisinanewstate,AVOID.Aboatinthisstate does not change its angle or speed in the usual way but lets the avoidfunctiondetermineitscourse.

Itistobeexpectedthatinmanycasesoneofthetwoboatsinvolvedwillbethe player’s boat, because the NPCs have been given courses that avoidcollisions in the firstplace.Thisparticularstrategyhas theNPCs takea ratherpassive stance, and the player can push them around by being aggressive. Ofcourse, this presents the risk of forcing a collision if theNPCcannot respondproperly.

CollidingwiththeShoreWhenaboatcollideswith theshore itmust try toescape.Movingon land

shouldnotbepossible.Itsactionsmustbereasonablebasedonthesituationinarealboatrace.

So,ifanNPCboatcollideswiththeshore,itstopsabruptlyandmusttrytoescape.Thisamountstoyetanotherstate,whichwillbecalledCOLLIDED.Inthiscasethewaypointwillceasetobetheimmediatedestinationuntil theboatsteersawayfromtheshore.TheonlywaythatanNPCcangroundisifanotherboatpushesit,becauseinmostcasesitwillmovefromwaypointtowaypoint.

Therearemanywaystheboatcouldtrytoescape,butanobviousoneistobackupabitandthenturn.Thenitwillresumecourse.Ifithitstheshoreagain,itwillrepeattheprocess.Theshorelinehasbeendesignedsothatitshouldnotbe possible to get trapped in a loopwhile trying thismaneuver.While in theCOLLIDEDstate,theboatwillfirstattempttobackup.Acountwillbekeptof

Page 226: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

thenumberofstepstheboathasmadedoingthis,andafterafixednumber(20inthisgame),itwillthentrytoturn.Again,20stepsareperformed,andeachoneturnstheboatby2degrees.Atthispointtheboatattemptstoresumecoursetothecurrentwaypoint.

Themethodthatdoesthisiscalledescapeandlookslikethis:

defescape(self):

ifself.estate<20:#Backup

ddx=self.speed*math.cos(math.radians(self.angle))

ddy=-self.speed*math.sin(math.radians(self.angle))

self.x-=ddx*2

self.y-=ddy*2

elifself.estate<40:#Changetheangleby2degrees

self.angle+=2.0

else:#40steps.ExitCOLLIDEDstate

self.state=self.NORMAL

self.speed=1

self.estate=self.estate+1#estateisthecurrentstepnumber

Thereareotherways toaccomplish this that takemoreeffortbutcouldbebetter:1 Another set ofwaypoints running down the center of the track and closely

spaced tobeusedas targets,andanearbyonewouldbeselectedwhentheboatgrounded.

2 Thepathjustfollowedcouldbestored,andtheboatcouldbackawayalongthatpathwhenithitstheshore.

3 Thedistancetothecenterofthewaterareaforeachpointcouldbefound,andtheboatcouldmovetowardthatpoint.

SoundNow that the user control system is being implemented, itmakes sense to

assignaudioeventstoeventsinthegame.Thereareonlyafewaudioeventsinthisgame,butitisimportanttogivethemsensiblesoundeffects,onesthataboatracingfanwouldrecognize.Inparticular:

- There will be the sound of the boat engine(s) whenever the engine isrunning,thatistosay,whentheboatismovingintheforwarddirection.

- Therecouldbesoundeffectsofbouncesagainsttheshore.- Therewillbesoundeffectsofexplosionswhenboatsaredestroyed.- Thereisagunthatindicatesthestartofthegame,andonethatindicates

theend.

Page 227: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

- Therecouldbeextraaudiencesounds,likecheers,whichcanbeplayedatrandom.

EngineSoundsSome time was spent in Chapter 6 showing how engine sounds could be

createdusingAudacity.Thesoundscreatedinthiswayhavebeensavedasmp3filesnamedengineBoat1.mp3 throughengineBoat5.mp3.Each engine sound isdistinct,andeachshouldbeassignedtoadifferentboatinthegame.Thesoundshould play as long as the associated boat is under power. For ex-ample, theplayer’sengineshouldplayaslongasthe“w”keyispressed.

Asimplemodificationtothepreviouscontrolcodewilldothis.Addaglobalvariableengine_on that has theobviousmeaning.Now if anyof the “a,” “s,”“d,”or“w”keysarepressed,alocalvariableeonwillbesettoTrue,indicatingthattheplayerwantstomovetheboat(turntheengineon).Ifitisalreadyon,noproblem.Otherwise,turniton(startthesound):

ifeonandnotengine_on:

start_engine()

elifnoteonandengine_on:

stop_engine()

Eachcheckofthekeysthataredepressednowlookslikethis:

ifk[pygame.K_s]:

speeds[0]=speeds[0]-.1

eon=True

Eachtimethroughtheeventloop,thevariableeonisfirstsettoFalsesothatiftheplayerreleasesthekeys,theenginewillshutoff.Thefunctionsthatdotheworkare:

defstart_engine():globalengine_on,sound_on,engine1engine1.play(1000)engine_on=True

defstop_engine():globalengine_on,sound_on,engine1engine1.stop()engine_on=False

Thereareothersounds,and thosewillbe implemented inmoredetailafterwe knowmore about animation andwhenmore of the game rules have beenimplemented.

Page 228: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CollisionsandExplosionsWhenaboatcollideswithanotherboat,anexplosiontakesplace.Thesound

of theexplosionhasbeencreatedusingAudacity,and thereare threevariants:expl00.mp3, expl01.mp3, and expl02.mp3. One of these should be selected atrandomandplayedwhen an explosion takesplace.This reduces the repetitivenature of sound.The same event rarely sounds exactly the same twice in reallife,butfrequentlyagameusesonlyonesoundfileforaparticularevent.Oneshouldalwayshavemultiplesoundsforanyeventthatoccursfrequently.

StartingGunThis is only used at the beginning of the game, so there is only one file:

start.mp3.This isplayedwhenallof theNPCboatsareallowedtobegin theirmotion, and it allows the player to manipulate their boat. It was created byrecordingapencilpoundingonadeskandextendingthedurationandaddingareverb. It would be better to record an actual gunshot or use a pre-recordedsoundeffect.

FinishThereisasoundthatplayswhenthewinningboatpassesthefinishline.This

soundisfinish.mp3.

TESTING

Whentestinganygame,aswithtestingmanyhuman-builtobjects,therearereallytwoaspectstobeconsidered.Thefirstis“doesthisobjectmeetthecriteriafor being functional?” The second can be expressed as “is this object a goodexampleofitstype?”orinthewordsofagamedesigner,“isitart?”Theformerkindoftestingforagameisoftenjustcalledgametesting,butitislargelyabouttesting the software that implements thegame.The latter is calledplaytesting,anditisintendedtoanswerthequestion“isitfun?”

Software testing is a tedious process. The program is executed again andagain in an attempt to execute every line of code and make certain that itexecutesasdesigned.Codeistestedagainstthedesigndocumentandagainstasetofstandards.Thedesigndocumentanswersquestionsaboutwhat thegameshould do at any particular point. The standards indicate correctness criteria:doesthiscodedothecorrectthingwhenafileisnotfoundorwhenconvertingarealtoaninteger?Doesitdividebyzero?Arethereanyoffbyoneerrorsinthe

Page 229: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

loops?Thesearemoretechnicalquestions,andonesthatariseinanysoftware.Game testing is performed by the Q/A (Quality assurance) department in

somedevelopmentcompanies,andsometimesbypeopleoutsideofthecompanyhiredas testers.Youmight think thatbeinghired toplaycomputergames isagreatjob,butit ismostlyagrind.Thetestermustplaythroughthegamequiteanalytically, andwhenaproblem is found, thenatureof thatproblemmustbecarefully defined. The precise circumstances of the error have to be found bytrialanderrorandgiventothedeveloperforcorrection.Then,afterbeingfixed,thetestermustmakecertainthattheerrorisinfactgone,andthattheprocessofcorrectingitdidnotcreateanynewproblems.

Playtesting is a different process. It is like other kinds of product testing,wherepeoplearehiredtotrytheproductandarethenaskedquestions.Ingametesting,playersarerecruitedtoplaythegame.Theyareaskedquestionsbeforeplaytocharacterizetheirdemographicidentity,theyplaythegame,andtheyarelateraskedquestionsaboutit.Playersareoftenrecordedonvideowhileplayingto identify emotional reactions. All of the data collected goes to answerquestionsaboutwhetherthegameisenjoyable,whereit isfun,andwhereit isnot.Iterationsofthistestingcanbedone,makingdesignchangesbetweeneachtest,involvingsixtotwelvepeopleeachtime.

Beta testing is the final stage. Unlike beta testing for software systems, agamecontinuestohavethecodetestingassomethingofadistinctprocessfromthatofthegameplay.Thebetatestinvolvesareleaseofthegametothepublic,orasubsetofthepublic,somanypeoplecanplayit.Theywillfindproblemsinthecodeifanyremain,butthekeyelementisplay.Manypeopleareplayingandreport on their experience. Final tweaking can be done before the ultimatereleaseofthegame,whichwehopewillbethebestwecando.

Playtesting can and should be done from the early stages of development,fromthefirstplayableifpossible.Itcanpreventthegamefromgoingtoofarinthewrongdirection,whichwouldcostalotoftimeandmoneytofix.Itiseasiertofixagameintheearlystages,ofcourse.

Here’showyoudoit.First,selectasmallgroupofplayerstotestyourgame.Theymustnotbeselectedfromthedevelopergrouportheirfamilies.Thebestchoiceisagroupselectedfromthegame’stargetgroup.Fiveorsixissufficient.

Thetestersaregiveninstructions:theyaretoplaythegameaccordingtotherulesthatareprovidedforafixedtime,usuallyfifteenortwentyminutes.Thentheyareallowedtoproceed.Thetestersareobservedcarefullyduringthetesttoseewhatthataredoing,whichpathstheyselect,wheretheyhavedifficulty,andwhere they seem to be having fun.The observers should not be on the actualdevelopmentteam.It’scommontorecordthesesessionsonvideo,andtheteam

Page 230: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

canwatchthose,butdeveloperstendtohaveopinionsandtheplayersshouldnotbeexposedtothem.

Itisofspecialinterestwheretheyarelookingonthescreenandwhentheymakeanyverbalutterance.Verbalizationisanindicationofanextremereaction,one way or another. Growling and cursing are signs of frustration, whereascheeringandlaughingaresignsoffun.Whatishappeningwhenutterancesaremadeisveryimportant.

Theobserversshouldnotofferassistanceunlessaskedforhelp.Obviously,any assistance given should be noted so that the game or the rules can bemodifiedtofixtheproblem.Assistancemustbelimitedtothequestionsasked;theobserversshouldnevervolunteerinformation.Indeed,sometimesoneshouldrepeatthequestionbacktotheplayer.Forexample:

Player:HowdoIfirethisgun?Observer:Howdoyouthinkyoushouldfirethegun?Thisnotonlyindicatesapossibleproblembutalsosuggestsasolution.One

shouldnotdothistoooftenoritwillbecomeirritating.Aftertheplaysessioniscomplete,theplayersshouldrestandsometimesfill

outaquestionnaire.Someofthesearelong,somearebrief,butoneofthebestisfound on Schell Games’ web site(https://www.schellgames.com/blog/insights/the-definitive-guide-to-playtest-questions):

1 Whatwasthemostfrustratingmomentoraspectofwhatyoujustplayed?2 Whatwasyourfavoritemomentoraspectofwhatyoujustplayed?3 Wasthereanythingyouwantedtodothatyoucouldn’t?4 If you had amagicwand towave, and you could change, add, or remove

anythingfromtheexperience,whatwoulditbe?5 Whatwereyoudoingintheexperience?6 Howwouldyoudescribethisgametoyourfriendsandfamily?

This information is used to give feedback to the developers about whatshould be changed, andwhy. Such a test can be done at almost any phase ofdevelopmentoncesomeofthebasicmechanicsareworking.Thereisatendencytowaituntiltheartisinplace,butthatcouldbeamistake.Itiscriticaltocatchproblemswhiletheyarestilleasytofix.

Thereisalotmoretosayaboutplaytesting,entirevolumesinfact,butthesearethekeyitems.

Page 231: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

SUMMARY

Inthischapter,wealmostfinishthedesignandimplementationof theboatracegame.Theplayer’sboatmovesunderplayercontrol,NPCboatsfollowpre-definedpaths,andcollisionsareidentified.

EXERCISES

1 Selectaweb-basedgameofyourchoiceanddocumentthefollowingaspects:a. Identifyallscreensandtransitions.b. Characterizeallinterfaceactions(keypressesandmouseclicks).c. Doesthegamepossessinternalstates?Identifythem.

2 Discuss thepros and consof using themouse as an interactionmechanisminsteadofkeysonthekeyboard.

3 Therearemultiplesoundeffectfilesformanyoftheeffectsusedinthegame,and as described the system chooses one at random every time a sound isneeded.This could result in the samesoundbeingplayedmany times inarow,defeatingthepurpose.Deviseaschemethatmakesitimpossibleforthesamesoundtobeplayedtwiceinarow.Implementthatscheme.

4 Createordownloadasoundeffect that representsa typicalaudiencesound,suchasclapping,pounding,orahornblowing.Edit the soundso that it isacceptable in the context of the game (i.e., adjust the pitch or duration,reducenoise).Thenhavethissoundplayedatrandommomentsduringgameplay.

5 Writeashortvoiceovertobegintherace—somethinglike“Racersprepareforthe start.” Record using any equipment available, such as a VOIPmicrophone; thenaddambiancesuchasecho.Play thisat thebeginningoftherace.

RESOURCES

SoundEffectsThesoundsfromSoundBible.com(http://soundbible.com/about.php)thatare

labeled “public domain” or “creative commons” can be used without fee ingames.Attributionshouldbegiven.

Someofthesoundeffectsweredownloadedfromfreesfx.co.ukorarebasedonthoseeffects(http://www.freesfx.co.uk).

Page 232: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

SoundEditingAudacity– Thisisfreelydownloadableeditingsoftwarewithahighdegree

offunctionality.IfsavingasanMP3isneeded,you’llhavetodownloadtheLAMEMP3encoderandinstallit(http://audacity.sourceforge.net/).

Goldwave – Freely downloadable sound editor with a large set of audioformatsinwhichsoundscanbesaved(http://www.goldwave.com/).

LAME– MP3encodingsoftware.(http://lame.sourceforge.net/).

GraphicsEditingPaint – Comes with Windows and is a highly underestimated tool for

puttingtogether2Dimages.LView– AnimageeditorthatisavaluableadditiontoPaint.Itisespecially

useful for making backgrounds in GIF images transparent. Freedownload, but you should send them money if you like it(http://www.lview.com/).

REFERENCES

1 FernandoBevilacqua. (2013).Understanding Steering Behaviors: CollisionAvoidance. https://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-collision-avoidance--gamedev-7777.

2 JeremyGibsonBond.(2014).IntroductiontoGameDesign,Prototyping,andDevelopment.Addison-WesleyProfessional.

3 Bryce Boe. (2006). Line Segment Intersection Algorithm.http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/.

4 Tracy Fullerton, Chris Swain, and Steven Hoffman. (2004).Game DesignWorkshop:Designing,Prototyping,&PlaytestingGames.CMPBooks,SanFrancisco.

5 ZackHiwiller. (2015).PlayersMakingDecisions:GameDesign EssentialsandtheArtofUnderstandingYourPlayers.NewRiders.

6 Shawn Patton. (2017). The Definitive Guide to Playtest Questions.https://www.schellgames.com/blog/insights/the-definitive-guide-to-playtest-questions.

Page 233: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER8

ANIMATIONAnimationisadiscreteartbynecessity.Thereisnotechnologythatpermits

the recording of the motion of real-world objects precisely; such motion iscontinuous.Inbetweentwopositionsofamovingobjectthereisalwaysanotherposition,andrecordingallofthemisimpossible.Videorecordingscapturestillpictures every 1/30 of a second, andwhen these are played back at the samespeed, they look good enough to seem like they aremoving. It is an illusioncausedbypersistenceofvision.Thehumaneye takessome time toprocessanimage andkeeps it for a fractionof a secondwhileprocessing it.Still imagesdisplayedfastenoughcangivetheappearanceofmotionbecauseoureye-braincombinationcan’tprocesstheimagesanyfasterthanthatinreallife.Animationusesdrawings,humanorcomputergenerated,tosimulateavideoscene.Theobjectsinananimationdon’texistexceptasrenderings.Consecutiveimages inananimation,or frames, showmotionas a change inposition, size,and/ororientationofthedrawnobjects.Withitsmainlooprunningat30framespersecond,Pygamecouldhavebeendesignedspecificallytodisplayanimations.Aprogrammercouldsimplydisplay thenextframeinsequenceeach timeit iscalled,asimpleprogramofabout twodozenlines includingthereadingof theimagefiles.ThisprogramisAnimation01.pyontheaccompanyingdisc.Itreadselevenfilesofapersonwalking.Itdisplaystheminintervalsof1/10ofasecondandthenstartsoveragain.Theessentialcodeis:

i=0

whileTrue:

clock.tick(10)#Makesure1/30secondhaspassed

display.fill((100,100,100))#Clearthescreen

display.blit(images[i],(0,0))#Writecurrentframe

(image)toscreen

i=(i+1)%11#Indexforthenextframe

pygame.display.update()#Updatethescreen

Ifthatwasalltherewastoit,thenthischapterwouldbedone.Inagame,animationsservemanypurposes,but it isonlyincutscene that

Page 234: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

wedisplaytheanimationasafullscreensequenceofframes.Inallothercases,animationsformapartofthescene:perhapsacharacteriswalkingandthegaitisasequenceofframes;perhapsadisplayonavideoscreencanbeseenbytheplayer; sometimesaneffect, likeanexplosion, results fromacollision.Gamesareaspecialcaseforananimator.

Animationforcesanartistordesignertothinkintermsoftimeandmotion.Game design makes a designer think in terms of story, image, and—again—time.Ashasbeensaidinpreviouschapters,agameneednotbereal,butithastolookreal,sotheanimationsthatareusedinagamemustcontributetothelookandfeelofthegame,inthattheymakethegameseemmorereal,buttheyshouldnot takevaluablecomputing timeaway from the renderingorAIcomponents.Themotionintrinsictotheanimationscanmakethegamemuchmoreappealingandlifelike.

Veryhigh-qualitygamesspendahugeamountoftime,energy,andmoneyonhigh-quality animations. The characters in games like Grand Theft Auto arenearlyperfectintheirlifelikequalitiesattimes.Whatwillbediscussedherewillbejustthebasics,andthereferencesareintendedtoleadyoutomoredetailsifanimationisaspecialinterest.

CREATINGELEMENTARYANIMATIONS

Itisprobablyagoodideatodosomethingfirstandthendiscussthetheorylater. Animations consist of a sequence of drawn frames, sowe’ll need somedrawing software.Themost commonly available drawingprogramon aPC isPaint,andalthoughitoffersonlyelementarydrawingfunctionality,itisperfectlyusable,ubiquitous,andfree.Asafirstprojectitisimportanttoselectsomethingsimpletodoandyethavingsomecomplexitiesandgrowthpotential.Oneideaisbilliards.

The animation should be linear and two dimensional, and billiards fits thebill.Thegamehastwowhite(cue)ballsandaredone.Eachoftwoplayersusesoneof thecueballsandstrikes itwith thecue stick,hoping tohitbothof theother twoballs.Whatwill be animated is one stroke.For a first draftwewillneed:

- abilliardtabledrawing,whichisapooltablewithnopockets- renderingsofthethreeballs

ThePaintprogramcanbeusedtocreatetheimages.Theballscanbecircles;the table is a green rectangle with markings and a wide boundary. An initial

Page 235: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

scenarioneedstobesetup:theballthatwillbestruckandthedirectioninwhichitwillmove.Oncethatisdonethesignificanteventsintheanimationneedtobedetermined.Asignificanteventoccurswheneversomethingnewhappens:inthiscasewhenacollisionoccurs.Alloftheseeventsareaconsequenceoftheinitialconfiguration,whichiswhatmakesthisa“simple”animation.

Figure8.1showstherenderingsofthetableandtheballsandoutlinesaplanfortheactionintheanimation.Theplanisthis:ball1istruckbythecuestickand moves along the path indicated by the line until it strikes ball 2. It willbounceoffofball2,againfollowingtheline,untilitstrikesball3.Itwillbounceoffofball3intothecornerandbounceoutagain.Ball2willstarttomovewhenball1strikesit,movingtowardthebottomcushionandbouncingoffofit.Ball3will alsomovewhenstruckbyball1,moving towardandbouncingoffof theleftcushion.

In animation, as in life, the events occur in a particular order, and it isimportant toget it right.The events are collisions, and in this animation, theyare:

1. Ball1collideswithball2.Ball2startsmoving.2. Ball2collideswiththecushion,bounces.3. Ball1collideswithball3,ball3starsmoving.4. Ball3collideswiththecushion,bounces5. Ball1collideswiththecushion,bounces.

FIGURE8.1Initialconfigurationandplanforthebilliardsanimation.Thelinesindicatingthepathsareapproximateatthispoint.

Theanimationwillbeconstructedbasedontheseevents,whicharethebasis

Page 236: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

forwhatwecallkeyframes.Thekeyframeswillbedrawnasthefirsttaskintheconstructionprocess.Thentheanimationframesthatrepresenttimesinbetweenthekeyframesaredrawn—thesearecalledtweens.

The firstkey frame is the initial setupandwillbecalledkeyframe0.Thesecond,keyframe1,representsthecollisionofball1withball2,andwillshowthe contact between the two balls. From this frame can be determined thedirectionstheballswilltakeforthenextfewframes.AsshowninFigure8.2thebounces can be determined geometrically from the motion of ball 1 and theprecise point of contact.We don’t have to do anymath; justmake the angleslookright.Theruleisthestruckballwillmovealongalinethatjoinsthecentersofthetwoballs.Thestrikingballmovesawayalongalinethatis90degreestothatofthestruckball.ThissituationisdiagrammedinFigure8.2also.

Thesecondkeyframewillshowball2strikingthecushion.Ball1willhavemovedtowardball3duringthistimetoo.Ball2willreboundwithanoutgoingangleequaltotheincomingangle.

Keyframe3willshowball1strikingball3.Therulesforthisimpactarethesameasfortheprevious(andall)ball-ballcollisions.Ball2willhavetomovefartheralongitstrackalso.Theremainingcollisionsareball-cushioncollisionsandarejustlikethepreviousone.

Thenextstep,nowthatallkeyframesexist,istodeterminethetiming.First,lettheoverallanimationtakethreeseconds.Weneedtodeterminehowmuchtheball slows down during each time period and how speed is transferred duringcollisions.Ifthespeedisdividedequallyforanyball-ballcollisionandnoneislostonacushionbounce,neitherofwhichisstrictlytrue,thenthetimingscanbeapproximatelydeterminedandallkeyframescanbeputintheirplaces.Time0isthebeginningofmotionforball0andisthetimeofkeyframe0.

FIGURE8.2(Left)Keyframe1,showingthefirstcollision.(Right)Thegeometryofaballtoballcollision:ball2movesalongalinejoiningtheballcentersandball1movesawayat90

Page 237: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

degreestothatline.

Betweenthepointsaandb,ball1ismovingatfullspeed(callitspeed=1).At thatpointball1andball2moveathalfof thatspeed.Ball2movesat thatspeedfromthenon,butball1againsharesitsspeedwhenithitsball3(pointc).Nowballs1and3aremovingat0.25speed,andball2ismovingat0.5speed.

If we get a ruler andmeasure the distances of the paths, we’ll be able todetermineatimeframeforthekeyframes.Figure8.3ashowsthespeedsoftheballandthelengthsofeachpath,whileFigure8.3bshowsthetimeneededatthegiven speeds to travel the path. All distances are relative to the a-b distance,whichwill be treated as 1. It does notmatterwhich portionwe choose to beequalto1;everythingworksoutthesame.Thelongestpathintermsoftimeisa-b-c-f,whichsumsto9.4timeunits.Let’smakethetotalnumberoftimeunitsa nice round 10 and have all of the balls bounce a short distance off of thecushion.Thismeansthat10timeunitsisthreeseconds;3secondsat24framespersecondis68frames,or6.8framespertimeunit.Thus,thenumberofframesbetweenaandbwillbe6.8(wecanroundto7),betweenbandcwillbeverynearly 30, and so on. That is the last critical thing thatwe need to finish theanimation—thenumberofframesbetweeneachkeyframe.

Atableofkeyframetimesandframesbetweenthemwouldlooklikethis:

KeyFrame Time Frame Delta0 0 0 01 1 7 72 3.8 26 19

Page 238: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE8.3(Left)Distancesbetweenkeyframeeventsandthespeedalongthepathsegments.(Right)Therelativetimespentoneachpathsegment.

KeyFrame Time Frame Delta3 5.4 37 304 7.8 53 135 9.4 64 27

Thecolumnlabeleddeltatellsushowmanyframesarebetweenkeyframesandallowsus todo thedrawings.Sobetweenkey frames0 and1 there are7framesinall.

Nowwe simply draw the correct number of frames showing balls on thecorrectbackground(thetable)separatedbythecorrectamountofspace;thatis,forkeyframes0and1,thetweensaredrawingsofthecueballmoved1/7ofthedistanceeachtime.UsingPaint,onewaytodothisistousearulertomeasurethelineonthescreen,dividethedistancebythenumberofframes,andmarkthepositionsalongthepathswithcoloreddotsorlines.Movetheballtothemark,removetherestofthemarks,andsavetheframe;repeatthis.

Numbering the marks is a good idea, because it allows recovery fromprogramcrashes,powerfailures,andotherdisasters.Figure8.4showsthemarksusedforpartofthebilliardsanimation.Notethattherulemarkersdon’thavetobeprecise.Thetweensbetweenanypairofkeyframescanbeassignedtoteamsofartists,andbecausetheactionhasbeencarefullyscripted,theresultshouldbeacceptable. A lot of famous cartoons (Bugs Bunny, for instance) wereconstructed using key frames drawn by the director, usually the best animatoravailable,andthenassigningthetweenstolessseniorpeople.

Page 239: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE8.4Markingthepointsonanimagewheretheballswillbewhenframesarecaptured.Movetheballstothelocationsforeachframe(1,2,3…)andthenerasethemarkersandsavetheframe.

Paint has some serious limitations as an animation tool. It has no timingfacilities at all, does not handle transparency, and can’t even rotate objectsexceptby90degrees.Photoshopcandealwithtransparencyandrotationandhasmuchmoreadvancedimageeditingfacilities;itcanbeexpensivethough.Flashisdesignedtodoanimationsandcandoeverythingyoumightwant,butitisalsocostlyandisdisappearingfromtheWeb.

Theotherwaytoconductananimationiscalledthestraightaheadmethod,inwhichtheartistdrawsthefirstframe,thenthenext,andsooninorder.Usingthismethodisfineiftheentirethingisdonebyasingleartistandifnoseriouserrorsaremade.It’squitehardtofixasingleframe,anditwouldbelikelythattheanimationwouldhavetoberedonefromthepointoftheerror.We’lllookatthismethodlaterinthechapter.

Thecompletebilliardsanimationcanbefoundonthedisk,anditisavailableasaGIF,MP4,andAVIfile.TheGIFistheoriginalandiscleanest.

ANIMATIONMATH

In order to be good at animation, an artistmust have an understanding ofhowthingsmove.Livingthingsmoveinadifferentwayfromnonlivingthings,andallhavea“natural”motionfromtheperspectiveofahumanviewer.Viewerstend to be uncritical of themath and physics andmore critical of the general

Page 240: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

quality of the perceivedmotion, butmovement that is technically incorrect islesslikelytobeacceptable.Let’slookatsimplecasesofmovementofinanimateobjects.

Balls and rocks and feathers move in the environment as described byNewton’sLawsofMotion,ofwhichtherearethree:

1. Inertia.Everyobjectthathasweightwillremaininitscurrentstateofmotionuntilaforceisappliedtoit.

2. Constant acceleration. An object accelerates in the direction of the forceappliedtoit.Thegreatertheforce,thegreatertheaccelerationgiventotheobject.Foragivenforce,thegreaterthemassoftheobject,thesmallerwillbetheacceleration.ThefamousequationthatdescribesthisisF=m*a.

3. Foreveryactionthereisanequalandoppositereaction.Ifaforceisappliedtoanobject,theobjectreactswithanequalandoppositeforceonwhateverapplied the force.For instance, if your kick a ball, it pushesbackonyourfoot.

What do all of these rulesmean in the context of animation?They definewhatismeantbyrealityandreasonablenessintermsofobjectmotion.Thefirstlawhasbeenobservedbyeveryonemainly as friction.Wedon’t expect that aboxthathasbeenpushedwillmoveforever,becausethat’snotwhatwesee.Wedoexpectittoslowandstopbecauseoffriction,andthatforceispresentinallmotionobservedbeforethetwentiethcentury.Ifwe’dbeenlivinginouterspaceourwholelives,thenthefirstlawwouldappeartousinamoreliteralfashion—objects thatmovedotendtocontinuetomove.Frictionisnotamajor issueinspace,atleastnotforbasiclinearmotion.

The second lawdefineshow thingsmovewhen theyarepushedorpulled,andagainour interpretationofmotion thatwesee isdefinedbywhatwehaveseenbefore.Thislawismostobviousinfallingobjects.Anobject thrownintothe air slows, stops, and falls backbecause the force of gravity acts on it.Anobject thrown up and horizontally moves in a parabola, the vertical motionbehavingaspreviouslydescribedandthehorizontalmotionbehavingaccordingto thefirst law.Ofcourse, thereareotherequations that relatespeed,position,andacceleration,andthoseareessentialtodeterminingobjectpositions,buttheyarealmostalwaysrelatedtoforcesapplied.

Thethirdlawismoresubtleandisillustratedinday-to-daylifeasreactiontocollisions.Objectsthatcollidedon’tgenerallyjuststopmoving,theybounce.Anobvious example is the game of pool. The cue ball strikes another ball andimpartssomeofitsspeedtotheotherball,makingitmove.Theotherballkicks

Page 241: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

back and slows the cue ball and nearly always makes it change direction.Cartoonanimationsexaggeratethiseffectandsometimeshavetheobjectsdistortinshapeduringacollisionandthenreturntonormalform.

MotionEquationsThe elementary math that describes motion is known to most people

intuitively. Distance, velocity, and time are related in an obvious way.Whendrivingacarat60milesperhour(MPH)foronehour,weendupdrivingfor60miles.Itseemssimpleenough,andalldriversknowthis.Theequationis:

distance=speed*time

or

d=v*t

Physicistsusethelettervtorepresentspeedveryoften.Itstandsforvelocityandisdifferentfromspeedtechnically,butfornowitwillbetreatedthesame.Objects in an animation must adhere to this relationship, or they will lookstrange.

Acceleration is less intuitive. It is the change in velocity as a function oftime,andwedosee it everyday:acar starting tomovewhena lightchangesfromredtogreenisaccelerating.Elevatorsacceleratewhenthedoorclosesandstarttomoveupordown.Droppedobjectsacceleratedownwardandthenagainwhen they strike the ground and stop moving. In general, an object havingaccelerationaforatimeperiodtsatisfies:

speed=acceleration*timeorV=a*t

Iftheobjecthasaspeedv0beforeitstartstoaccelerate,thenthathastobeconsidered,andtherelationshipbecomes:

v=a*t+v0

Finally,wecanfindthedistancetraveledbyanacceleratingobject:

Page 242: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Thisisveryimportant,becauseitprovidesthewaytocomputethepositionof an accelerating object at any time. Falling and bouncing objects areacceleratingandare themostcommonexamples, so let’sconsideranobject, aball,whichisfalling;theaccelerationduetogravityisa=32ft/sec2.Assumethatitisdropped,sov0=0.Atintervalsof1secondwehave:

time distance(ft)1 162 643 1444 2565 4006 576

Clearlythedistancebetweenconsecutivepositionsoftheballisnotequallyspaced.Ananimationofthefallingballwouldhavetobedrawnwiththisfactinmind.Nowconsiderthesituationofaballbeingthrownupward.Thereisnowaninitialvelocity,andtheaccelerationopposesthatvelocity;thatis,thevelocitystarts as negative (meaning moving upward), against the force of gravity. Afastball can be thrown with a speed of up to 106MPH, but let’s reasonablyassume that the ball is thrown upward at 35MPH, which is 103 ft/sec. Thisvelocityopposestheaccelerationgivenbygravityandsowillbepositivewhileaccelerationisnegative.Again,atintervalsof1secondwehave:

time 1/2at2 v0t distance(ft)

1 -16 103 872 -64 206 1423 -144 309 1654 -256 412 156

Page 243: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

5 -400 515 1156 -576 618 427 -784 721 -63

Accordingtothistable,theballmovesupwardforalittleover3secondsandthen falls back.At time t=7 the ball is 63 feet belowwhere it was originallythrown. At what time does the ball stop moving upward?When the velocitybecomeszero,andusingv=a*t+v0,thattimeis:

Figure 8.5 shows this ball-throwing example as points drawnon a grid.Acritical thing to notice is thatwhen the ball ismoving its fastest, the distancebetween consecutive drawn points is the greatest. That’s because in the fixedintervalbetweencalculationtimes,theballmovesfartherwhenitmovesquickly.This isquite a simple idea,but it is critical in ananimation,whereonly fixedintervalsamplesareseen.

Page 244: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE8.5Ball-throwingexperiment.Thepositionoftheballatselectedpointsintime.

Onemorebitoftheoryandthenwecandrawsomethingelse.Aquestionofsome interest iswhere is the ball in themiddle of any time interval? At timet=1.5theballwillhaveaheightofbetween87and142feet,butwhereexactlyisnot known from the graph. We can use the equation to figure it out, but asanimatorsweareinterestedinthepositionrelativetotheothertwopoints.Isitinthecenter?No.

Let’s look at the dropping ball again. The equation covering thiswas d =1/2at2,andweknowthatattimet=1ithasfallen16feetandatt=2ithasfallen64feet.Att=1.5,halfofthetimebetweenthosetwopoints,d=8*1.5)2=36feet.Thisis20feetfromthefirstpoint(t=1)and28feetfromthesecond,or20/48ofthe distance between the two points, or almost 0.4 of that distance. So,whendrawingthe tweens, the tween in themiddle in termsof timeshouldbedrawn40%ofthedistancebetweenthetwokeyframes.Thisprocesscanberepeatedforothertweens;althoughitisnotexactitwillbecloseenough.Asaresult,thedistancebetween theballs in successive frameswill increase,which is correctaccordingtointuition.

Insummary,basicphysicscanbeusedtocalculatethepositionsofobjectsinframes.Inparticular,thetweenscanbegeneratedusingthefundamentalmotionequationsforobjectsundergoingsimplemotion:falling,rolling,andsoon.

REACTIVEANIMATIONS

Whatwillbecalledreactiveanimationislikelythemostcommonsorttobefoundinavideogame.Simplyput,itisananimationthatrepresentsareactiontoaneventinthegame:forexample,anexplosionorfireafteracollision,ortheshatteringofabrittleobjectthathasfallen.Thesetendtobequitebriefandnotnecessarily easily modeled by physics. A car crashing and exploding is anexample. The animation is short, often has a random component, and can beaccompaniedbyanexternalsoundeffect.

Many such animations are built with simple tools using a straightaheadmethodology.Thatworksprettywellbecausetheytendtobeveryshort,runningbetween 1–2 seconds, which is 24–60 frames. Each drawing is a variation,sometimes a slight one, of the previous frame. Using computer tools it ispossible to start drawing a particular frame using the previous one by justmovingpartsofitaround.

Considerananimationofaballoonpopping.Startwithaballoon,asshowninFigure8.6. Ineach successive framepartsof theballoon from theprevious

Page 245: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

frameareerasedandmoved.Becausetheballoonisexploding,thepartsshouldbemovedawayfromthecenter.Theexplosionitselftakesframes15through23,whicharetheonesshowninthefigure.Itshouldbeclearhowsuccessiveframeshavebeenbuilt.ThePainttoolseraseandselectareusedtoremovepartsoftheballoonandmoveotherpartsawayfromthecenter,givinganexpandingvolumeofsmallerballoonparts.

The same technique can be used to build short animations of explosions,impacts,rocketexhaust,andotherevent-basedvisuals.Eachframeisarandomvariation of the previous one, and thisworkswell so long as the animation isshortandnot repeated. Ifplayed ina loop theanimation loses its randomness,andtheviewercanseedetailsnotintended.Thesearelikesoundeffects;iftheyareplayedtoooftentheylosetheirimpact,somultipleshortanimationscouldbethesolution.

FIGURE8.6Drawnframesfortheballoon-poppingsequence.Eachframeisavariationoftheonebefore,createdbyarandomeditwiththeoverallplaninmind.

Reactive animations will occupy a small portion of the screen for a veryshorttime.Itisimportanttoplacetheframesinthecorrectspotineachframe.Considerananimationofasmallexplosion,perhapsahandgrenade.Thismustbe seen at the locationwhere the grenadewas located just before it explodes,meaningthatitcouldbedrawnanywhereonthescreendependingontheplayinthegame.

Intermsofsoftware,theneedforanimationsinspecificlocationsimpliesthe

Page 246: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

need for software that willmanage the animation, just aswe had software tomanage thesoundclips.Ananimationnotonlyconsistsofasetof framesbutalso a current framebeingdisplayed, a location, a frame rate, andpossibly anorientation,inthecaseof3Dgames.Weneedawaytostartandstopanimationstoo, and somemightbe linked to a sound that is tobeplayed simultaneously;soundcanbeapartofananimation,but for reactiveanimations it isneveranintegralpartofit.

Let’sdesignananimationmanager forgames, startingwithwhatweknowrightnow.Itwillpossessanarrayofframes(images)andawaytoreadthemin.Includedwillbeaway tonormalize the frames; they shouldclearlyallbe thesamesize.We’llneedawaytoplayandstopthedisplayofframes,andtheywillbe displayed at a specified point on the screen. Soundwill also bemanaged.Hereiswhatanoutlineofthis,implementedasaclass,wouldlooklike:

classanimate:

def__init__(self,xx,yy):

self.xpos=xx#Positiontoplacetheanimation

self.ypos=yy

self.frames=()#Imagesforthisanimation

self.nextFrame=0#Nextframetobeplayed

self.Nframes=0#Totalnumberofframes

self.soundName=“”#Nameofthesoundfileforthisanimation

self.playing=False

defplay(self):

defstop(self):

defpause(self):

defsetPosition(self,x,y):

defgetPosition(self):

defsetSoundName(self,s):

defaddFrame(self,p):

defdraw(self):</CODE>

Touseananimationinagame,aninstanceoftheanimationclasswouldfirstbedeclared.Theframeswouldthenbereadin.Itiscommontohaveapatterninthe file namesof the frames that canbe recognizedby aprogramand read inautomatically.Wewill have a text name ending in digits and then “.” and thesuffix that defines the image file type (“jpg,” “gif,” etc.). For the balloonanimation the files are “balloon00.png,” “balloon01.png,” and so on in anobvioussequence.Theanimationclassisgiveneachoftheanimationframesinproperorder,anditsavestheminaninternaltuple.Theanimationwillbedrawnstartingatthexandycoordinatesprovidedwhentheclasswasinstantiated,butthispositioncanbechangedusingthegetPositionandsetPositionmethods.

Page 247: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Toplayananimation, instantiateitandset theinitialposition, thenaddtheframes.Calltheplaymethodtostartplayingit,andensurethatacalltoitsdrawmethod occurs someplacewithin themain loop.Thedrawmethod causes thecurrent frame to be rendered into the graphicswindow.The animation frameswillbedisplayedinorderandwillloopuntileitherstoporpauseiscalled.

Example:

ac=animate(20,30)#Instantiate

...

foriinrange(1,N):#Readtheimagesthatrepresenttheanimation

im=pygame.image.load(“imagefilenameN“)

ac.addFrame(im)

...

ac.play()

whileTrue:

...

ac.draw()

Asacompleteexampleoftheuseofthisclass,imaginethatwehaveagamethatusesaninitialscreenwithasmallanimatedfeature—ajetofgasorsteam.The screen will consist of a graphic, and on top of this will be played ouranimation.Figure8.6showsthescreenwiththeanimatedsectionoutlined.Theframesoftheanimationareplayedsequentially,inthiscaseasaloop,afterbeingtranslated towindowcoordinates (28,156), theareacorresponding to thebox.After initialization, each frame is displayed there in succession using thefollowingcodethatusestheanimateclass:

FIGURE8.7Animatingaportionofascreen.Thesteamjetistranslatedtothecorrectpositionbeforedisplay.

importpygameimportanimateClass

Page 248: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

pygame.init()clock=pygame.time.Clock()display=pygame.display.set_mode((800,512),pygame.SRCALPHA,32)

ac=animate(28,156)background=pygame.image.load(“002.jpg”)

foriinrange(0,17):ifi<10:im=pygame.image.load

(“b00”+str(i)+”.jpg”)else:im=pygame.image.load

(“b0”+str(i)+”.jpg”)ac.addFrame(im)

ac.play()

whileTrue:clock.tick(10)display.blit(background,(0,0))ac.draw()pygame.display.update()

Thisanimationsoftwareobjectseemsreasonablegivenwhatweknowrightnow.Itmaychangealittleasmorerequirementsareseentobeneededbyothertypes of animations. The frames of the jet animation are built startingwith asmall image cut from the screen.This image has the steam added to it and issaved,thenthesteamisvariedabitanditissavedasasuccessiveframe,andsoon until enough frames (in this case 17 in all) are created. In that way thebackground remains constant and compatible with the rest of the existingbackground.Anotherwaytodoasimilarthingistousesteamframeshavingatransparentbackgroundcolor.

Theanimation isplaced into thebackgroundwhere itbelongs.There isnoreasonthattherecouldnotbemanyanimationsplayingatthesametime,aswillbeseenlaterinthischapter.

UsingRealImagesUntilnowtheanimationshaveconsistedofdrawnimageslinkedtogetherin

asequence.Thereisnoreasonwhyarealimagecannotbeusedatthestarting

Page 249: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

point.Therearetwomainwaystodothis:tovaryarealimageabit,aswe’vebeendoingwithdrawings,ortouseashortvideothathasbeenconvertedintoastillimagesequence.

Ifasinglerealimageistobeusedasastartingpoint,theprocessissimilartotheonewe’veusedbefore:manipulate theoriginal image tobecomea secondframe, then the third, and soon. It’s a bit trickier to edit captured images andkeepthemlookingreal.Partof theproblemis lightandshading,whichinrealimagesiscontinuous,andpartisboundariesbetweenobjectsinthescene,whichincapturedimagesarenotprecise.

Considertheexampleofacandle.Someimagesofaburningcandlecouldbetakenusingacellphonecamera.Takingenoughtobeusedasconsecutiveframesin an animation is possible in this specific case, because candlesdon’t changemuchbetweentwoimagesafewsecondsapart.Theflamemaynotbehaveaswewishintheseframes,andsoeditingoneortwointoasequenceoftwenty-fourtoforty-eight isprobablyamorepractical idea.These imagescanbeusedas thebasisforasetofanimationframes:eachonecanbeedited,shearingtheflame,changingitsshapeandcolor,andsoon.Usingrealvideodataisanotherviablealternative.Thefirststepistoextractthestillframesfromavideoimage,andthisrequiresspecialsoftwaretools.Anexcellent video creation/extraction tool is VideoMach, which has a freedownloadableversionandwhichisveryinexpensiveinitspaidform.AusablecopyofthissoftwareisincludedontheaccompanyingCD.

Extracting frames is exceptionally simple: load the video and saveas (forinstance)jpg.Theresult isacollectionofJPEGfiles in thesavedirectory thatareconsecutiveframesfromthevideo,andthesearenamed“00.jpg,”“01.jpg,”and soon.These files canbeplayed as if theywere an animation, and itwilllook just like a video so long as the frame rate is the same as in the originalvideo,usually30framespersecond.

VideoMachcanalsotakeasetofframesandcreateavideoinoneofadozenformats,includinggifandavi,andthisisavaluablefacilityforpreviewingtheanimationsbeforeinsertingthemintothegame.SimplycreateandplayanAVIfileorusethebuilt-inpreviewfacilitytoseehowsmooththeframetransitionsare, whether the lighting is good, and if there are artifacts. Figure 8.8 showsVideoMachbeingusedtomakeanaviversionoftheballoon-poppinganimation.

Page 250: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE8.8UsingVideoMachtocreateanAVIvideofilefromindividualframes.

Microsoft’sMovieMaker toolcansimilarlycreateavideofromstillframes,but it requires theuser to specify thedurationof the framesmanually, so it issomewhat less convenient, and it can’t save in the same variety of formats.Mac’siMoviecanalsoexportstillframesfromavideo.

AMBIENTANIMATIONS

Ambientanimationsareusedtoprovideinterestingbackgroundactivity.Ananimationofacomputerscreenordatadisplaythatappearsonacontrolpanelinthebackgroundwouldbeanexample.Sowouldsmokeorsparksfromdamagedequipment.Theseveryfrequentlyhavetoloop,andsotheycannotrepresentanobviouspatternifthatcanbeavoided.Theyalsoarerequiredtobeplayableinmanylocationssimultaneously.Acontrolconsolecanusethesameanimationinmany positions as digital readouts so long as they are not identicalsimultaneously;theymayneedtobeplayedoutofsync.Theyalsomayneedtoberescaled,skewed,orrotatedtoo.

Making such animations is similar tomaking a reactive animation. It’s theplaybackthatcanbedistinctive.Theneedsofsuchanimationswillbeimportantincontinuingthedesignoftheanimateclass.Consider,asapracticalexample,thecreationofacontrolroomforaspacecraft launch.Inpracticetherewillbescoresofactivescreensvisible,butlet’slimitittofive.TheimagethatwillbeusedforthebackgroundisshowninFigure8.9,anditisinfactastillphotoofthe Russian control room for the International Space Station. The three large

Page 251: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

screens at the front and a coupleof smaller oneswill have animateddisplays.Thescreenswillbethelocationoftheanimateddisplays,andtheyarecoloredgreen in the original image. The green simplymarks the locations and is notneededforthedisplay;thisisnotgreenscreentechnology.

The two small screens in the lower part of the image are essentiallyrectangular and can be overwritten with an animation as we’ve done before.Sincethescreenslooklikecomputerterminals,wecanmakeasetofframesthatshowtext,images,andwindowsscrollingpastandpoppingup.Makingalargeset of such animations, one for each display in the image, would be timeconsumingandnotworththeeffortjustforaneffect.Whatcanbedoneinsteadis to display the same sequence of frames in each location but start from adifferentpointandmaybeatdifferentspeeds.Thisidearequiresmodificationstotheanimateclass.

FIGURE8.9Thecontrolroombackgroundimageshowing“greenscreen”areaswhereanimationswillplay(backgroundimagefromNASA).

Theability toplay the sameanimation inmore thanoneplace implies theneed for anoperation thatmakes a copyof ananimation.Eachcopycouldbeplacedatadistinctlocationinthescene.Theanimateclassdoesthisthroughamethodcalledcopy inamodulenamedcopy that returnsa reference toanewanimateobjecthavingthesamepropertiesastheonecloned.So,theassignment:

ad=copy.copy(ac)

createsacopyofacthatcanbelocatedelsewhereanddisplayedseparately.

Page 252: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Theframesare thesame.Thecodesimplycreatesanewanimateinstanceandinitializesallofitslocalvariablestothoseoftheinstancebeingcloned.

Thatsolvespartoftheproblem.Next,weneedtheabilitytoslowdownthedisplayofframesforananimation,andtobeginplayingthesequenceofframesanywhere we choose. For sequencing a new procedure named setNext() hasbeencreatedwhich simply sets thevalueof thenext frame tobeplayed.Playnormallystartsatframe0,butacalltosetNext(12)willbeginplayatframe12.Now,twoadjacentscreenscanplaythesameanimationandseemasiftheyaredistinct.

TheproceduresetRateslowsdownplayoftheanimation;setRate(1)isthedefault, which plays frames at a rate of 1 per call to display(). A call tosetRate(2)meansthattwocallstodisplay()willbeneededtochangetheframedisplayed, and setRate(4) means that four calls to display() will result in achangetotheframe.ThelargertheparametertosetRate(),theslowerwillbetherateatwhichframeswillbedisplayed.

The three large screens in the scene present a new problem: they are notactuallyrectangular.Theyareinreallife,naturally,buttheyarebeingobservedfromaboveandtotheside,soperspectivehasgiventhemirregularshapes.Howcan we play a rectangular image frame in such a space? By using texturemapping.

In the animation frame in Figure 8.9, the large green screens are notrectangles.Eachpixelineachofthosescreensmustbedrawnfromapixelinarectangularimage,soweneedtodefineamappingbetweenthequadrilateralonthescreenandtherectanglethatistheimage,ortexture,tobedrawn.Therearemany ways to do that, including perspective transformations, bilinearinterpolation,polynomialwarping,andsoon.Mostgraphicssystemswilldothismapping automatically if the coordinates that correspond to the corners of thequadandtheimageareprovided.Pygamedoesnotoffer thatfacility,sointheanimationclass,amethodnamedsetSizeisprovidedthatgivesthecornersoftheimage in screen coordinates.When draw is called amapping of pixels to thescreentakesplacesothatirregularshapescanbefilledwithimages.

WhencallingsetSizea listofx,ycoordinates isprovided,beginningat theupper left andmoving clockwise. It onlymaps images onto quadrilaterals, sotherewillbeeightparameters.Forexample,thelargegreenscreeninthecenterofFigure8.9hasscreencoordinates(267,73)(478,73)(471,225)(276,224).Settingthisupasananimateclassanimationwouldbe:

ac=animateClass.animate(0,0,display)#Createtheinstance

foriinrange(0,35):#Readtheimages

ifi<10:

Page 253: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

im=pygame.image.load(“screen1/00”+str(i)+”.jpg”)

else:

im=pygame.image.load(“screen1/0”+str(i)+”.jpg”)

ac.addFrame(im)

ac.setSize(267,73,478,73,471,225,276,224)#Setthelocation

InFigure8.9,therearefivegreenscreensthatareintendedtoholdanimations.Allcanbeplayedintheirproperplacesatthesametime:simplycreatethefiveinstancesandreadtheimages,callsetSizeforeachonespecifyingtheirlocationandshape,playthem,andthencalldraw()foreachonewithinthemainloop.Aprogramthatdoesthisisnamedcontrol.pyontheaccompanyingCD.

CHARACTERANIMATION

Creatinganimationsof livingcreatures isamong thehardest tasks invideogames, and animating humans is the most difficult. It’s because living thingsmoveinverycomplexways,andviewersareveryfamiliarwithhowthatmotionshould look and are therefore quite critical of flaws. Character animation is aspecializedsubject, andwewill lookat themostcommonlyneeded typehere:gait.

If your gamehas a human character, itwill need at the very least towalkaroundthegamespace.Thelegsandarmsmustbehaveaswehumanobserversexpectthemto.Wewillneedtobuildashortanimationofthecharactertakingasinglecompletestep,andthenthiscanbeplayedwheneverthecharactermoves.Ofcourse,theavatarmayneedtojump,shoot,reach,crouch,ordomanyothertasks,butcharacteranimationisacomplexskillthatdependstoagreatextentontheartist’sabilities.

Animatinggaitisamatterofcreatingasequenceofdrawingsthatshowsthearmsandlegsofthecharacterwalkinginanormalway.FromtheillustrationinFigure8.10,asetofworkablestepsisshown.First(top)isasetofkeyframes,inthiscaseshowingtherightarmandlegofastickfigureduringasinglefullstep. Next the left arm and leg are added and tweens are created (middle).Finally,thecharactercanbefleshedoutovertheskeletonandcolorsortexturesadded.The final sequence here has just enough detail to be useful both as anexample and as an avatar. This avatar is carrying a pack of some kind on hisback.

Whentheavatarismoved,forexamplebypressingtherightarroworthe“d”key,theframesareplayedinsequenceandthepositionoftheavatarismovedtotheleft,givingthedesiredeffect.Theframescanberedrawnorsimplyflipped

Page 254: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

horizontallytoallowtheavatartomovetotheleft.

FIGURE8.10(top)Keyframesforagait,rightsideonly.(Center)Tweensforthegait.(Bottom)Asetofframesforasinglestride.

Thisdiscussionofcharacteranimation is intentionally trivial.Although theactualdisplayofframesissimpleandusesmethodsthathavebeendiscussedindetail, the creation of the frames can be profoundly complex. If you have theability to create realistic motions in a frame sequence, then your games willprofitfromthisskill.Ifnot,itcanbelearnedor(perhapsbetter)peoplewiththatskillcanbeengagedtoworkforyou.Thecostissmall,andtheimprovementinthequalityoftheresultcanbepriceless.

CUTSCENES

Acutsceneorfullmotionvideo(FMV)isananimatednarrativethatexplainsapartof thegame’s storyorbackground. It isplayedon the full screen likeamovie.Thereisoftenoneatthebeginningofthegame,andoftenonethatservesasatransitionbetweenlevels.Theyaremadeobviousbyachangeinaspectratiotoamorecinematic1.85:1fromthestandardcomputerscreenvalueof1.6:1.Nointeractionwiththegameispossibleduringacutscene.

Thesecanbemadeinanywayonechooses,evenwithliveactionvideo.Theissueagainishowtoplayit.Cutscenescanhaveamuchhigherimagequalitythanthegameproper,andtoreadanddisplaysingleframeswouldtakefartoomuch time and memory to be practical. What you must do is create ananimation, save it as a video file, and play that file at the proper place in the

Page 255: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

game.Thissectionofthebookcouldbecalled“HowtousePythonvideoclassesandfunctionstodisplayvideoinagame.”Toplayvideosweuseatrick.

Pygameusedtohaveamovieclassbutiswasremoved.Itapparentlycausedmoretroublethanitwasworth.So,howcanweplayacutscene?Itmustagainbedoneframebyframe.However, it isnotnecessarytoreadallof theframesintomemoryfirst,whichcoulduseagreatdealofspace.Insteadwecanreadtheframes just beforewedisplay themand reuse the same image for each frame.Playing a video in thiswaymeans playing the sound concurrently, so the cutscenevideowouldhavetobeprocessedinthefollowingway:

1. Eachoftheframeswouldhavetobeextractedintoadistinctfile.2. Theaudiotrackneedstobeextractedintoa.wavor.mp3file.

Here’ssomecodethatwilldothis:

importpygame

pygame.init()

clock=pygame.time.Clock()

display=pygame.display.set_mode((800,512),pygame.SRCALPHA,32)

pygame.mixer.music.load(“xx.mp3”)#ReadthesoundtrackasanMP3file

i=0

pygame.mixer.music.play(0)#Startplayingthesound

whilei<=253:

foreventinpygame.event.get():

ifevent.type==pygame.QUIT:

exit()

#Readthenextframe

ifi<10:

im=pygame.image.load(“screen1/00”+str(i)+”.jpg”)

elifi<100:

im=pygame.image.load(“screen1/0”+str(i)+”.jpg”)

else:

im=pygame.image.load(“screen1/”+str(i)+“.jpg”)

i=i+1

display.blit(im,(200,140))#Displaytheframe

pygame.display.update()

clock.tick(30)

pygame.quit()

Page 256: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

There are other modules that can accomplish this. They includemoviepy,pygamevlc,PyMedia,andothers.Eachmustbedownloadedandinstalledbeforeuse.

ANIMATIONSINTHEBOATRACEGAME

Therearenotverymanyanimationsintheboatrace,andfortunatelytheyareallbrief.Theyinclude:

1. Thewakeofaboatunderpower2. Birds3. Anexplosion4. Flags

WAKES

Thiswillbe awhite trail behindaboatwhen it ismovingunderpower. Itshouldmoveinsomewhatrandomwayssoastoseemlikeawaterwave.There’snoneedforkeyframeshere;straightaheadanimationisfine.Startwithoneoftheboatsandabackgroundofbluewater fromthe terrainmap.Copy theboatintotheimageandthendrawasetofwhiteandgreyextensionsfromtherearofthe boat, saving each one as a separate numbered file. Paint or any drawingprogramcanbeused;thisisarelativelylowresolutiongame.Figure8.11showsapartofthisprocess.

Thefinalstepistoisolatethewakeanimations.SimplyclipthemoutofthePaintimage,makingcertainthatallarethesamesizeandthattheentirewakeiscaptured each time. Figure 8.12 shows some of the individual wake frames.Whentheboatsareunderpower,thesewillbedrawnbehindthem.

SUMMARY

Inkey frame animation the frames that define themotion are created first,and then the frame inbetween those (tweens) aredrawn.This lends itself to aproduction line system that usesmultiple animators. In addition,we canmoreeasilysynchronizekeymomentsintheactionwithspecificframes.However,theuseofmanyartistscanleadtoinconsistentdrawings.Instraightaheadanimationwecreatethefirstframe,thenthesecond,thenthethird.Thisleadstoartisticallyexciting images and is goodwhen there is a lot of action.On the other hand,

Page 257: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

thereisalotofpressureontheanimator,asthismethodrequiresagreatdealofconcentration. It’s also hard to correct, and some kinds of specific timing arehardtodo(e.g.,lipsynch).

Figure8.11CreatinganimationframesforaboatwakeusingPaint.(a)Aboat.(b)Waterbackground.(c)Randomwhiteareasdrawntorepresentthewake.

Figure8.12Sampleframesfromthewakeanimation.

Basicphysicscanbeusedtocalculatethepositionsofobjectsinframes.Inparticular,thetweenscanbegeneratedusingthefundamentalmotionequationsforobjectsundergoingsimplemotion:falling,rolling,andsoon.

Areactiveanimationislikelythemostcommonsorttobefoundinavideogame,anditrepresentsareactiontoaneventinthegame:anexplosionafteracollision, for example. Ambient animations are used to provide interestingbackground activity. An animation of a computer screen or data display thatappearsonacontrolpanelinthebackgroundwouldbeanexample.Acutsceneisananimatednarrativethatexplainsapartofthegame’sstoryorbackground.Itisplayedonthefullscreenlikeamovie.

Creatinganimationsof livingcreatures isamong thehardest tasks invideogames and should be avoided if possible or hired out to a professional if not.Avatarmotionsdependoncharacteranimationandneedtobegood.

Page 258: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

EXERCISES

1. Make a short (<10 second) animation of a ball bouncing.A basic solutioncouldbealoop,butreallyitshouldbouncetoalowerheighteachtimeandfinallyenduprestingontheground.

2. Makeashortanimationofaballbouncingdownsomestairs.Youmayusetheanimationfromexercise1asastart.

3. Createavideofilefromoneoftheanimationsinexercises1or2.Useanytool you like, but document the process you used in a brief (< 5-page)document.

4. Takesomeimagesofwaterflowingfromafaucet.Createashortanimationofthisflowanddisplaytheframesasananimation.Usinganytoolyoulike,createavideofileofthisanimation.

5. Makeavideoofwaterflowingfromafaucetandextracttheframes.Selecttwenty-fouror soandplay them in randomorder ina smallwindowasananimation.Howdoesitlookdifferentfromavideoofthewaterflowing?

6. Observe the gait of any animal. Try to create an animated gait for thiscreature.Playitbackandtrytofindflaws—keepawrittendescriptionoftheprocessandwhatyoufound.

7. Anentertainingwaytomakeananimationisthestopmotionorstop frametechnique, in which actual objects in an actual scene are moved a bit,photographed, and moved again. Miniatures are often used. Make a stopframeanimationusinganymaterialatyourdisposalandturnitintoavideofile.Plantheanimationusingkeyframes.

8. A common tool used in the creation of animations and films is thestoryboard.Thisisasequenceofdrawings,usuallyincludingsketchesofthekeyframes,thattellsthestoryoftheanimation.Ithelpswiththedesign,anditisusedtopresenttheideatotheproductiongroup.Makeastoryboardforany 30 seconds of animation you choose: a cartoon, perhaps. Part of thevalue of a storyboard is in its presentation so, if you can, present yourstoryboardtoasmallgroup.

RESOURCES

Wideo:Anonlineanimationcreation tool.Youmust signup,but it is free.http://wideo.co/.

Howtoanimateflames:http://www.youtube.com/watch?v=f_cNlQocaV8.Site for downloading inexpensive images for use as textures:

Page 259: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

http://www.dreamstime.com/.VideoMachvideocreationtool:http://gromada.com/videomach/.UnFREEz tool for making animated GIFs:

http://www.whitsoftdev.com/unfreez/.Macintosh iMovie: http://www.macworld.com/product/412943/imovie-

09.html.MovieToImage for getting stills from an iPhone. It’s a $1 app.

http://www.macworld.com/product/599549/movietoimage.html.GOM Media Player can save stills from a video too:

http://player.gomlab.com/eng/download/.Apple’sQuickTime:http://support.apple.com/kb/dl837.GSvideo:http://gsvideo.sourceforge.net/.Storyboard That, an online storyboard creation tool.

http://www.storyboardthat.com/.Gaitsofahorseforanimation:https://www.youtube.com/watch?v=2f2oSAqvrsghttps://www.youtube.com/watch?v=sF2h5Enyaos

REFERENCES

1. Garry Faigin. (1990). The Artist’s Complete Guide to Facial Expression.Toronto,Canada:Watson-GuptillPublications.

2. MaureenFurniss. (2008).TheAnimationBible.NewYork,NY:Abrams.3.KitLaybourne. (1998).TheAnimationBook.NewYork,NY:ThreeRiversPress.4.BrianLemay. (2006).LayoutandDesignMadeAmazinglySimple.Oakville, Ontario: Animated Cartoon Factory.http://www.brianlemay.com/Books/layout.html.

3. Lynn Pocock and Judson Rosebush. (2002). The Computer Animator’sTechnical Handbook. San Francisco, CA: Morgan Kaufmann.6. ChrisWebster. (2005). Animation: The Mechanics of Motion. Burlington, MA:FocalPress.

4. Tony White. (2006). Animation from Pencils to Pixels. Burlington, MA:FocalPress.

5. Tony White. (1986). The Animator’s Workbook. New York, NY: Watson-GuptillPublications.

6. Richard Williams. The Animator’s Survival Kit: A Manual of Methods,Principles,andFormulas.London,UK:FaberandFaber.

Page 260: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER9

C2H6O–FINALSTEPSThe Jet Boat Race game requires a fewmore systems and components in

order to be complete. First, it is not yet a game! The boats have to follow aspecific path inorder to successfullypass the finish line and score.Thegamemusttrackthat.Itismorefuntotrackthetimesofeachboatanddisplaytheminrealtime.Thishasnotbeendone.Thereisnoofficialstartofthegame,andnorecordiskeptofpassingthefinishline,orofthewinner.

Mostof thesoundsarenotbeingplayed.Theanimationsarenoteither, sowhen two boats collide a message is printed; there is supposed to be anexplosion.

Aminimapwould be fun too, and it is not too difficult to implement. It’scommoninracegamestobeabletoseewherealloftheboatsare.

Finallythegameshouldbetunedabitsothatitdoesnotgiveanadvantagetoanyboat,andsothatplaymovesalongquickly.

ANIMATIONS

There are twomain animations in this game: the explosions and thewakefromeachboat.ThesewerecreatedinChapter8buthavenotbeenusedyet.

WakesAllof theanimation framescanbestored ina single image,and thegame

willextracttheneededframejustbeforeitisdisplayed.

Page 261: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE9.1Theanimationframeimageforboatwakes.

Thewakes.png image includeseighteen frameswhereeach frame is83x35pixels.Todrawaframeinpositioniofrowj:

display.blit(im,(100,100),(i*83,j*35,83,35))

Thereare18frames,wecangeneratearandomframenumberandthenconvertitintoapairof(i,j)indices:

k=int(random.random()*18)

i=k//9

j=k%9

There isanother stepneeded,because theboatsare rarelyorientedalongavertical or horizontal axis.The frame,which is a surface in pygame,must berotatedsothatitalignswiththeaxisoftheboat,andmustbetranslatedsothatitispositionedattherearoftheboatbeforeitcanbeblittedtothemainsurface.InChapter2,there,wasanexplanationofhowtoorienttheboatsprite,whichwasused inChapter 7.Nowwe have to add the animation to the back end of theboat,butwhentheboatchangesdirection itshouldstill rotateabout theboat’scenter,notthecombinedcenteroftheboatandthewake.

Accomplishing this is pretty simple. Use a new Surface (named r in thecode)thatiswiderthanthecombinedimagesofthewakeandtheboatby1/2thesizeoftheboat(40pixels).Copy(blit)theboatimageintoratlocation83,thesizeofthewake,andcopythewakeimageat0.Thenrotateanddisplayratthe

Page 262: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

neededlocation.CodetorenderatthecenterofthedisplaySurfaceis:

r=pygame.Surface((251,35),pygame.SRCALPHA)

...

k=int(random.random()*18)#Whichwakeimage?

i=k//9

j=k%9

r.blit(boat,(83,6)#Copyboattor

r.blit(wakes,(0,6),(i*83,j*35,83,35))#Copywake

boatr=pygame.transform.rotate(r,angle)#Rotate

sx=boatr.get_width()

sy=boatr.get_height()

display.blit(boatr,(250-sx/2,200-sy/2))#Display

Thiscodedrawsthewakeusingrandomframes.

ExplosionsWhenaboatcollideswith theshore, it tries to findawayoffof thebeach

usingamethoddiscussedinChapter7.Whentwoboatscollidewitheachother,theydestroyeachother.Theyarecarryingalotoffuelandtheirenginesarehot.Therewillbeanexplosionand theboatswilldisappear.Theywill reappearatthestartingposition,wheretheirchanceofwinningissmall.

Asmallcollectionofexplosionanimationswasgeneratedusingaprogram,andthisprovidesaselectionthatcanbeusedforcollisions.Playerscantellifthesame one is used over and over.When a collision happens the first step is toselectanexplosionanimationatrandom.Therearefiveanimations.

Next the animation should start to play along with the sound of theexplosion.Eachanimationhassixteenframes,andtheseshouldbedisplayedinsequence in place of the boats that collided.Anew state calledEXPLODINGwillbeaddedtotheNPCclassthatwillresultinthenextframeintheanimationbeingdisplayedinsteadoftheboatsprites.ThedisplaymethodmustbemodifiedtotestwhetherthestateisEXPLODINGand,ifso,displaytheanimationinsteadofthesprite.

Afterthefinalframeisdisplayed,thetwoboatsinvolvedmustbeplacedattheiroriginalstartingpositions.Thisisasimplematterofsettingtheirpositionandorientationtotheinitialvalues.Ifoneoftheboatsistheplayer’sboatthen,ofcourse,thescreenviewwillchangeandremaincenteredonthatboat.

Playingtheexplosionanimationisthesameasplayingthewakeanimation.Theframeoftheexplosionisextractedfromalargerimagethatcontainsallofthe frames; in this case the explosion frames are 64 x 64 pixels and there are

Page 263: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

sixteen frames in each sequence. In addition, when the animation starts acorrespondingsoundisplayed.

FIGURE9.2Theanimationframeimageforanexplosionsequence,explode3.gif.TheseareinGIFformatbecausetheyhaveatransparentbackground.

There are five different animation sequences for the explosion, namedexplode1.gif to explode4.gif, and explode5.png (Figure 9.2). The sound filesare exp01.wav and exp02.wav. When an explosion occurs one of the fivesequencesisselectedforusesothatallexplosionsdon’tlookthesame.Thereisatestprogramnamedexplode.pythatteststheanimationandsoundcodeoutsideofthegame.Thisisacommonpractice.Theprogramsetsoffanexplosionatapointwheretheuserclicksthemouse.Thisworksfine,soitcanbeaddedtothegame.

Inthegameitselftheexplosionwilltaketheplaceofthetwocollidingboats.Theboatswillnotbedrawn,andtheframesoftheexplosionwillreplacethem.When thecollision isdetected, theboats enter theEXPLODINGstate and thesound begins to play. In the EXPLODING state the boats are not drawn, andinstead the current explosion frame is displayed.When all frames have beendrawn,thetwoboatsareplacedatthestartinglineagainandthegameresumes.

Insideofthedrawmethodforaboatwesee:

ifself.state==self.EXPLODING:

self.showNextExFrame(ccx,ccy)

else:

display.blit(pygame.transform.rotate

Page 264: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

(self.r,self.angle),(ccx,ccy))

sothatiftheboatisexploding,theboatsarenotdrawn.ShowNextExFramedisplaystheexplosion:

defshowNextExFrame(self,x,y):

globalim,s1,kimage

i=self.frame/4

j=self.frame%4

display.blit(im[kimage],(x-32,y-32),

(i*64,j*64,64,64))

self.frame=self.frame+1

ifself.frame>=16:

self.state=self.NORMAL

self.reset()

FIGURE9.3Anexplosionhappenswhentwoboatscollide.

Theclassvariableself.frame representsthenumberofthecurrentframetodisplay,andkimageistheindexoftheexplosion.Finally,whenthelastframeisdisplayed,theboatisresetbyputtingitbackinthestateitwasinatthestartofthegame.Themethodthatdoesthisisreset.

DeterminingaBoatCollisionThe boat class (npc) has a method that determines whether a collision is

pending(boatCollision),andthishasbeendiscussedindepth.Whatitlacksisamethod that determines if a collision has actually occurred, which is apreconditionforanexplosion.

Page 265: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE9.4Determiningwhentwoboatscollide.

Each boat has a bounding box computed and saved for each iteration. Asimplecollisiondetectionmethodwouldbetodetermineiftheboxesofanytwoboatsoverlap—theseareobject-orientedboxes,soitwillworkokay.Thegameshould allow for some degree of “bumping,” so this may be too severe acondition.Theboxcanbemadesmallertopermitsomeoverlap.

Theobject-orientedboundingboxforeachboatisstoredasfourpoints:ul,ur,lr,andll(upperleft,etc).Thesepointsaredeterminedforeachiterationusinga call to the method update_box in the npc class. A global functionbox_intersect does the math to determine whether the boxes intersect eachother,andifsothentheexplosion,sound,andstatechangearedone.Inthemaingame,loopwecheckallboatsagainsteachother:

ifscreenState==PLAYSTATE:

move()

foriinrange(0,3):#Checkboatcollisions

forjinrange(i+1,3):

ifboatCollided(i,j):#Boom

boats[i].savedx=boats[i].x

boats[i].savedy=boats[i].y

boats[j].savedx=boats[j].x

boats[j].savedy=boats[j].y

boats[i].state=boats[i].EXPLODING#Changeboatstates

boats[j].state=boats[j].EXPLODING

boats[i].frame=0

boats[j].frame=0

snd[int(random.random()*2)].play()#Playsound

If the boats are already in theCOLLIDING state, then nomore has to be

Page 266: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

done,orshouldbe.Collisionisdonelikethis:

defboatCollided(a,b):

ifboats[a].doneorboats[b].done:

returnFalse

boat1=boats[a]

ifboat1.state==boat1.EXPLODING:

returnFalse

boat2=boats[b]

ifboat2.state==boat2.EXPLODING:

returnFalse

returnbox_intersect(

(boat1.ul,boat1.ur,boat1.lr,boat1.ll),

(boat2.ul,boat2.ur,boat2.lr,boat2.ll))

WhileintheEXPLODINGstate,thenpcclassdrawmethodwillreplacetherenderingoftheboatwiththenextanimationframe:

ifself.state==self.EXPLODING:

ifself.frame==0:

self.savedx=ccx

self.savedy=ccy

self.showNextExFrame(self.savedx,self.savedy)

else:

display.blit(pygame.transform.rotate

(self.r,self.angle),(ccx,ccy))

SOUNDS

After buildingmore of the gameplay aspects, the need formore sounds isapparent.Right now, the player’s boat has an engine sound and an explosion.However:

- Westillneedsoundeffectsofbouncesagainsttheshore.- Westillneedexplosionswhenboatsaredestroyed.- Weneedastartingsequence.- Weneedafinishsequence.

EngineSoundsSome time was spent in Chapter 6 showing how engine sounds could be

createdusingAudacity.Thesoundscreatedinthiswayhavebeensavedasmp3filesnamedengineBoat1.mp3 throughengineBoat5.mp3.Each engine sound isdistinct,andeachshouldbeassignedtoadifferentboatinthegame.Thesoundshould play as long as the associated boat is under power. For example, the

Page 267: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

player’sengineshouldplayaslongasthe“w”keyispressed.Asimplemodificationtothepreviouscontrolcodewilldothis.Addaglobal

variableengine_on thathas theobviousmeaning.Now if there are anyof the“a,” “s,” “d,” or “w” keys pressed, a local variable eon will be set toTrue,indicating that the playerwants tomove the boat (turn the engine on). If it isalreadyon,noproblem.Otherwiseturniton(startthesound):

ifeonandnotengine_on:

start_engine()

elifnoteonandengine_on:

stop_engine()

Eachcheckofthekeysthataredepressednowlookslikethis:

ifk[pygame.K_s]:

speeds[0]=speeds[0]-.1

eon=True

Eachtimethroughtheeventloop,thevariableeonisfirstsettoFalsesothatiftheplayerreleasesthekeys,theenginewillshutoff.Thefunctionsthatdotheworkare:

defstart_engine():globalengine_on,sound_on,engine1engine1.play(1000)engine_on=True

defstop_engine():globalengine_on,sound_on,engine1engine1.stop()engine_on=False

Thereareothersounds,and thosewillbe implemented inmoredetailafterwe knowmore about animation andwhenmore of the game rules have beenimplemented.

StartingGunThisisonlyusedatthebeginningofthegame,andsothereisonlyonefile:

start.wav.Thisisplayedwhenthestartingcountdowniscompleted:gun.wav.

FinishThereisasoundthatplayswhenthewinningboatpassesthefinishline.This

soundischeer.wav,andisanaudiencecheering.

Page 268: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

BingWhentheplayerreachesacheckpoint,thissoundplaystoindicatethisfact:

bing.wav.

AudienceThere is a background audience sound playing while the race is running:

audience.wav.

GAMEPLAY

The ideaofa timer is todeterminea timedurationbetweenevents. In thisgameitcouldbeusedtoshowtheplayerstheelapsedtimefromthestartofthegameuntilsomeonepassesthefinishline.

CompletingtheRaceWhenthegamebegins,asspecifiedbytheuserpressingthestartbuttonon

the initialpage,a timercancountdown to theactual start.Let thathappen10secondsafterthegamebegins.After10secondsthegameplaytimerwillbegin,butthesametimercanbeusedtocountdownthe10secondsatthebeginning.Thegamecanbeinoneofthreestates:Initial(countdown),playing,andend.

Intheinitialstatethecountdowntimerisdisplayedontheplayscreen,goingfrom10 to0.Atzero the startinggun is fired, and thegamebegins.Theplayscreenmustnowbedividedintothreestates.Thecountdownstateis:

StartWhenthePlaybuttonispressedontheopeningscreen,thegameentersthe

playstateandthegamecanbegin.Thestartoftheraceshouldnotbeimmediate;theplayershouldhaveafewsecondstoadapt.Asecondmousepresscouldbeused to start the game, but another option is to do a countdown to the start,perhaps five seconds. After that time has passed, the player’s controls willoperateandtheNPCboatswillstartmoving.

Thecountdownshouldappearonthescreenaftertheplaybuttonispressed.Thenumbers“10,”“9,”“8,”andsoonwillappear,followedbythetraditionalgunshottostartthegame.

The countdown can be implemented as a new state that is entered at thebeginning of the game, after thePlay button is selected. In this starting state

Page 269: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

none of the controls will operate. Five seconds after the state is entered thecountdownwillbegin,andatthe“0”counttheracebegins.

TimerTherearetwowaystokeeptrackoftimeusingPython.Likelythebestone

would be to use the time function, located in the timemodule. It returns theexecution time for your program in seconds. So, to time any differential onecoulddothefollowing:

importtime

start=time.time()

…code

end=time.time()

time_difference=end-start

Whentheplaybuttononthestartscreenisselectedthecode

initialTime=time.time()

is executed and thevariable starting is set to true.Nowa functionnamedcountdowniscalledeachiteration,anditreturnsthecurrentnumberofsecondssincetheplaybuttonwaspressed,butbackwardfrom10.When0isreachedthisfunctionsetsstartingtoFalseandplaysthestartingsoundeffect.

#Codeinmovefunction

ifstarting:k=countdown()player.display()boat3.display()boat4.display()pygame.draw.rect(display,

(0,0,0),(500,0,200,400),0)text(“Startin“+str(k)+“seconds”,520,100)return

defcountdown():globalinitialTime,starting,

globalstartdiff=time.time()-initialTimeif10-diff<=1:starting=FalseinitialTime=time.time()gun.play()ambiance.play(loops=-1)ambiance.set_volume(0.1)return0else:returnint(10-diff)

Notice that when the countdown reaches 0, the initialTime is set to the

Page 270: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

currenttimeagain,meaningthatnowthedifferencebetweenthisandthetime()valuewillbethenumberofsecondsthegamehasbeenrunning.Thisisthegametimer.

FIGURE9.5Thestartingtimer.

ThecountdownisshowninFigure9.5.

IntermediateGoalsInordertoensureafairgame,allboatsmustpasscertaincheckpointsduring

the race. The routemoves up the initial fjord,moves right to the final island,around that island and left to the first island, and around that and back to thefjordat the far right.The finish line is at theendof that fjord.Howcan it beensuredthatallofthecheckpointshavebeenreached?

There are a couple of possibilities. A boat could reach a checkpoint if itcomeswithin a specified distance of a specific location on themap. There isonlyonesuchcheckpointatatime,likewaypoints,andwhenoneisreachedthenextoneisselected.Anotherideawouldbetoplaceinvisibleobjectsalongthepath that the boat must collide with. A collision simply marks the relevantportionofthetrackashavingbeencompletedandbeginsanewsection.

The checkpoints are to bemarkedon the screenwith little flags or buoys,andtheboatsmustpassbetweentheseflags.Theymustalsopassthroughtheminthecorrectorder.ThefunctiondrawWaypointsdrawstheflagsonthescreen,anditiscalledforeachiteration.

Oneof theNPCboatsuses theblue flags,and theotheruses the redones.

Page 271: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Theplayerusestheblueflagsalso.

FinishThewinneroftheraceisthefirstboattocrossthefinishline,locatedinthe

lowerrightoftheterrainmap.Itcorrespondstowaypoints29and30,thefinalNPCwaypoints,andwhenitisreachedtheirpositionintherace(first,second,orthird)andthetimeneededtocompletetheraceshouldbedisplayed.Thereisacheerfromthecrowdafterafinish.

FIGURE9.6Themarkerflags,whichhappentobeatthesamepositionasthewaypoints.

Page 272: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE9.7TheplayareaofthegameSMVRainbowshowingamini-map.

MINI-MAP

Amini-mapisamuchsmallerversionoftheplayingareaarrangedsothatitcanallbeseeninitsentirety,oratleastsothatmostoftheplayareacanbeseen.Thismeansthatthelocationsofyouropponentscanbeseenevenwhentheyarefar ahead or behind you.Other gameobjects can also be seenwith respect toyourcurrentposition.It’saverycommongamefeature.AnexampleisshowninFigure 9.7 from a game named SMVRainbow, butmany driving and combatgameshavethisfeature.

Tocreateamini-mapwestartwiththeoriginalterrainimageandreduceitinsize. In thisgame the size reduction is16x,meaning that themini-map is200pixels across.Aproblem is that there’s noplace toput it in thedrawing area.Anywherethismapgoesitwillpossiblyblocksomevaluablegamerealestate.Theansweristomakethedrawingarea200pixelswider,andtodrawthemini-mapinthelowerpartofthatarea.Nowthecreationofthedisplayis:

display=pygame.display.set_mode((700,400),pygame.SRCALPHA,32)

Themapitselfisacopyifthebackground(terrain)mapreducedinsize:

bk2=pygame.transform.scale(background,(200,169))

Thisimageisdrawnat location(500,220)duringeachiteration.Theboatsmustbedrawnon thismap too, for themap tobeuseful.Take thepositionofeachboatonthebigmapandsimplydivideby16,themapscale.Thendrawitrelative to the upper left of themini-map (500,220). The player, for example,wouldbe:

pygame.draw.circle(display,(255,0,0),

(int(500+player.x/16),int(220+player.y/16)),2,0)

TheplayerisdrawnasaredcircleandtheNPCboatsareblue.

GameDataThemini-maponlyusesthelowerportionoftheexpandedarea.Thisleaves

someemptyspacethatcanbeusedforotherthings.Whynotdisplaysomeofthegamedata here, such as the boat positions, speeds, and courses? It addsmoreinteresttothegame.Agametimerwouldbegoodtoo.Thisisaclockshowinghowfar into the raceweareat themoment.Allof those thingswillbedrawn

Page 273: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

intotheregiontotherightofx=500andabovethemini-map.Samplecodeis:

FIGURE9.8Thenewplayscreenshowingthemini-mapandplayingdata.

text(“Player“+str(int(player.x))+”“+str(int(player.y)),

520,100)

text(“Speed:“+str(int(player.speed*10))+“Course:“+

str(int(player.angle)),520,115)</CODE>

TUNING

Theconceptoftuningagameinvolvesadjustingtheparametersofalloftheobjects soas tomake thegamemore fun.Fun is impossible todefine,butweknowwhenwe’rehaving fun, so this should be possible.What are the tuningparameters of this game?Eachwaypoint has a speed parameter.These can bevaried to make the game more or less competitive. In fact, there could be adifferentsetofwaypointsforeasy,medium,anddifficultversionsofthegame.The location of thewaypoints can be changed also. All of thewaypoint dataresidesonafile,sotheseareeasytomodify.

The acceleration and turning speed can change too. These values areconstants in thecode,but theyareeasy tochange ifyouhave the source.Thelocationsofthecheckpointscanbemodified,andtherequiredpathcanbemademoreorlessconstrained.

EXERCISES

Page 274: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

1. Theplaytestersnotedthatthepassagesfromthestarttothelakeandattheendofthegameweretoonarrow.Describehowthiscouldbeimproved.

2. Thewakeanimationswillplayover topofotherboatsand theshore if thesituationisright.Howcouldthisbechanged?

3. The end of the game is unfinished. Add the necessary code to name thefinishersandtheirtimesandmakeuseoftheendscreen.

4. There isa filenamed flags.png thatcontains the imagesof the twosetsofwaypoint marker flags. In the current implementation these images aredrawnontotheterrainbackground.Modifythegametodisplaytheseflagsasanimations.

5. Whatwouldhappentothegameif,insteadoftheflagsbeingdrawnontotheterrain as the game is being played, they were a part of the backgroundimage?Isthatabetterwaytodothis?

6. UseaPythonprofiler todeterminewhichof thecode sections isusing themosttime.Isitpossibletoimprovethat?

RESOURCES

Steering: https://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-collision-avoidance--gamedev-7777.

Pygameanimation:http://usingpython.com/animation/.Pygame animation using Spritesheets:

https://codehackersblog.blogspot.com/2015/06/explosion-animation-using-spritesheets-in-pygame.html.

REFERENCES

1. alterspielend-programmieren.(2011).ThePythonGameBook:ScrollingandMinimap.https://www.youtube.com/watch?v=DusPphBj98A.

2. Bryce Boe. (2006). Line Segment Intersection Algorithm.http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/.

3. Tracy Fullerton, Chris Swain, and Steven Hoffman. (2004). Game DesignWorkshop:Designing,Prototyping,&PlaytestingGamesCMPBooks,SanFrancisco.

4. ZackHiwiller. (2015). PlayersMakingDecisions:GameDesignEssentialsandtheArtofUnderstandingYourPlayers.NewRiders.

5. Shawn Patton. (2017). The Definitive Guide to Playtest Questions.https://www.schellgames.com/blog/insights/the-definitive-guide-to-playtest-

Page 275: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

questions.6. Eric Meythaler. (2009). “2D Rotated Rectangle Collision.” Gamedev.net.

https://www.gamedev.net/articles/programming/general-and-gameplay-programming/2d-rotated-rectangle-collision-r2604.

7. CharlesP.Schultz. (2016).GameTestingAll inOne,3rd edition.MercuryLearning&Information.Dulles,Virginia

Page 276: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

CHAPTER10

NETWORKING

Anetworkedgameallowsmanyplayerstoparticipateatonetime,andtheseplayers need not be in the same room. Multiplayer games are distinct fromnetworkedgamesinthatabasicmultiplayergamepermitsmultiplepeople(uptoNplayers, usuallynomore than four) touse the samecomputeronwhich thegamesoftwareisexecuting.Anetworkedgameallowsmanymoreplayers,asageneral rule,and theycanbe inquitediverse locations.Communications takesplaceusingtheInternet.

The usual situation has a special computer somewhere, the game server,whichtakesloginsandmovesfromplayersusingInternetprotocols.Aprogramoneachplayer’scomputer,calledtheclient,sendstheuser’sactionstotheserveranddisplays the actionson theplayer’s computer. It also receives informationfromtheserverabouttheactionsoftheotherplayersandtheirlocations.

Thismeansthateachplayercan“see”theotherplayers,atleastinthesensethat all of the avatars are visible on each player’s screen.Reality dictates thattheremustbeasmall timedifferencebetweenwhataplayerseesandwhattheactualsituationisasdefinedbytheserver,butinanidealsituationthiswouldbesmall.Thetimedifferenceisoftenreferredtoaslatency.Ifthisgrowstoolarge,thenthegamebecomesunplayable,sinceeachclienthasaverydifferentideaofwheretheotherplayersare.

Consider a game where two players were involved, and one was in NewYorkandtheotherinChicago.ImaginethattheserverisinSeattle.Thegameisafirst-personshooter,andbothplayersareinthesameregionofthegame.Theservermediatesall interactionsby theplayers,but theclientoneachcomputercan seewhat the local player is doing andwill update the view very quickly,faster than the server can. Why? The local client can do graphics inmicroseconds, but the server is limited by the transmission speed between theclientandtheserver.

So, the clientside program of a network game renders the scene, playssounds,andhandles the input fromoneplayer. It also receivesupdates fromaserveronwherealloftheobjectsareinthegameandwhattheirstateis.Infact,

Page 277: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

itusuallyonlydoessoforasmallregionofthegame.Itgetsupdatedpositionsandorientationsofobjects from the Internet so theycanbe rendered,and it isinformed of new creations and deletions of objects. Finally, it sends playerposition and orientation data, new creations, and newdeletions from the localcomputertotheserversotheycanbesharedwithalloftheotherplayers.

In this chapter we’ll look at the networking facilities that are easilyaccessiblefromPythonandusethemtobuildasimplegame,acomputerversionoftennisthatresemblesthearcadegamePong,releasedbyAtariin1972.

THEGAME:PYTHONPONG

For the fewpeoplewho are not familiarwith the originalPong, the gameconsistsofarectangularplayarea,amovingball,andtwo“paddles.”Theballcanbounceoffofthetopandbottomoftheplayareaandalsooffofthepaddles.Thepaddlesaremovedupanddownbytheplayerssoastopreventtheballfrommovingpast themandexiting theplayarea fromeither end. If theballmovespast the left edgeof the screen, the right player scores apoint, and if theballexitstherightsidethentheleftplayergetsapoint.Ballsrestartfromthemiddleofthescreensomeplace.

FIGURE10.1Backgroundfortheparallelponggame.

Thebasicgamecanbeplayedbytwoplayers,eachusingadifferentpairofkeys: the left player uses “w” and “s” to move their paddle up and down

Page 278: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

respectively,andtherightplayerusestheupanddownarrows.Thisgamewillbe implemented first, and then it canbeconverted intoonewhereeachplayerhastheirowncomputer.

Thisisaverysimplegame,indeed,althoughithasalloftheingredientsofacomputergame.Therearethreeobjects:twopaddlesandaball.Theplayerusesonlytwokeysandcontrolsoneobject inonlyonedimension.Theplayareais640by480pixels.Itcanbecodedinabout225linesofPythonusingaballclassandapaddleclass.

ThePaddleClassApaddleisasimulationofaping-pongpaddle.Inthegameitisrepresented

byasimpleverticalline.Ithasthefollowingproperties:

xpos-Thehorizontalposition.Theleftpaddlehasxpos=100,andtherightpaddlehasxpos=540.

ypos-Theverticalposition.Canbeanywhereintheverticalspanoftheplayarea.Theyposvaluespecifiesthepositionofthecenterofthepaddle.

color -Thecolorwithwhichthepaddle isdrawn.In thedefaultgameit iswhite(255,255,255).

size-1/2thelengthofthelinetherepresentsthepaddle,inotherwordsthelengthofthelinefromthecentertoeitherend.

disp-Thedisplayonwhichthepaddlewillbedrawn.APygameSurface.sx-Thewidthofthedisplaysurface(640).sy-Theheightofthedisplaysurface(480).score-Thescorefortheplayerofthispaddle.

Theclasscantellifitisaleftorrightpaddlebythevalueofposx.

Theleftplayerusesthe“w”keytocausethepaddletomoveupward,andthe“s”keytomakeitmovedown.Thepaddlecontinuestomovewhilethekeyisheld down. So, as a code example consider the left paddle: the main loopdetermineswhetherthe“w”or“s”keyisdepressedandsetsaflagluporldown,dependingonwhetherthepaddleshouldbemovingupordown:

whileTrue:

foreventinpygame.event.get():

ifevent.type==pygame.QUIT:

exit()

ifevent.type==pygame.KEYDOWN:#Rightpaddle

Page 279: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

ifevent.key==pygame.K_UP:

rup=True

ifevent.key==pygame.K_DOWN:

rdown=True

ifevent.type==pygame.KEYUP:#Leftpaddle

ifevent.key==pygame.K_w:

lup=False

ifevent.key==pygame.K_s:

ldown=False

Then,ifthepaddleistobemoved,itisdonebyamethodnamedchangey()inthepaddleclass:

iflup:#Moveleftifneeded

pleft.changey(-1)

ifldown:

pleft.changey(1)

Theparameter indices thedirectionofmotion(-veisup,+veisdown)andthedegreeofmotion(numberofpixels).Thechangeymethoddoesnotdrawthepaddle.Thisisdoneinthemaingameloopbycallingthedrawmethodofeachpaddle.Asomewhatsimplifiedversionofdrawis:

defdraw(self):

pygame.draw.line(self.disp,self.color,(self.posx,self.posy),

(self.posx,self.posy-self.size),3)

pygame.draw.line(self.disp,self.color,(self.posx,self.posy),

(self.posx,self.posy+self.size),3)

font=pygame.font.Font(None,36)

text=font.render(str(self.score),1,(100,100,100))

ifself.posx<320:

self.disp.blit(text,(100,40))

else:

self.disp.blit(text,(550,40))

Thisversiondrawsthescoreaswell.

TheBallClassTheballisamorecomplicatedobjectthanthepaddle.Itmovescontinuously,

bouncesoffofotherobjects,and is responsible for thescore in thegame. It isrepresentedasasmallcircle.Whenitmovesofftheendoftheplayingareathereisasmallpause,andthentheballisdrawnsomewhereinthemiddleoftheplayareaandstartsmovingagain.

Theballobjecthasthefollowingproperties:

Page 280: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

xpos-Thehorizontalposition.ypos-Theverticalposition.color-Thecolorwithwhichtheballisdrawn.Inthedefaultgameitiswhite

(255,255,255).size-Sizeoftheboundingboxoftheball(5).disp-Thedisplayonwhichthepaddlewillbedrawn.APygameSurface.sx-Thewidthofthedisplaysurface(640).sy-Theheightofthedisplaysurface(480).speed-Speedwithwhichtheballmoves(pixelsperframe).dx-Changeinxpositioneachframe(initially1).dy-Changeinypositioneachframe(initially1).countdown-Thenumberofframesremainingbeforeanewballisdrawn.resetDelay-Numberofframesofpauseafterascoreismade.left-Theleftpaddle(anobjectreference).right-Therightpaddle(anobjectreference).

Theballisdrawnusingacalltothedrawmethod:

defdraw(self):#Drawtheballatthecurrentposition

pygame.draw.circle(self.disp,self.color,(int(self.posx),

int(self.posy)),self.size,0)

It is just a filled circle. Ball movement is more complicated. It changespositionby(dx,dy)eachiteration.Ifitbouncesoffoftheupperorloweredgeofthe display area, the value ofdy changes sign. If the ballmoves past the left(x=0)orright(x=640)endsoftheplayarea,apointisscoredandacountdownisstarteduntiltheballstartsmovingagainfromthecenteroftheplayarea.Finally,iftheballhitsapaddle,thevalueofdxchangessign.

Thiscodealsochangesthescorefortherelevantpaddle,anditintroducesasmall variation in movement after a paddle collision so that movement issomewhat less predictable. Collision with a paddle is tested by the methodcollision, which checks to see where the ball is relative to each paddle. Forexample,fortheleftpaddle:

ifself.posx<=self.left.posxand\

self.posy<self.left.posy+self.left.size\

andself.posy>self.left.posy-self.left.size:

ifself.posx<self.left.posx-2:

returnFalse

self.dx=-self.dx

returnTrue

Page 281: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

defmove(self):

#Movetheballonestep.Checkcollisions

ifself.countdown>0:#delaypostgoalself.countdown-=1return

ifself.countdown==0:self.posx=240self.posy=random.random()*100+200self.countdown=-1

self.posx=self.posx+self.dxself.posy=self.posy+self.dy

#Agoalifself.posx>self.sx:

self.left.score+=1self.countdown=self.resetDelay

ifself.posx<0:self.right.score+=1self.countdown=self.resetDelay

#bounceoffofthewallifself.posy>self.sy:self.posy=self.syself.dy=-self.dy

ifself.posy<0:self.posy=0self.dy=-self.dy

ifself.collision():#Paddlecollision?self.dx=self.dx+\

(random.random()-0.5)*0.2

Page 282: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

#Aslightchangeafterbouncing

self.dy=self.dy+(random.random()\

-0.5)*0.2d=math.sqrt(self.dx*self.dx+\

self.dy*self.dy)self.dx=(self.dx/d)*self.speedself.dy=(self.dy/d)*self.speed

Withouttheinnerifstatement,theballcould“bounce”ifitmovedbehindthepaddlewithout collidingwith it. This has unfortunate consequences as can beseenifthisstatementisremoved.

These two classes implement the game. When one paddle or the otherreachesacertainscorevalue,thegameisover.

Nowlet’sseehowcommunicationisdoneinPythonbetweencomputersonanetwork.

CommunicationBetweenProcessesCommunication between programs on a network is conducted very much

likeaconversation.Oneperson(program),theclient, initiatestheconversation(“Hithere!”).Theother(theserver)responds(“Hello.Nicetoseeyou.”).Nowitistheclient’sturnagain.Theytaketurnssendingandacceptingmessagesuntilonesays“goodbye.”Thesemessagesmightcontainemail,orFTPdata,orTVprograms.Thecommunicationssystemdoesnotcarewhatthedatais;noneofitsbusiness,really.Itsjobistodeliverit.

Data are delivered in packets, with each containing a certain amount. Inorderfortheclienttodeliverthedata,theremustbeaserverwillingtoconnecttoit.Theclientneedstoknowtheaddressofaserver,justasanFTPaddressoremail destination was required before, but now all that is needed is the hostnameandaportnumber.Aportisreallyalogicalconstruction,somethingakinto an element of a list. If two programs agree to share data by having one ofthemplaceit inlocation50001ofalistandtheotheronereaditfromthere,itgivesanapproximateideaofwhataportis.Someportnumbersareassignedandshouldnotbeusedforanythingelse;FTPandemailhaveassignedports.Othersareavailableforuse,andanytwoprocessescanagreetouseone.

Amodulenamed socket, basedon the interprocess communication scheme

Page 283: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

onUNIX of the same name, is usedwith Python to sendmessages back andforth.Tocreateanexample,twocomputersshouldbeused,onebeingtheclientandonetheserver.TheIPaddressoftheserverisrequired.

Example:MovingaBallontheScreen

Theclientwillopenacommunicationslink(socket)totheserver,whichhasaknownIPaddress.Theserverwillengageinashorthandshake(exchangeofstrings)andthenexpecttoreceiveanumberfortheclient.Theclientwillsendan integer, the serverwill receive it, square it, andsendback theanswer.Thissimpleexchangeisreallythebasisforallcommunicationsbetweencomputers:onemachinesendsinformation,theotherreceivesit,processesit,andreturnsareplybasedonthedataitreceived.

The client: will begin the conversation. It creates a connection, called asocket,totheserverusingthesocket()functionofthesocketmodule.Protocolsmustbespecified,andthemostcommononeswillbeused:

importsocket

HOST=‘19*.***.*.***’#Theremotehost

PORT=50007#Thesameportasusedbytheserver

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.connect((HOST,PORT))

Theclientmust identify thehost computer that is themachine running theserver.Anyonewhoplaysanonlinegamehasdownloaded theclient softwarethatmakesthatpossible,andthissoftwarehastheserverIPaddressbuiltintoit.TotestthisprogramweneedtwocomputersandweneedtoknowtheIPaddressoftheserver.Thiscanbefound,forthetest,byexecutingtheipconfigprogramonyourPC.Figure10.2showsapossibleresult.

Port50007isusedbecausenothingelseisusingit.Nowtheclientstartstheconversation, just as it appears at the beginning of this section, by sending amessage.Inthiscasethemessageisastring:

s.send(b’Hithere!’)

Thesend()functionsendsthemessagepassedasaparameter.Thestring(asbytes) is transmitted to the server through the variable s,which represents theserver.Theclientnowwaits for theconfirmationstringfromtheserver,whichshould be “Hello. Nice to see you.” To receive the message, the client calls

Page 284: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

anothersocketfunction:

data=s.recv(1024)

whichwaitsforaresponsefromtheserver.Thisresponsewillbe1024byteslongatmost,anditwillwaitonlyforashorttime,atwhichpointitwillgiveupandanerrorwillbereported.If thisclientgetstheresponse, itproceedstothenextstepinthecommunicationprocess.Inthiscaseitshouldbetoreceivethe(x,y)positionofanobjectonthescreen.

FIGURE10.2OutputfromipconfigshowingyourIPaddress.

Now let’s say thatwe have agreed that the received datawill be a pair ofintegers.Theclientcouldreadthestring,convertitintointegers,andusethemas screen (window) coordinates at which to draw a ball. Then the client willdraw the ball, read another pair, draw again, and so on. The nature of thecommunicationisagreedoninadvanceandmustbefollowedexactly.

Whentheexchangeofdataiscomplete,theclientclosestheconnection:

s.close()

TheServer: is always listening. It creates a socket on a particular port sothat the operating system knows something is possible there, but because theserver cannot predict when a client will connect or what client it will be, itsimplylistensforaconnection,bycallingafunctionnamedlisten():

importsocket

fromrandomimport*

Page 285: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

HOST=‘’#Anullstringiscorrecthere.

PORT=50007

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.bind((HOST,PORT))

s.listen()

AF_INET and SOCK_STREAM are constants that tell the system whichprotocolsarebeingused.Thesearethemostcommon,butseethedocumentationfor others. The bind() and the listen() functions are new to this discussion.Associatingthisconnectionwithaspecificportisdoneusingbind().Thetuple(HOST,PORT)saystoconnectthishosttothisport.TheemptystringforHOSTimplies this computer.The listen() call starts the server process, this program,accepting connectionswhen asked.A process connecting on the port thatwasspecified in bind() will now result in this process, the server, being notified.When a connection request occurs, the servermust accept it before doing anyinputoroutput:

conn,addr=s.accept()

In the tuple (conn,addr) that is returned, conn represents the connection,likeafiledescriptorreturnedfromopen(),andisusedtosendandreceivedata;addr is the address of the sender, the client, and is a string. If theaddrwereprinted:

print(“Connectedto“,addr)

ItwouldlooklikeanIPaddress:

Connectedto423.141.12.911Now the server can receive data across the connection, and does so by

callingrecv():

data=conn.recv(1024)

print(“Serverheard‘”,data,“’”)

Theparameter1024specifiesthesizeofthebuffer,orthemaximumnumberofbytesthatcanbereceivedinonecall.Thevariabledataisoftypebytes,justastheparametertosend()wasintheclient.Theclientwasthefirsttosend,anditsentthemessage“Hithere!”Thatshouldbethevalueofthedatanow,ifithasbeenreceivedproperly.Theresponsefromtheservershouldbe“Hello,nicetoseeyou.”:

conn.send(b’Hello.Nicetoseeyou.’)

Page 286: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

The sameconnection is used for sendingand receiving.Now the real datagets exchanged.The serverwill accept integers, sent asbytes. It candraw theballatthespecifiedposition:

whileTrue:

data=conn.recv(1024)#Readtheincomingdata

ifdata:

xpos,ypos=convertData(data)#Convertittointegers

print(“Received“,i)

drawBall(xpos,ypos)#Drawtheball

Theservercantellwhentheconnectionisclosedbytheclient,butitisalsopolitetosay“Goodbye”somehow,perhapsbysendingaparticularcode.Iftheloopeverterminates,theservershouldclosetheconnection:

conn.close()

This is a pretty good example of a data exchange and a contract, becausethere are specified requirements for each side of this conversationwhichwillresultinsuccessifdonecorrectlyandfailureifmessedup.Failureissometimesindicated by an errormessage, often a timeout where the client or serverwasexpecting something that never arrived. In other cases, failure is not formallyindicated at all; the program simply “hangs” there and does nothing. Forexample, if at any time both processes are trying to receive data, then theprogramwillfail.Thisisafailureintheimplementationoftheprotocol.

Figure10.3showsthecommunicationbetweentheclientandtheserverasadiagram. If theclientand the serverareatany timeboth trying toacceptdatafromtheconnection,thentheprogramwillfail.Inthediagramalldatatransferscanbeseenastransmit-acceptpairsbetweenthetwoprocesses,andasreadwritepairswithintheserverandwrite-readpairswithintheclient.

#Theclientimportsocket

#TheremotehostHOST=‘19*.***.*.***’#ThesameportusedbytheserverPORT=50007

s=socket.socket(socket.AF_INET,\socket.SOCK_STREAM)s.connect((HOST,PORT))

Page 287: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

s.send(b’Hithere!’)data=s.recv(1024)foriinrange(0,100):data=str(i).encode()s.send(data)data=s.recv(1024)

s.close()

#Theserverimportsocket

HOST=‘’#Anullstringisokhere.PORT=50007s=socket.socket(socket.AF_INET,\socket.SOCK_STREAM)s.bind((HOST,PORT))s.listen()conn,addr=s.accept()data=conn.recv(1024)print(“Serverheard”,data,“’”)conn.send(b’Hello.Nicetoseeyou.’)whileTrue:#Readtheincomingdatadata=conn.recv(1024)ifdata:

#Convertittointegeri=int(data)print(“Received“,i)

#Squareitandconverttobytesdata=str(i*i).encode()

#Sendtotheclientconn.send(data)

conn.close()

Page 288: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE10.2Typicalcommunicationbetweentheclientandtheserverprocesses.

NETWORKPONG

Thenetworkedclient-serverversionofthisgameisplayedontwocomputersby twoplayers,with a third computer as the intermediary for communication.Eachclientprogramgathersuserinterfaceinformationandsendsittotheserver.The server shares the result of this information with the clients, in that akeystrokeinoneclientresultsinamoveofthepaddlewhichissenttotheotherclientasachange in thepaddleposition.Theclienthasnouser interface, andsimplyactsasanintermediate.

TheClientThegameclienthasafewmajortasks:

1. Establishaconnectiontotheserver.2. Determinewhichpaddleitcontrolsusingcommunicationtotheserver.3. Waittobetoldthegamehasstarted.4. Playthegameasfollows:

Identify movement of the paddle by the player and transmit this to theserver.Determinewheretheballisanddisplayitatthecorrectplace.Telltheserverwhenapointisscored.

Page 289: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Getfromtheserverthepointsforeachsideanddisplaythem.Getfromtheserveranoticewhenthegameisover.

There is aproblem that shouldbekept inmind,but it canbeneglected inimplementationuntillater.Thatisthequestionofwheretheballreallyis.Eachofthethreeprocessesmayhaveaslightlydifferentviewofthatfact.Whatthismeansisthattheball’sbouncesmayoccuratdifferentmomentsinrealtimeoneachofthethreecomputers.We’llwaittoseeifthisbecomesaseriousissue.

We’veseenhowtoestablishaconnectiontotheserver.Theclientmayhavetowait,becausetheserverinthischapterwillallowonlytwoclientsatatime.Athirdclienttryingtoconnectwillhavetowaititsturntoplay.

Theclientwillreceiveamessageindicatingwhichplayeritis,leftorright.Thatisagainsomethingthatwe’veseenbefore.Itwaitsuntiltheclientsendsitamessage.Whentheservergetstwoplayerswhowishtoplay,asindicatedbyitsreceivingmessages from two different computers, then it sends a message tobothclientssayingthatthegamehasbegun.Itsendstheclientsthepositionoftheball.

The client accepts information from theplayer about paddlemotionof thepaddle it controls,which it translates into positions and sends to the server. Itasks theserverfor thepositionof theopponent’spaddleandtheball,andthenrenders thenewscene.Thepaddlesneednotmove,but theballdoes,and it isupdatedeachframe.Thus, theballpositionupdatescanbeusedasameans totime the screen updates: each time a ball update is received amounts to one“clocktick,”whichtriggersanewframetoberenderedbytheclient.

Thisisthecoreoftheclientcode,andasketchofanimplementationwouldconsistofaloop:

initialize()

whileTrue:voidkeyReleased()

getamessagemifmovepaddleupkey

ifmisapaddlepositionsendserveranewpaddleposition

movethepaddleifmovepaddledownkey

ifmisaballpositionsendserveranewpaddleposition

movetheball

rendertheframe

Fromthissketchitcanbeseenthattheclientdoesnotupdateitsownpaddledirectly,butwaits tohear from the server.Thedelayon thenetworkcouldbesuchthatthelocalpaddlepositionwasfaraheadofwheretheserverandotherclient had most recently recorded. This means that a player could see theirpaddle in one place while the server saw it in another, resulting in points or

Page 290: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

bounces being recorded that the player could not see. Itwould be frustrating.Anyonewhohasplayedanonlinegameunderstandstheproblemsthat lagcanbring.

Wecanalsoseethatamessagehasaspecificmeaningortype,andeachtypehas parameters. According to the sketch there are at least two types: paddleposition and ball position. There are more, of course. The format of eachmessagecanbespecifictothecontent.So:

Message IDCode Param1 Param2Paddleposition

(PPOS)01 Positionyxpositionis

fixedWhichpaddle(0or1)

Ballposition(BPOS)

02 Positionx Positiony

In the initialize section of code, there is amessage sent that identifies theclient’sdesignation,leftorright:

Designation000=left,1=right

(DESI)

Thiswillbethefirstmessagereceived.Themessagesconsistoffourintegers(128bits),theIDcodethatidentifiesthekindofmessage,andthreeparameters.Eachcodewillhaveonlyonebitsentatmost.Parametersare32-bitintegers.AmessagecanbesentbycallingafunctionnamedsendMessage(a,b,c,d).

TheServerTheserverhasthebulkofthecommunicationresponsibility.Itmustwaitfor

aconnectiontotwoclientstobeestablished.Ittellseachclientwhatpaddletheycontrol and then sits in themiddleof thegame,collectingdata fromeachandsendingittoboth.Whentheserverreceivesapaddlepositionfromoneclient,itmustsendtheresultingpositiontobothclients.Thatisbecausetheserveristheultimatearbiterofpaddleposition.Itdetermineswhattheballpositionisateachiterationandtransmitsthatpositiontoeachclient.Thatisbecausetheserveristheultimate arbiter of theball position.Becauseof this, the serverdetermineswhenagoal isscoredandwhenthegameisover. It is responsibleforsendingthesedatatotheclients.

Theserverwaitsfortwoclientstoconnectandthenassignseachofthemapaddle,sendingthemaDESImessage.Itthendelaysforafewsecondstogive

Page 291: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

theplayerstimetogetreadyandthensendsaBPOSmessage,placingtheballata randomstartingposition. It thenmoves theball as isdone in the standalonegame,sendingaBPOSmessageaftereachmovement.Aftereachballmovementthe server looks forPPOS messages from the clients and updates the paddlepositionsifanyareencountered,passingpaddlepositionstobothoftheclientsaswell.WhenaPPOSisreceivedfromtheleftclient,theserversendsittobothclients—theydonotupdatetheirpaddlesuntiltheyhearfromtheserver.

Whenascoreoccurs,amessageissenttobothclientstothateffectsothatthecorrect scorecanbedisplayedon their respective screens.The server thenwaitsforafewsecondsandstartsthegameagainwiththeballinarandomstartposition.When one client has scored 21 points, it haswon the game, and theserversendsamessagetothateffecttobothclients.

Wehavetwonewmessages:

Message IDCode Param1 Param2Goal

(GOAL)04 Leftscore Rightscore

Gameover(OVER)

08

After thegame isover, thecommunicationchannelsareclosed.Theservercanstartover,gettingtwonewclientsandbeginninganewgame.

BlockingandNon-BlockingThereareagreatmanyoptions,protocols,andpossibilitieswhenbuildinga

communication system using sockets.One important option iswhether to useblockingornon-blockingsendandreceiveoperations.

When reading from a socket using recv, the default is a blocking read,meaningthat thefunctionrecvdoesnot returnuntil ithasobtainedsomedata.Theprogramcandonothingelseuntil thedatahasbeenreceived.If thereturnvalue is0, itmeans that theprocessat theotherendhasclosedandwillneveragainsendanydata.Asendoperationwillnotreturnuntilthedatahasbeensent;sendingdatameanswriting it into a buffer in the receiver, and if space is notavailable,thenthesenderwaitsuntilitis.Blockingcanbeaproblemifitisnotknownwhichofmultipleprocesseswillsendamessage.Inthecurrentexamplethat’strueofpaddlepositions.Eitherclientcansendapaddlepositionupdateatany time. These updatesmust be dealt with as soon as possible, and using a

Page 292: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

blocking read on the left paddle will delay until a message is set by the leftclient;meanwhile,therightclientcouldhavesentmanyPPOSmessages.

AsolutionwouldbetoensurethateachclientsendsonePPOSmessageeachiteration,andthenawaitsaBPOSmessagefromtheserver.Thisconstrainsthereactionof thepaddlemovementandsendsmanymoremessages thanneeded.Anotherwouldbetocollectpaddlemovementssothattheycouldallbesentinasinglemessageaftereachballmovementwasreceived.Bothsolutionsmeanthatthesequenceofsend-receiveispredictable,andsotheblockingwouldnotcausetoomuchtrouble.

Anon-blocking receivealways returns right away,whetherornot anydatawassent.Ifdataexiststhecallworksasithasbefore.Ifthereisnodata,thenthecallwillthrowasocket.errorexceptionwiththeerrornumber(errno)ofeitherEAGAIN orEWOULDBLOCK. Reading from a socket is now a littlemorecomplex:

defreadf(s):

msg=“error“

try:

msg=s.recv(8)

exceptsocket.erroraserr:

iferr==socket.errno.EAGAINorerr==socket.errno.

EWOULDBLOCK:#Nodata

return“”

else:

print(err)

returnmsg#anerroroccurred

else:

returnmsg#Datawasreceived

Inthepreviouscode,ifnodataisreceivedthentheprogramcouldwaitforsometimeandtryagain.

Causingthesockettobenon-blockingisaccomplishedbyacall:

mysocket.setblocking(0)

Dealing with non-blocking channels can be a problem, because manyconditions have to be tested for any attempted communication. All recv callsneed to be embeddedwithin tests for errors and content, as previously. Theremayalsobemanyclientsthatareincommunicationatthesametimeaswell.Amodule named select has been constructed which enables non-blockingcommunicationtobedealtwithveryeffectively.

Themethodselecttakethreelistsasargumentsandreturnsasubsetofeachofthosethreelistsasavalue.Inthecall:

Page 293: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

select(a,b,c)

aisalistofobjectstobecheckedforincomingdata,bisalistofobjectstowhichdatawillbesent,andforwhichbufferspacewillbeneeded,andcisalistofobjectsthatmayhaveresultedinanerror.Mostoften,cconsistsofalloftheobjectsinaandb.Thecallreturnsthreelists,so:

x,y,z=select(a,b,c)

returnsxasalistofobjectsthatarereadable,inthattheyhaveincomingdatathatcanbeaccessedusingarecvcall;y is a listofobjects thathave space intheirbufferandcanbewrittento;andzisalistofobjectsthathaveindicatedanerror.Thegame serverwouldhavewithin it, using this scheme, the followingcode:

inputs=[ls,rs]

outputs=[ls,rs]

queues={}

whileTrue:

readable,writable,exceptional=select.select(inputs,outputs,inputs)

forsinreadable:

print(“Reading”)

m1=readf(s)

ifm1!=“”:

print(“[.............“,m1)

#nowupdateandsendballposition

...

Thegamecan’tdoverymuchexceptwaitforaresponsefromaclientifoneisnot immediatelyavailable, so there isno realpenalty forusing theblockingsend and receive. At this point we have a strategy for organizing thecommunicationportionof thenetworkgame.Wearealmost ready tocode thegame.

MessagesWehavedefinedfivedistinctmessagesthatthegamerequires:PPOS,BPOS,

DESI,GOAL,andOVER.Theconnectionstransmitcharactersoverthesockets,soeachmessagewillbeacharacterstring.Therewillbeatmosttwoparameters,andeachof thesewill be atmost threedigits, because theyareusually screencoordinates.Thus,eightcharactersisenoughforamessage.

Sendingamessagemeanstakingthemessagetypecodeandtwoparametersandconvertingthatintoastringthatcanbesent.Theeasiestmessagetoformatisgameover,whichhasnoparameters.Itwillalwaysbe“08000000.”

Page 294: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

DESI has only one parameter, and that’s either 0 or 1. A left DESI is“00000000”andarightDESIis“01000000.”

PPOS has only one parameter as well, but there are two paddles. It issensibletosendboththeleftandrightpaddlepositionsinasinglemessage.TheimplementationofPPOSwillhave thefirstparameter represent the leftpaddlepositionandthesecondparameterbetheright.

Let’sassumethatifaparameterisnotneeded,itwillbesetto0.Thenany8-bytemessagecanbeformattedusing:

‘{:02d}{:03d}{:03d}’.format(code,p1,p2)

So,forsomeexamples:

DESIleftis00000000

DESIrightis01000000

OVERis08000000

PPOS121,255is01121255Leftpaddle=121,right=255

BPOS671,330is02671330

Decoding the messages is pretty simple too. Any string has a 2-charactercodeandtwo3-characterintegers.So,astringscanbedecodedas:

code=int(s[0:2])

p1=int(s[2:5])

p2=int(s[5:8])

Nowwecanbegintoseparatetheclientandserverpartsofthegamecode.

ThePongClientTheclientcodeismostsimilartothestandalonegamecodeinthatitaccepts

commandsfromthekeyboardanddisplays theplayingareaonthescreen.Theclientbeginsbyestablishingaconnectionwiththeserver.

Theimplementationoftheclientusesacommunicationsclasstodoalotofthe data transmission to and from the server. It holds themessage codes, theserveraddress, and importantlyhasamethodcalled initClient that establishesthelinktotheserver.Thefirstthingtheclientdoesiscreateaninstanceofthecommunications class that tries to connect. This class also contains thefollowing:

defreadf(self):Readamessagefromtheserver

defmakeMessage(code,p1,p2):Constructamessagestring

defgetMessage(s):Decodeamessage

defreadMessage(self):Readanddecodeamessage

Page 295: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

defsendPPos(self,yl,yr):Sendpaddlepositions

After theconnection ismade, theclient receivesaDESImessage fromtheserver telling it which side (left or right) the client is playing. Only the keypressesappropriate to theclientwillbeprocessed. If theclient is the left side,then the arrow keys will have no effect. The functions IAMLEFT() andIAMRIGHT() can be used by the client to determinewhat side it is playing.Thetwosidesalsodifferinthefollowingways:

- Thepaddlebeingplayedbyeachclientwillbedrawningreen.- Thepaddlepositionforthepaddlebeingplayedissenttotheserver.

Thegame loop for the client is the sameup to thepointwhere thepaddlemotionhastobeimplemented.Thenwehavethefollowingcode:

First,sendthecurrentpaddlepositiontotheserver.

ifIAMLEFT():

coms.sendPPos(pleft.posy,0)

else:

coms.sendPPos(pright.posy,1)

Nowget the positionof the ball from the server andplace the ball in thatposition.

#---------------Getballposition-------------------

m1=coms.readMessage()#m1isastring

xlst=coms.getMessage(m1)#xlstisatuple

ball.move(xlst[1],xlst[2])

Read the paddle positions that the server has. These are really the currentpositions,becausetheserverdeterminescollisions.

#------------Getotherpaddleposition--------------

m1=coms.readMessage()#m1isastring

xlst=coms.getMessage(m1)#xlstisatuple

pright.posy=xlst[2]

pleft.posy=xlst[1]

Nowreadthescorefromtheserver.Thisisusedtodisplayonthescreen,andtodeterminewhenthegameisover.

#------------Getthescore--------------------------

m1=coms.readMessage()#m1isastring

xlst=coms.getMessage(m1)#xlstisatuple

pright.score=xlst[2]

Page 296: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

pleft.score=xlst[1]

Therestisnearlyasbefore.Drawthebackground,theball,andthepaddles.Inthisversionthemaximumscoreis3,whichmakesdebuggingeasier.

display.blit(background,(0,0))#Displaythebackground

ifpright.score>3:

gameover=True

ifpleft.score>3:

gameover=True

pleft.draw()#Drawtheleftpaddle

pright.draw()#Drawtherightpaddle

ball.draw()#Drawtheball

pygame.display.update()#Refreshthescreen

And that’s thegame.The client doesnot determinepaddle collisions,wallbounces, or scores. The server does this because it is always the owner of allcurrentpositions.Thismeansthattheservermaybeakeypressorsobehindaclientduetolatency,butitstillistheauthorityconcerningthegamestate.Thecodefortheclientisonthebook'sdisc.

ThePongServerTheserverdoesnotdisplaythegame.Itrunsonacomputer,perhapsinthe

backgroundwithotherprocesses,andsimplyarbitratesthetwoclients.Ithastheactualball class andpaddle class, determines bounces and scores, and sendsmessagesbackandforth.Ithasnouserinterface.Paddlepositionsaresentfromeachclientandaresentbacktotheclientsaftertheserverprocessesthem.

Thismeans that the entire section of the game loop that handles the userinteractionisnotneeded.Thegameloopis,infact,verybrief:

whileTrue:

clock.tick(50)

foreventinpygame.event.get():#OnlyeventshouldbeQUIT.

ifevent.type==pygame.QUIT:

exit()

#------------------GetPaddlepositions------------------------------------

m1=readMessage(rs)#ReadpaddlemessagesentbyRIGHTclient.

pright.changey(m1[1])#Alsochangethepositionofthepaddle

m1=readMessage(ls)#ReadpaddlemessagesentbyLeftclient.

pleft.changey(m1[1])#Alsochangethepositionofthepaddle

Page 297: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

#---------------------------Moveball,sendposition---------------------------------

ball.move()#Movetheball

sendBPos(ls,int(ball.posx),int(ball.posy))

sendBPos(rs,int(ball.posx),int(ball.posy))

#-----------------------------Sendpaddlepostoclients-----------------------------

ls.send(bytes(makeMessage(PPOS,pleft.posy,pright.posy),‘utf-8’))

rs.send(bytes(makeMessage(PPOS,pleft.posy,pright.posy),‘utf-8’))

#-----------------------------Sendscoretobothclients-----------------------------

sendScore(ls,pleft.score,pright.score)

sendScore(rs,pleft.score,pright.score)

Themessagespassedbetweentheserverandtheclienthavebesynchronizedoroneoftheblockingreadswillsimplyhang,waitingfordata.Thegameloopfor the servermust have a sendwhenever the game loop for the client has areceive,andviceversa.Inthiscasetheprotocolis:

ServerClient

GetthepaddlepositionsSendpaddleposition

m1=readMessage(rs)coms.sendPPos(pleft.posy,0)

m1=readMessage(ls)

SendtheballpositionGetballposition

sendBPos(ls,int(ball.posx),int(ball.posy))m1=coms.readMessage()

sendBPos(rs,int(ball.posx),int(ball.posy))

SendthepaddlepositionsGetpaddlepositions

m1=coms.readMessage()

ls.send(bytes(makeMessage(PPOS,pleft.posy,pright.posy),‘utf-8’))

rs.send(bytes(makeMessage(PPOS,pleft.posy,pright.posy),‘utf-8’))

SendthescoreGetthescore

sendScore(ls,pleft.score,pright.score)m1=coms.readMessage()

sendScore(rs,pleft.score,pright.score)

PlayingtheGameThreecomputersareusedtoplaythisgame.Firstruntheserverprogramon

thecomputerhavingtheserver’sIPaddress,asusedbytheclients.Thenrunaclientoneachoftheothertwocomputers.Onewillbeassignedtheleftpaddle,theothertheright.Notethattheballhasthesamepositiononeachgamescreen,andwhen the left playermoves their paddle, themovement shows up on therightplayer’sscreen.

Page 298: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

FIGURE10.4Livescreenfromtheponggame.

RESOURCES

PythonSocket–NetworkProgrammingTutorialhttps://www.binarytides.com/python-socket-programming-tutorial/Getting Started with Processing for Android

http://createdigitalmotion.com/2010/09/getting-started-with-processing-for-android/

Socket-Low-LevelNetworkingInterfacehttps://docs.python.org/3.6/library/socket.htmlPython-NetworkProgramminghttps://www.tutorialspoint.com/python/python_networking.htmhttp://realmike.org/blog/2010/12/11/sound-playback-in-processing-for-

android/

REFERENCES

1. Todd Barron and LostLogic. (2002).Multiplayer Game Programming, 1stedition.CourseTechnologyPTR.

2. A.Freier,P.Karlton,andP.Kocher.(2011).TheSecureSocketsLayer(SSL)Protocol Version 3.0. Internet Engineering Task Force (IETF).https://tools.ietf.org/html/rfc6101?ref=driverlayer.com.

Page 299: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

3. Warren Gay. (2000). Linux Socket Programming by Example, 1st edition.QuePublishing.

4. JoshGlazer andSanjayMadhav. (2015).MultiplayerGameProgramming:ArchitectingNetworkedGames,1stedition.Addison-WesleyProfessional.

5. John Goerzen and Tim Bower. (2010). Foundations of Python NetworkProgramming:TheComprehensiveGuidetoBuildingNetworkApplicationswithPython,2ndedition.Apress.

6. AlbertoLeon-Garcia and IndraWidjaja. (2003).CommunicationNetworks,2ndedition.McGraw-HillEducation.Boston.

7. AndrewS.TanenbaumandDavidJ.Wetherall.(2010).ComputerNetworks,5thedition[IndianInternationaledition].PrenticeHall.

Page 300: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

AppendixA

A*INlPYTHONclassnode:

def__init__(self,a,b):

self.i=a

self.j=b

self.parent=None

self.bestf=100000

self.unusable=False

self.g=100000

self.seen=False

self.mark=False;

defMark(self):

self.mark=True

defunMark(self):

self.mark=False

defupdateF(self,f,p):

iff<self.bestf:

self.bestf=f

self.parent=p

defsetUnusable(self):

self.unusable=True

definitialize():

globalz

foriinrange(0,10):

forjinrange(0,10):

z[i][j]=node(i,j);

“””Firstmaze

z[2][1].setUnusable()#Setupthegrid

z[3][1].setUnusable()

z[4][1].setUnusable()

z[5][1].setUnusable()

z[5][2].setUnusable()

z[6][2].setUnusable()

z[6][3].setUnusable()

Page 301: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

z[7][3].setUnusable()

z[7][4].setUnusable()

z[8][4].setUnusable()

z[8][5].setUnusable()

z[8][6].setUnusable()

z[1][6].setUnusable()

z[2][6].setUnusable()

z[3][6].setUnusable()

z[3][7].setUnusable()

z[3][8].setUnusable()

“””

foriinrange(0,9):

z[2][i].setUnusable()

foriinrange(1,10):

z[5][i].setUnusable();

printGrid()

defprintGrid():#Printthescene

foriinrange(10):

forjinrange(10):

ifi==1andj==5:

print(“S”,end=””)

elifi==7andj==5:

print(“E”,end=””)

elifz[i][j].mark:

print(“^”,end=””)

elifz[i][j].parent!=None:

print(“.”,end=””)

elifz[i][j].unusable:

print(“#”,end=””)

else:

print(“.”,end=””)

print()

defh(p):

return(abs(p.i-goalx)+abs(p.j-goaly))*10

defg(p):

returnp.g

deff(p):

returnh(p)+g(p)

definList(p,l):

forllinl:

ifll.i==p.iandll.j==p.j:

returnll

returnNone

Page 302: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

defsmallestOpenList():

q=openList[0]

forpinopenList:

ifp.bestf<q.bestf:

q=p

returnq

defneighbors(p):

nlist=[]#Createalistofneighborsofp

foriinrange(-1,2):

forjinrange(-1,2):

ifi==0andj==0:

continue

ii=p.i+i

if(ii<0orii>=10):#Rangecheck

continue

jj=p.j+j

if(jj<0orjj>=10):

continue

nlist=nlist+[z[ii][jj]]

returnnlist

defunMarkAll():

foriinrange(0,10):

forjinrange(0,10):

z[i][j].unMark()

defprintCost():

foriinrange(0,10):

forjinrange(0,10):

ifz[i][j].g>300:

print(“xxx“,end=””)

else:

print(z[i][j].g,”“,end=””)

print()

z=[[Noneforjinrange(10)]foriinrange(10)]

initialize()

startNode=z[1][5]#Wheretobeginthepath

goalNode=z[7][5]#Theplacewearetryingtoreach

openList=[]#Openlist;alistofpoints

closedList=[]#Closedlist;alistofpoints

goalx=7

goaly=5

startNode.g=0

print(“Startingfis“,startNode.bestf)

openList.append(startNode)

Page 303: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

print(openList[0].bestf)

while(len(openList)>0):#Whileopenlistnotempty

p=smallestOpenList()#Selectanodefromtheopenlist

if(p==goalNode):#Wehavereachedthegoal.

print(“Done.”)

printGrid()

break

closedList.append(p)#Addtoclosedlist

openList.remove(p)#removefromopen

nlist=neighbors(p)#Findallneighbors

forcinnlist:#Examineeachneighbor,named‘c’

ifc.unusable:#Ifunusableor

continue

ifinList(c,closedList)!=None:#ifitisintheclosedlist,

continue#ignoreit

ifp.i==c.iorp.j==c.j:#Distancectop

d=10

else:

d=14

cost=p.g+d#Newcostofcisoldcost+d

ifinList(c,openList)==None:#cnotintheopen

list

openList.append(c)

ifcost>=f(c):

continue

c.g=cost

c.parent=p#Settheparent

c.bestf=f(c)

printCost()

print(“-----------------------------------------------------------”

unMarkAll()

p=z[goalx][goaly]

while(p!=startNode):

print(“<“,p.i,”,”,p.j)

p.Mark()

p=p.parent

printGrid()

printCost()

Page 304: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

APPENDIXB

C2H6OJETBOATRACEGAMEDESIGNDOCUMENT1. GameOverview1.1.Concept–Thisgamewill involve theplayerguidinga jetboat througha

coursedownariverandaroundalakeandoverafinishline,whileescapingtraps,avoidingobstacles.

1.2.Genre–Thisisabasicracestylegame,2Dwithoverheadview.1.3.Audience–Anyage,butwithayoungerdemographic.1.4.GameFlow–Aftermovingthroughtheinitialscreens,theplayerissignaled

to begin the race.The gamebegins at a small dockwith three boats, andinitiallyallmovedowntheriverandjockeyforposition.Alakeisenteredthat has floating pylons to guide the player, each having a number and acolor. The number indicates the next pylon to pass in sequence, and thecolorindicateswhichboatmustpassneartothepylon.Thefirstboattopassthefinalpylonwinstherace.

1.5.VisualStyle–Theviewoftheplayingareaisfromabove,anditscrollstofollowtheplayer.Itisatypical2Dracegameinthataspect.Boatsare21stcenturyjetboats.

2. GameplayandMechanics2.1.Gameplay2.1.1.GameProgression–Thereisonelevel,andonegoal.2.1.2.Mission/challengeStructure–nospecificmissions.2.1.3.Objectives–Theoverallobjectiveistocrossthefinishlinebeforeanyof

theother(NPC)boats.Othergoalsinclude:-Topassnearflagsalongtheroute-Tofueluptoavoidrunningoutoffuel(canceled)-Tointerfere,ifpossible,withtheotherboats2.1.4.PlayFlow–Thegameis focusedon thehumanplayer.Otherboatswill

Page 305: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

attempt to avoid the player. The playermustmove through the obstacles,passthemarkerscorrectly,andpassoverthefinishline.

2.2.Mechanics–Theplayercancontroltheirboat,makingitaccelerateorturnleftorright.Hittinglandslowstheboat,whichtheplayermustguidebackintothewater.Theracebeginsonariver,entersalakewhereonelapofacircuitmustbemade,

andendsonanotherriverwherethefinishlineis.Small flagsarefloatingnear theboat’spath,and thesemustbeencountered in

thecorrectordersothattheplayermaywin.Missingaflagmeanshavingtogoback.

Aclockkeeps trackof the time that theboathasspenton the raceso far.Theboatwiththesmallesttimeatthefinishwins,irrespectiveoftheirphysicalplaceintherace.

2.2.1.Physics –Thegame takes place on the surface of thewater,which is ahigh friction surface. Acceleration can be quick, but slacking off on theacceleratorwillslowtheboatquickly.Theboatcannotturntooquickly,somovingtoofastwhenaturnisneededslowstheplayer’sprogress.

2.2.2.Movement in thegame–The“q”keyaccelerates theboat forward,andreleasingitwillslowtheboat.Turnsareperformedusingthe“a”key(left)andthe“d”key(right).

2.2.3.Economy–Thereisnoin-gameeconomy.

2.2.4. ScreenFlow–A graphical description of how each screen is related toeveryotherandadescriptionofthepurposeofeachscreen.

Therewillbeanopeningscreen(loadgameassets)Startscreen(play,exit,options,sound)Optionsscreen–selectboats,soundon/offPlayscreenEnd–win/lose,savescore,replay/exit

2.3.GameOptions–Theplayercanselectaboatthathasspecificpropertiesoftopspeed,acceleration,andmaneuverabilityfromasmalllist.

2.4.ReplayingandSaving–Gamecan’tbesavedbutcanbereplayedandalistofplayersandscorescanbemaintained.

Page 306: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

3. Story,Setting,andCharacter3.1. Story andNarrative – There is no narrative here, just a race.Cut scenes

beforeandafter the raceare realboat racing scenes fromactual jet boatraces.

3.2.GameWorld3.2.1. General look and feel of world – A 2D plane showing water and land

areas, flags, boats, refueling area, and obstacles. The terrain backgroundimageisxx.png.

3.2.2.Thestartarea isadockalongariver.Whenthegamebegins, theplayerandNPCsacceleratetotheleftalongtheriver.

3.2.3. The river opens into a lake that has colored flags and islands to avoid.BluepylonsareneededbytheplayerandoneoftheNPCboats,theredonesbytheotherNPC.

Page 307: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

3.2.4.Thereisanotherriverenteringthelakewhichcontainsthefinishline,anditistobeusedaftercircuitsofthelakehavebeenperformed.

3.3. Characters. NPC boats have various colors and shapes.Boat3 (NPC3) isboat2a.gifasafile.

Boat4(NPC4)isboat5a.gif.Eachis88x27pixelswithatransparentbackground.

4. Levels–

4.1.Levels.Onlytheone.4.2.TutorialLevel–Later

5. Interface5.1.WindowsandTransitions

WhenthegamebeginstheSTARTscreenisdisplayed.(startScreen.jpg)

Therearethreebuttonsonthisscreen:Play,Quit,andOptions.When the Options button is pressed, the Options screen is displayed

Page 308: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

(optionsScreen.jpg):TheOptionsscreenhasabutton that turns thesoundonoroff,andaback

buttonthatreturnstheplayertotheStartscreen.When theQuitbutton ispressed thequit screen isdisplayed,which shows

thecredits.Anymouseclickwillterminatethegameprogram.

When thePlaybutton ispressed thePlayscreen isdisplayed.This is themain

Page 309: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

playareaandiswherealloftheremaininggameaspectsoccur.Thegamescreenis700by400pixels.500x400showthegameplay,and200x400showamini-mapandothergamedataontherightsideofthescreen.

5.2.VisualAssist.HUD.Cameraisabovetheplayer’sboat.

HUD(mini-map) is in the lower right corner and showsawider areawithother boats and scene features. Above that is a text area showing the currentposition,speed,andcourseofeachboat.

5.3.ControlSystem–KeyboardThe“q”keymovestheplayer’sboatforward.The“a”keyturnsitleft,and

the“d”key turns it right.Thedescribedactionscontinueas longas thekey isdepressed.

5.4.AudioMusicNomusicStartinggun–gun.wavEndindicator–Peoplecheering.finish.wavFlagindicator–a“bing”noisesoundswhentheplayerreachesanewflag.

(bing.wav)Engine noise – Plays while the player has depressed a motion key

(engine1.wav)

Page 310: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Ambiance–crowdnoiseplaysoncethegamestarts(audience.wav)

5.5.HelpSystem–asinglehelpscreencanbeopenedatanytimebytypingthe“h”key.Contentslater.

6. ArtificialIntelligence6.1.PlayerandCollisionDetection

Aboatcancollidewithanotherboatorwiththeshore.

BOAT-BOATCOLLISION

Whentwoboatscollidetheyexplodeandstartoverfromthebeginning.Anexplosionanimationplaysandanexplosionsoundisstarted.

Collisions are based on object-oriented box intersections. These boxes aresomewhatsmallerthantheboundingbox(sizetobedeterminedbyplaytest).

Therearefivedifferentexplosionanimations,selectedasasequenceduringplay. They are represented as sprite sheets (explode1.gif, explode4.gif,explode5.png).

Page 311: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Thesehave16 individual frames that are32x32pixels.The soundof theexplosionisexp1.wavorexp2.wav,andisselectedatrandom.

BOAT-SHORECOLLISION

A collision with the shore is detected by using the corner points of a boat’sboundingbox.Ifanyofthesefallonaterrainpixelthatisnotthesamecoloraswater(33,174,173),thenacollisionisindicated.

6.2.Pathfinding

TheNPCboatseachhaveasetofwaypointstofollow.NPC3(boat3)followstheoddwaypoints,andNPC4followstheeven-numberedones.Thesearefoundonthefileparamets.txt,whereeachlineoftextcontains:

1.Thewaypointnumber2.WaypointXcoordinate3.WaypointYcoordinate4.Targetspeedoftheboatatthatwaypoint

Example:13402391.423252385.633691849.643771713.7

...Whentheboatreachesawaypoint(withinadistanceof100),itselectsthenextwaypointandslowlyadjustsitsspeedtothenextsuggestedspeedandthecourseto intersectwith thenextwaypoint.The finalwaypoints (29and30) representthefinishofthegame.6.3.OpponentAI

NPC boats will attempt to avoid the other boats, especially the player’sboat.NPC boats are guided by waypoints, but sometimes when attempting toevadetheplayer’sboattheywillrunaground.WhentheshoreisintersectedbyanNPCboat,itattemptstoreversecoursefor30iterations,andthenattemptstorotate counterclockwise for another 40 iterations. It then resumes its course tothenextwaypoint.

Page 312: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

AVOIDINGTHEPLAYER

TheNPCboatsprojectarayinfrontofthemfor200pixels.Ifthatrayintersectswith another boat (using theboundingbox), then a collision is imminent.TheboatenterstheAVOIDstateandturnsawayfromthecollision.Thisisdoneinaset of 100 steps. It then leaves the AVOID state and resumes a course to itswaypoint.

6.4.FriendlyAINone

7. Technical7.1.TargetHardware–Anydesktop

7.2.Developmenthardwareandsoftware,includingGameEngine–PythonandPygame

7.3.Networkrequirements–Later

8. Game Art – Key assets, how they are being developed. Intended style.Gamehasbeenseenexceptfor:

Pylons(flags)

Animations

1. Boatwake.Tobedrawnbehindanyboatthatisunderpower(engineonandboatismoving).Canbedrawninarandomorder.Imagesare34x83pixelsandincludeawaterbackground.wakes.gif

Allwakeframes.

Page 313: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

2. Explosion. When boats collide.http://www.positech.co.uk/content/explosion/explosiongenerator.html tocreatetheframes.

See6.1forspritesheets.

9. Gameprogression

Start–WhentheplayerpressestheSTARTbuttononthestartscreen,theplayscreen is displayedwith nomini-map. Text will count down from 10 to 1 toallowtheplayertoprepareforthestart.Attheendofthecountdownsequence(1secondperstep),thefullgamescreenisdisplayedandtheboatscannowmove.

The NPC boats follow their waypoints until a collision or the end. After acollisiontheyresumefollowingwaypoints.

Theplayermaynavigateastheychoose,butcollisionswillbedetectedanddealtwith.

-Collidingwithanotherboatresultsinanexplosionandarestart.-Collidingwiththeshorestopstheboat.Theplayercanturnuntiltheboatis

free.

Whenevertheplayerreachesawaypoint,a“bing”soundisplayed.

Page 314: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Whenever the player holds down the “q” key, the engine sound plays and theboatacceleratestoitsmaximumspeed.Wheneverthe“a”or“d”keyisdepressed,theenginesoundplaysandtheboatturns.

Page 315: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

APPENDIXC

THENPC(BOAT)CLASSFORTHEEXAMPLEGAME#Aboat....................................................

classnpc:#Allclass,localvariables

def__init__(self,x,y,sprite,speed,angle,index):

self.x=x#CurrentXposition

self.y=y#CurrentYposition

self.speed=speed#Currentspeed

self.angle=angle#Currentcourse

self.index=index#Indexinboatstuple

self.sound=False#Enginesoundplaying?

self.volume=0#Soundvolume

self.targetSpeed=0#Howfastdoestheboatwanttogo?

self.targetAngle=90#Whatisthecoursesetting?

self.sprite=sprite#Theimageoftheboat

self.wpt=None#Nextwaypoint

self.name=“NPC1”#Nameofthisboat

self.NORMAL=0#NORMALstate.

self.AVOID=1#Statewheretheboatisavoidinganother

self.COLLIDED=2#Statewhereboathascollidedwiththeshore

self.EXPLODING=4#Statewheretheboatisexploding

self.state=self.NORMAL#Currentstate

self.ccount=0#CurrentstepinAVOID(0..100)

self.estate=0#CurrentstepinCOLLIDED

self.delta=0#AnglestepintheAVOIDprocess

self.frame=0#Currentexplosionframe

self.r=None#Tempsurfaceforrotatingtheboatimage

self.player=False#IsTHISboattheplayer’s?

self.ul=[1,1]#Upperleftcornerofboundingbox

self.ur=[1,1]#Upperrightcornerofboundingbox

self.lr=[1,1]#Lowerrightcornerofboundingbox

self.ll=[1,1]#Lowerleftcornerofboundingbox

self.sternx=0#Xcoordinateofthestern

self.sterny=0#Ycoordinateofthestern

self.prowx=0#Xcoordinateoftheprow

self.prowy=0#Ycoordinateoftheprow

self.centrex=0#Xcoordinateoftheboatcenter

self.centery=0#Ycoordinateoftheboatcenter

Page 316: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

self.done=False#Hasthisboatfinishedtherace?

self.kimage=int(random.random()*5)#Whichexplosionimagetouse

self.savedx=x#Lastxlocationoftheboat(forexplosion)

self.savedy=y#Lastxlocationoftheboat(forexplosion)

#Allmethods

defdisplay(self):#Displaythisboatoritsexplosionanimation

defshowNextExFrame(self,x,y):#Displaythenextexplosionanimationframe

defreset(self):#Restartthisboatatitsoriginalposition

#Courseandspeedwillchangegraduallytothetarget

defsetSpeed(self,s):#Setthetargetspeed

defsetCourse(self,a):#Setthetargetcourse

defsetWaypoint(self,w):#Setthecurrenttargetwaypoint

defsetName(self,s):#Setthetext5nameofthisboat

defadjustAngle(self):#Adjusttheboatcourseasteptotarget

defadjustSpeed(self):#Adjustspeedasteptotarget

defescape(self):#Doonesteptoescapefromashorecollision

defnormalize(self,vec):#Normalizeavector(makeislength1)

#CouldaboatcollisionbetweenIandjoccur?

defboatCollision(self,i,ddx,ddy):

defavoid(self,i,ddx,ddy):#Performastepinavoidinganotherboat

defplayerStep(self):#Movetheplayer’sboatonestep,alltests

defnextStep(self):#MoveanNPCboatastep,alltests

Page 317: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

INDEXAAABB.SeeAxisAlignedBoundingBoxAccuracy,18–19Actiongames,8ADC.SeeAnalogtodigitalconverterAdvent,8Adventuregames,8AgeofEmpires,6AI.SeeArtificialintelligenceAmbientanimations,225–228Analogtodigitalconverter(ADC),160AngryBirds,13,28Animation01.py,208–209Animations,208–233

ambient,225–228inboatracegame,231character,228–229C2H6OJetBoatRace,237–242cutscenes,229–231elementary,creationof,209–214math,214–219reactive,219–225wakes,231

Arc,53–54,55Architecture,10Areatest,123Artificialintelligence(AI),31,104–127,136–137,143–146

C2H6OJetBoatRace,193–201Aspectratio,64–65A*search,146–150Audacity,168–170Audioconcepts,157–161Audiosoftware,168–170Audiosystem,27–28

Page 318: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Autonomouscontrol,130–136Avoidancebehavior,133–135AxisAlignedBoundingBox(AABB)

collisiondetectionusing,116–117,118

BBack-faceculling,121Backgammon,1Ballclause,254–256Betatesting,204Bind,259Blitting,57–58Blockmapmethod,119Boardgames,3Boatracegame

animationsin,231collisiondetectionin,123–127C2H6OJetBoatRace,40–45,70–72,179–206,236–250

Bots,104Bouncingasimulatedball,78–79Boundingboxes,collisiondetectionusing,114,116–118Broadbasecollisiondetection,108,109–120

geometrictests,110–112operationalmethods,109–110spacesubdivision,118–120usingboundingboxes,116–118usingenclosingcircles,112–116

Broadcast-listener,33–34Buttons

C2H6OJetBoatRace,182–184

CCapitavelNavia,91Car,controlling,131–136

avoidancebehavior,133–135cruisingbehavior,132–133waypointRepresentationandImplementation,135–136

Cardgames,3–4randomnessin,90–96

Page 319: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Casualgames,8Cellularphones,13Channels,161,162,164–165Characteranimation,228–229AChristmasCarol,4Circle,56Circle-circlecollisions,114–116

closestpointonalinetoaspecifiedpoint,finding,115–116Civilization,13clock.tick,77–78Cognitivesimulation,104Collisiondetection,104–127

inboatrace,123–127,240–242broadbasecollisiondetection,108,109–120C2H6OJetBoatRace,193–196narrowbasecollisiondetection,120–122

Color(s)class,55gradientcreation,51–52pixelsand,67–70transparent,59–61

Computergames,commonaspectsof,9–10Conflict,4–15Copy,226CoreTechniquesandAlgorithmsinGameProgramming,27CrazyTaxi,14Crossproduct,111Cruisingbehavior,132–133C2H6OJetBoatRace,40–45,70–72,179–206,236–250

animationsexplosions,238–242wakes,237–238

artificialintelligenceboat,avoiding,199–200collidingwiththeshore,200–201collisions,193–196navigation,196–197waypoints,197–199

boatclass,192–193

Page 320: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

designdocument,41–45gameplay,244–247completingtherace,244finish,247intermediateplay,246start,244–246timer,245–246

mini-map,247–249gamedata,248–249

playscreen,187–190prototype0,180–181prototype1,181–187buttons,182–184endscreen,186optionsscreen,185–186playscreen,186screens,181–182startscreen,184–185

prototype2,186–187sound,201–203,242–244audience,244bing,244collisionsandexplosions,203enginesounds,202–203,242–243finish,203,244startinggun,203,243

testing,203–206tuning,249usercontrol,190–192

Cutscenes,229–231

DDanceDanceRevolution,8Desktopcomputers,10–11Dice,randomnessin,90–96Display,55,227display.blit,69Distanceattenuation,171–172DonkeyKong,8

Page 321: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Doom,8,18Dotproduct,111DoubleDash,15DragonSlayer,8Draw,55,222,228,240Drawingtext,58–59

EElderScrollsOnline,8Enclosingcircles,broadbasecollisiondetectionusing,112–116Entertaining,2Eventsofgameloop,79–87

bettergame,86–87keyboard,82–83mouse,81–82on-screenbutton,84–85simplegame,85–86

Explosionsboatcollisions,determinationof,240–242C2H6OJetBoatRace,237–242

FFermi,Enrico,96Fidelity,18–19Fightinggames,8Fill,55FinalFantasyXI,8Finitestatemachines,136–144

airstate,141–142attackingstate,142damagedstate,142defendingstate,142–143patrollingstate,143inpractice,137–140searchingstate,143skiddingstate,143startstate,141stateand“whatdowedonow”problem,140–141stoppingstate,144

Page 322: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Flash,214Flightsimulator,7FMV.SeeFullmotionvideofont.render,59Forloop,64Frequency,158Friction,215FSAs.SeeFinitestatemachinesFullmotionvideo(FMV).SeeCutscenes

GGambling,90–92Game,definitionof,1–2GameBoy,12GameCodingComplete,27Gameconsoles,11–12Gamedesign,28–30

mechanics,29–30Gamedesigndocument(GDD),39,40,179

C2H6OJetBoatRace,41–45GameDeveloper’sConference,17Gamegenres,6–9

action,8,9roleplaying,7–8simulation,7sports,6–7strategy,6

Gameloop,74–100events,79–87randomness,87–96randomvaluegeneration,96–98realityandintelligence,simulationof,98–100timeandintervals,74–79

Gamestate,32Gametesting,203,204GDD.SeeGamedesigndocumentGebert,Nigel,175Geometriclevelofgraphicssystem,26–27Geometrictests,forcollisiondetection,110–112

Page 323: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

getPosition,33,222get_pressed,83,191GHz.SeeGigahertzGigahertz(GHz),158Globalentities,34–35Globalstateofthegame,32Golfinggames,6–7GoogleDocs,40Graphics,15,47–72

pipeline,25system.SeeGraphicssystem

Graphicssystem,24–27geometriclevel,26–27objectlevel,25–26optimization,27rasterizationlevel,27

HHalfLife,15,156Halo,15,156Hertz(Hz),158Hiddencomputergames,30Hitchcock,Alfred,156HockeyPong,136Horrorgames,8Hz.SeeHertz

IImagetransformations,64–67

rotation,65–67Images

negativeimage,63–64pixels,62–63Pygame,61–64

im.get_at,62im.get_height,61im.get_width,61iMovie,225im.set_at,63

Page 324: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Intelligenceandreality,simulationof,98–100Interaction,9Interestinggames,aspectsof,13–19

conflict,14–15fidelity/accuracy,18–19graphicsandsound,15interface,16–17pace/scale,17–18props,15–16venue,13–14

Interface,16–17,33Interiorangletest,123Intervalsofgameloop,74–79isArmed,184

KKeyframes,211Keyboardevents,82–83Key_pressedmethod,83KHz.SeeKiloHertzKiloHertz(KHz),158Kineticgames,3,8

LLatency,251TheLawnmowerMan(film),4Line,52–53,55Listen,259LittleBigPlanet,15

conflict,15LogitechWingman,17Loudness,158Lua,35

MMac

iMovie,225Macs,10Managers,33

Page 325: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

MarioKart,134Mathematicalgames,3,4Mechanics,9,29–30Megahertz(MHz),158MHz.SeeMegahertzMicrosoft

MovieMaker,225AMillionRandomDigits(book),96Mini-map,247–249Mixer,161,162Monopoly,13Motionequations,216–219Mousebuttonevents,81–82mousePressed,182mouseReleased,182MovieMaker,225Moviepy,231Multipleinheritance,35Myst,8

NNarrowbasecollisiondetection,120–122

ray/triangleintersection,121–123Navigationandcontrol,129–152

A*search,146–150basicautonomouscontrol,130–136C2H6OJetBoatRace,196–197finitestatemachines,136–144pathfinding,144–146stochasticnavigation,151–152

Negativeimage,63–64Networking,251–272

SeealsoPongNewton’sLawsofMotion,215–216nextStep,198Nim,4Nintendo,12NintendoSwitch,12Non-playercharacters(NPCs),129,131,144,192,196,198,200,206,245,248

Page 326: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Notepaperpagecreationlinesandcurves,53–55pixellevelgraphics,50–51

NPCs.SeeNon-playercharacters

OObjectlevelofgraphicssystem,25–26Objectorientedboundingbox(OOBB)

collisiondetectionusing,117–118Objects,9,10Oddintersectionstest,123On-screenbutton,84–85OOBB.SeeObjectorientedboundingboxOpen,259Opponents,104,105Optionsbutton,183–184optionScreen,182

PPaddleclass,253–254Paint,210,214,220Parcheesi,1Pathfinding,144–146Pause,222Photoshop,214Pitch,157,158Pixellevelgraphics,49–52

colorgradientcreation,51–52notepaperpagecreation,50–51

Pixels,62–63andcolor,67–70SeealsoPixellevelgraphics

Planetside,9Platforms,10–13

cellularphones,13desktopcomputers,10–11gameconsoles,11–12portableconsoles,12tablets,11

Page 327: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

Play,2,9,222Playingthegame,byrules

artificialintelligence,31broadcast-listener,33–34gamestate,32globalstate,32hiddencomputergames,30managers,33push/pull(clientserver),32–33sharedandglobalentities,34–35

PlayStation,12Playtesting,203,204Polygonalobjects,collisionsin,107–109Polygons,56–57Pong,35–39,252–271

ballclause,254–256communicationbetweenprocessesmovingaballonthescreen,257–261

network,262–272blockingandnon-blocking,265–267client,262–264,268–269messages,267–268playingthegame,271server,264–265,270–271

paddleclass,253–254Portableconsoles,12Portal,9,28,30Positionalaudio,170–176

2Dpositionalsound,172–176distanceattenuation,171–172

Probability,92–93calculations,93–96

Props,15–16Pseudorandomnumbers,88,97–98Push/pull(clientserver),32–33Puzzlegames,8Pygame,47

blitting,57–58drawingtext,58–59

Page 328: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

essentials,48–49gameloop,74–100imagetransformations,64–67images,61–64linesandcurves,52–55pixellevelgraphics,49–52pixelsandcolor,67–70polygons,56–57soundin,161–176transparentcolors,59–61

pygame-vlc,231pygame.draw.circle,69–70pygame.event,79–87pygame.event.get,82pygame.font.Font,59pygame.image,62pygame.image.load,61pygame.init,54,55,76pygame.KEYDOWN,82,83,191pygame.key.get_pressed,83pygame.KEYUP,82,83pygame.QUIT,81,82pygame.Surface,68pygame.time,76–78pygame.time.delay,76,77pygame.time.wait,77pygame.transform.rotate,65,66PyMedia,231

QQuantization,24

RRacinggames,6–7Ragdollphysics,7RandCorporation,96Randomvaluegeneration,96–98

pseudorandomnumbers,97–98Randomness,87–96

Page 329: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

diceandcards,90–96Rasterizationlevelofgraphicssystem,27Raycasting,126–127Ray/triangleintersection,121–123Reactiveanimations,219–225

usingrealimages,224–225ReactiveGripcontroller,17Real-timestrategygames,6Realityandintelligence,simulationof,98–100Rect,56Rhythmgames,8Roleplayinggames(RPG),7–8RollerCoasterTycoon,7Rotate,199Rotationofimages,65–67RoyalGameofUr,1RPG.SeeRoleplayinggames

SSandbox,9,15Scale,17–18SchellGames,205SCRALPHA,60screenState,182,184screen_to_terrain,194Send,258,260set_at,55setExist,33set_mode,48,55setNext,227setPosition,222setRate,227Sharedentities,34–35Shooters,8shoreCollide,194showNextExFrame,240Sign,86SilentHill,8,9SimCity,7

Page 330: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

TheSimpsonsHit&Run,15TheSims,9,14Simulation

cognitive,104ofrealityandintelligence,98–100

Simulationgames,5,7Smallstudio,167–168SMVRainbow,247,248Socket,257–258Softwaretesting,203–204SonyPSPSlim,12Sound,15,156–176

C2H6OJetBoatRace,201–203options,162–165ownsounds,creationof,165–170positionalaudio,170–176inPygame,161–176recording,usingcellphonesandMP3devices,166–167volume,163–164

SpaceInvaders,29,75Spacesubdivision,collisiondetectionusing,118–120Spherevs.planecollision,113–114Sportsgames,6–7Sprouts,4SRCALPHA,60StarTrek(film),4,18startScreen,182,184Stochasticnavigation,151–152Stop,222Straightaheadmethod,214,219Strategygames,6SuperMarioBros,12surface,55surf.fill,61,68Survivalhorrorgames,8

TTablets,11Terraintexturegenerationtool,71

Page 331: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

terrain_to_screen,125,199Testing,203–2063Dgames,18,23–25

animations,221Timingofgameloop,74–79tkinter,47Towerdefensegames,6transform,64–67Transparentcolors,59–61Triviagames,8Tuning,249Tweens,211Twitchgames.SeeActiongamesTwo-playerchasegame,12Dgame,23–252Dpositionalsound,172–176Tycoongames,7

conflict,14

UUpdate,55USBinterface,16

VVenue,13–14Videogamearchitecture,21–28

audiosystem,27–28graphicssystem,24–27

VideoLotteryTerminals,88VideoMach,224–225Virtualreality,4–6Vita,12Volume,158

WWakes,231,237–238Warcraft,6Waypoint

C2H6OJetBoatRace,197–199

Page 332: Game Development Using Python - dl.booktolearn.comdl.booktolearn.com/ebooks2/computer/game... · Dulles, VA 20166 info@merclearning.com 800-232-0223 James R. Parker. Game Development

implementation,135–136pathfinding,134–135representation,135–136

Wordgames,4WorldofWarcraft,13

XXbox,12

ZZooTycoon,7,14Zork,8