280 likes | 366 Views
SGDC Boot Camp 4. Because I trust you guys. Here’s How it Works. I’m home for Passover. Unavoidable commitment. You’re going to teach yourself this one. Study at your own pace, then do the project Send questions to zfreedma@stevens.edu. Submit Your S**t. Do this immediately
E N D
SGDC Boot Camp 4 Because I trust you guys
Here’s How it Works • I’m home for Passover. • Unavoidable commitment. • You’re going to teach yourself this one. • Study at your own pace, then do the project • Send questions to zfreedma@stevens.edu
Submit Your S**t • Do this immediately • Navigate to the folder containing last week’s assignment • Normally, this is [Your Folder]/Documents/Visual Studio 2008/[Project Name] • Delete the folders called ‘obj’ and ‘bin’ • Zip up the entire project folder • Send it to zfreedma@stevens.edu
What’s Gonna Be Covered • Collections • How to keep track of a whole bunch of stuff • …DYNAMICALLY! • Iteration • How to deal with a whole bunch of stuff • …AUTOMATICALLY!
Collections • Remember how a field, like a float, is a slot? • Remember how a class (like your BadGuy) is a whole bunch of slots in a larger slot? • Well, a collection is a bunch of slots that are bound together. • The collections you’ll run into: • Array • List • Dictionary
This Episode Sponsored by the Letter T • When you see the letter T as a parameter, it means a Type of slot. • This doesn’t refer to an actual object, just a type of object. • These can be T: • float • bool • Vector2 • GoodGuy ← Assuming you’ve made the class • These are not T: • boolaBool; ← An instance • Vector2.Zero ← A static member • “foobar” ← A string literal
Arrays An array is the simplest form of a collection. One of the C# base classes Arrays are linked, usually consecutive, memory slots of the same type. When you declare an array, all of the slots are allotted at once. The [] parameter holders are used to deal with arrays
Arrays • How to declare an array: • float[] fiveEntryFloatArray= new float[5]; • This is saying, “Hey compiler! Crack open five float slots.” • Note the following: • The array must be instantiated, even though the base type (a float) does not • The array isn’t instantiated with a constructor • float[] fiveEntryFloatArray = new float[5](); ← NO!! • The number of slots in the array can’t be changed. • Let me repeat that: Once an array has been declared, the number of entries is locked.
Arrays • To refer to a specific slot by index, do this: • fiveEntryFloatArray[1] = 122f; • float myNumber = fiveEntryFloatArray[1]; ← Index • The slots start at index [0] • You’ll get an exception if you try to go out of range.This throws an error: • float myNumber = fiveEntryFloatArray[5]; • Think about that for a second. • The error returned is IndexOutOfRangeException. • Fairly self-explanatory
Lists A more complex way to store many pieces of data Slots are added as needed and linked together Uses more memory than an array And is a teeny bit slower to retrieve However, a list is not a fixed size. Lists require the System.Collections.Generic namespace This is usually included in the default using statements
Lists • How to declare a list: • List<float> listOFloats = new List<float>(); • This is a strongly typed list – it will now only accept floats. • Non-strongly-typed lists are tough to use. • Note the following: • The list must be instantiated with a constructor • The constructor must contain the same type in the <> as the declaration
Lists • To add or remove an entry, use the List<T>.Add() and List<T>.Remove() methods • You can retrieve entries like in an array • float myNumber = listOFloats[1]; • Starts at [0] • However, do not do this! • You can easily forget how many entries are in the list and get an IndexOutOfRangeException • A list is not sorted – no guarantee you’ll get the entry you’re looking for • So what’s the point? Bear with us.
Dictionaries A really complex way to store many pieces of data Behaves exactly like a list, except you explicitly set the indices. Keys and values are strongly typed, and can be any type you want Keys can’t be changed once the entry is added Uses a lot more memory than an array, but isn’t much slower to retrieve Useful any time a real-life dictionary would be. Good for storing information in an intuitive way.
Dictionaries • How to declare a dictionary: • Dictionary<string, float> studentsAndGPAs = new Dictionary<string, float>(); • Similar constraints as a List • To add or remove an entry, use the Dictionary<T, T>.Add() and .Remove() methods • You can retrieve entries using a key as the index • float myGPA = studentsAndGPAs[“Zack”];
Dictionaries • Caveats: • Multiple entries can have the same value, but all keys must be different • You’ll throw an exception if you flub the key • If the value of the key changes, you’ll have some shenanigans
Iteration • The fine art of doing things over and over again • Three main iteration keywords: • for • do/while • foreach
for • Iterates a specific number of times. • How to use: • for (inti = 0; i < 50; i++) { block ‘o code } ← In your code, use whitespace • WTF? • inti = 0; ← Declare and set a variable • i < 50; ← Boolean expression. If this is true, block ‘o code will run. If it’s not, leaves block ‘o code and stops iterating. • i++ ← After each iteration, this calculation is done. • The variable you use is available inside the block ‘o code.
do/while • Iterates until false • How to use: • do { block ‘o code } while (bool) • If bool is true, block ‘o code is done again • This is a great way to freeze your game. • Remember, the Draw() method ain’t called til Update() is done, and if it’s stuck in an infinite loop, your game is halted. • Don’t use unless necessary, and make sure there’s a kill-switch if it runs too long. • You’re probably better off using for. Forget I taught you this one.
foreach • Probably the most useful keyword in the entire C# language • Iterates over each member of a collection • How to use: • foreach (float f in listOfFloats) { block ‘o code} • f is available in your block ‘o code • This lets you do something with each member of a collection, one by one. • Such as call their Update() and Draw() methods. • Remember, a List can have a flexible number of entries. • Starting to put the pieces together?
foreach • Caveats: • Throws an exception if the number of entries in the collection changes during iteration. • Don’t add or remove during iteration! • To foreach through a Dictionary, use • foreach (KeyValuePairkvp in yourDictionary) • You can’t modify the properties of the KeyValuePair. Sorry.
Putting the Pieces Together • A List lets you hold a dynamic number of memory slots • The foreach keyword lets you do something with every entry, regardless of how many there are • Combine the two, and you no longer need to declare and call methods on entities by hand! • Think of the possibilities! • Sorry for wasting your time with the last assignment. • It was a learning experience
Just a Hot Second! • So if we can’t add or remove from a collection during foreach, how do we remove dead entries? • Simple: • Create a deadEntries List • During iteration, Add() a reference to the dead entry • After iteration, foreach entry in deadEntries, Remove() it from the live entries list • Finally, Clear() the deadEntries List.
Bonus! Enumerations • An enum is a linked set of named constants. • Basically, it’s a const int field where the user is limited to which ints they can pick, and each int is named. • You’ve used these before: • SpriteEffects • Players • Think of an enum like a color swatch book →
Enumerations • How to create: • public enumFishTypes { Salmon, Mackerel, Cod, Gefilte, Tuna, Flounder } • Create this OUTSIDE of a class • How to use: • private FishTypeswhatsMyFish = FishTypes.Gefilte; • Useful to limit programmers to predictable choices
Your Homework • Create Breakout! • Use your own images for the paddle, ball, and blocks • Re-use your collision detection code from last time • Hint: The position of two objects that collide can be used to determine where the collision occurred • foreach through an array to declare, initialize, update, draw each block in one shot • Use an enum to store which color the block is • Add some way to tell the player how many lives he has left • It must look significantly better than this →
Extra Credit • Add a few powerups • Fireball: Disable collision detection • Lasers: Re-use your Projectile class • Big Paddle: Change your Scale (and re-calculate the Bounds!) • Make some special blocks • Invinci-blocks • Blocks that take a few shots to destroy • Make sure the user can tell the difference! • Make a ridiculous way to destroy that last pesky block • Best project wins a prize
The Attached Code Demonstrates everything covered today To change what happens, edit the actionMode field in the Game1 class You can see the ActionModesenumright above the Game1 class.
The Attached Code • In ActionModes.ArrayDemo, a Sprite[16] is used to draw the Andy Warhol thingy in many fewer lines. • In ActionModes.ListDemo, a new BadGuy is added to the List whenever the A button is pressed. • In ActionModes.DictDemo, a Dictionary is populated with each button on the GamePad and is used to store their values. • To see this work, follow the directions in the code to enter Debug mode and view the Dictionary’s contents. • In ActionModes.ForDemo, a huge number of Sprites are drawn on the screen using for. • In ActionModes.DoWhileDemo, an infinite Do/While loop freezes the game.