Difference between revisions of "Code How To's"
(→Publish the Installer) |
|||
Line 685: | Line 685: | ||
* Once the upload is complete, ssh into a shell and enter the command "mv /home/{$user}/tAC_Installer.exe /home/belmonte/autismcollaborative.org/downloads/AstropolisSetup.exe" (you may have to open a terminal first, depending on your SSH client) | * Once the upload is complete, ssh into a shell and enter the command "mv /home/{$user}/tAC_Installer.exe /home/belmonte/autismcollaborative.org/downloads/AstropolisSetup.exe" (you may have to open a terminal first, depending on your SSH client) | ||
** If there is a permissions problem, contact Matthew to make certain that your user ID has write and search permission for the autismcollaborative.org/downloads directory. | ** If there is a permissions problem, contact Matthew to make certain that your user ID has write and search permission for the autismcollaborative.org/downloads directory. | ||
+ | |||
+ | ==Using the Mini Game Score Screens== | ||
+ | |||
+ | The Mini Game Score Screens are implemented in a class within the tAC_Engine. This class is utilized to encapsulate the behavior for the displaying the scores of mini games uniformly to players, while also allowing a uniform means of exiting the mini game. All mini games utilize the 2 screen approach (one for the menu for the game, one for the actual game) on top of tyhe stack. Because of this, the mini game score screen allows the direct exiting of a mini game after it has been played, returning back to the Colony Simulation or previous game screen on the stack, before the mini game was selected. | ||
+ | |||
+ | This is done by clicking the Exit button in the score screen, which performs 3 Done() operations on the stack. | ||
==Use the ErrorLog== | ==Use the ErrorLog== |
Revision as of 15:10, 3 March 2009
This page provides tutorials for some of the most common actions a programmer may wish to implement. It may helpful to read the Code Overview first.
Contents
- 1 Submit a Bug or Other Issue
- 2 Coding Conventions
- 3 Create a New Minigame
- 4 Use Images
- 5 Create a New Type of Game Object
- 6 Get User Input
- 7 Manage a Heads Up Display
- 8 Display Text or Icons with the Ticker
- 9 Display Text
- 10 Use Sound
- 11 Use the Particle Engine
- 12 Keep Score and Give Resources to the Simulator Mode
- 13 Write to the Experiment Log
- 14 Use the Game Script
- 15 Publish the Installer
- 16 Using the Mini Game Score Screens
- 17 Use the ErrorLog
- 18 Testing Procedure
Submit a Bug or Other Issue
- Go to http://www.AutismCollaborative.org/bugs/
- Fill out the fields that apply to this issue
Type of Bug:
- Functional Problem
- Any actual "Bug"
- Suggestion
- A possible change to the game that may improve it
- New Feature
- Something that absolutely must be implemented
- Use sparingly; make sure it's not actually a Suggestion
Severity:
- How much this issue affects the game/application
Priority:
- How soon the issue should be resolved (relative to other issues)
- The majority of issues should be Low priority
- Use High sparingly
Coding Conventions
- Place the name of the file, authors, and copyright info at the top of each file
- Any person who makes significant changes to a file should add their name to the list of authors in a file
- This helps anyone reading the code because they know who to ask if they have a question about something
- Any person who makes significant changes to a file should add their name to the list of authors in a file
- All private and protected class member variables are lowerCamelCase
- Private/protected class member variables are preceded with "m" (ie mLocalVariable)
- All functions, properties (sometimes called "smart fields"), and public class variables are UpperCamelCase
- Public variables should only be used with small classes that are used by only one or two other classes
- This code is intended to be viewed by many people who do not have strong programming backgrounds, therefore documentation is very important
- Document the purpose of each class's member variables, either next to their declarations or as a summary for their property accessor
- Create a summary documentation block for every function unless it is extremely obvious
- This can be done by placing the cursor above a function definition and typing "///"
- This block shows up in Intellisense when writing that function in code
- Add a summary to any properties that are possibly confusing or not straightforward
- Document every step of each algorithm (except for very obvious function calls like ResetSettings();)
- Someone should be able to read only the comments in a function and still understand what it does
- See MeteorMadness.cs for an example of the appropriate level of documentation
- See the Load a Texture section for naming conventions of texture assets
Create a New Minigame
For a step by step tutorial with code examples, see How_to_Make_a_Mini-Game
- Declare the class
- Create a new folder under ColonySimulator
- Create a new file in that folder named NewMinigame.cs where NewMiniame is the name of the new minigame
- Place all new minigame-specific classes in that folder
- Have the class derive from GameScreen
- Implement the Constructor
- Initialize game variables
- Declare a ScoreCard (see Scoring tutorial)
- Log the GameBegin code (see the Logging tutorial)
- Implement Update()
- Do not assume a constant call rate
- This function will almost always be called 60 times per second, but that rate may vary depending on CPU load
- At the beginning of each cycle, get the time since the last cycle like this:
- float dt = gameTime.ElapsedGameTime;
- Build the time into all movement and timers, for example:
- Do not assume a constant call rate
myEntity.LifeSpan -= dt; myEntity.Position += myEntity.Velocity * dt;
- Implement Draw()
- Be sure to call each entity's Draw and Update methods. Optional: Register all entities with the XNA game object.
This will have XNA automatically call their Draw and Update functions at appropriate times.
- Consider using a generalized render-queue such as GenericWorldSpace (not yet implemented as of October 2007)
- Use the Raise function to place the minigame gamescreen on the stack based game system.
- End the mini-game using Done function. This will pop the mini-game off the game stack, returning the game to the previous state.
- Flush the particle system (see the particles tutorial) if any emitters were created
- Log the GameEndSuccess/GameEndFailure code
- Show the score
Use Images
XNA supports most common types of images, including JPEG, GIF, DDS, etc.
Load a Texture
Before you can load a texture in code, though, you must add it to the content pipeline:
- Import the content into the project
- Browse to the appropriate folder in Visual Studio's Solution Explorer
- For example, Content\MiniGames\MyImage.png
- Right-click on that folder and select Add->Existing Item
- Select the image to import
- Browse to the appropriate folder in Visual Studio's Solution Explorer
Once that's done, you can load it memory using the XNA content manager:
Texture2D myTexture = Content.Load(@"General\myTexture");
The XNA content manager defaults to the content folder of the project, so all addresses can be relative from there. Also, the name of the image should be the same as the asset name. This can be set in the properties window.
Display a Static Image
Before manually drawing something to screen consider using some type of game object, be it an Entity, HUD element, or even a Ticker (see the tutorials below). Game objects all know how to draw themselves, so it is unlikely that a minigame will need to draw something directly to the screen. Should the need arise, however, here's how it's done:
- Load it in code:
GraphicsDeviceManager gdm = ...; // This is declared in GenericGameManager.cs ConentManager cm = ...; // Usually a parameter, as in Update(ContentManager content) SpriteBatch sb = new SpriteBatch(gdm.GraphicsDevice); // Basically a wrapper for a DirectX render target Texture2D texture = TextureManager.Load(@"Content\General\myTexture"); Rectangle destination = ...; // Display destination Color tint = Color.White; // Tint the image with this color float rotation = 0f; // Rotation (in radians) Vector2 center = new Vector2(texture.Width / 2f, texture.Height / 2f); // Origin of rotation float zDepth = 1f; // Order to draw sprites within this spritebatch sb.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, SaveStateMode.SaveState); sb.Draw( texture, destination , null, // What part of the source image to sample from--null tells it to use the whole image tint , rotation, center, SpriteEffects.None, // How to mirror the image zDepth ); sb.End();
Display an Animation
Animations are created using the AnimatedSprite class. Here's an example:
//Declare Animated Sprite //Parameters: Game object, SpriteSheet as a Texture2D object, Position as Vector2, FrameSize as Vector2, Number of Frames AnimatedSprite testAnimation = new AnimatedSprite(this, Content.Load<Texture2D>("TestSpriteSheet"), new Vector2(200, 300), new Vector2(64, 64), 16); //Pass a reference to the SpriteBatch that the AnimatedSprite will use testAnimation.SpriteBatch = spriteBatch; //Turn on the Animation testAnimation.Animate(true); //Turn off the Animation testAnimation.Animate(false);
- Do not forget to call the draw and update methods of the AnimatedSprite explicitly, or to add them to the XNA game.components array so as to allow XNA to call them.
Create a New Type of Game Object
All specific game objects (players, enemies, collectibles, projectiles, etc.) should derive from Entity. This gives them easy ways to draw themselves, move, collide with other entities, and be passed to many tAC_Engine functions.
Get User Input
DO NOT use the standard XNA keyboard accessors (Xna.Framework.Input.Keyboard) or mouse accessors (Xna.Framework.Input.Mouse) because tAC_Engine does a lot of caching and logging behind the scenes. Use the InputHandler instead.
Keyboard Example
// Bind the 'A' Key to the event 'PressedA' mInputHandler.Bind(Keys.A, InputHandler.Trigger.Pressed, (int)EventCodes.PressedA); ... InputEvent inputEvent = mInputHandler.GetNextEvent(); if (inputEvent.EventCode == (int)EventCodes.PressedA) { // The A key was pressed }
Loading Keybinds from a file
// Load Bindings from 'keybindings.dat' mInputHandler.LoadBindings(typeof(EventCodes), RootDirectory + @"\keybindings.dat");
The Bindings file is a plain text, human-editable file that takes the following form:
"Event Name" (tab*) "Key Name" (tab*) (flags*)
Keybinding Examples
Quit Escape
- Trigger the Quit event when Escape is pressed.
PlaceBuilding Left mouse
- Trigger the PlaceBuilding event when the Left Mouse Button is pressed.
ZoomInStop OemPlus released
- Trigger the ZoomInStop event when the Plus Key is released.
Manage a Heads Up Display
Use the HUD class for any HUD element (like health bars, menu buttons, etc.). Typically, you'll want to create a class that inherits from Widget2D. See MeteorWidgets.cs for examples.
Display Text or Icons with the Ticker
string text = "w00t."; // Text to display (can be "") Texture2D image = null; // Can also be set to an image Vector2 imageSize = new Vector2(25f, 25f); // Size of the (optional) icon Vector2 offset = new Vector2(700f, 50f); // This will display the ticker 700 pixels to the right of the screen's // center and 50 pixels below the screen's center Vector2 velocity = new Vector2 (-10f, 0f); // Move left 10 pixels per second Ticker.Font font = Ticker.Font.Standard; // Regular text Color color = Color.DeepPink; // The manliest of colors float opacity = .5f; // 50% transparent float seconds = 5f; // Disappear after 5 seconds bool fade = true; // Fade in and fade out Ticker.Display(text, image, imageSize, offset, velocity, font, color, opacity, seconds, fade);
Display Text
First you must import the desired font:
- Create an xml spritefont file for the new font called FontName.spritefont and set the desired values.
Now for the code:
ContentManager cm = ...; SpriteBatch sb = ...; SpriteFont = cm.Load<SpriteFont>(@"FontName");
sb.Begin(); sb.DrawString(SpriteFont, "Some Text!", new Vector2(10.0F, 10.0F), Color.Azure); sb.End();
Use Sound
Import a new Audio File
- Run the XACT tool from Microsoft DirectX SDK
- If--after following the steps in this tutorial--playing a file in code throws an exception about using the wrong version of XACT, try using Xact.exe from a different SDK build
- Open AudioProject.xap file for the Minigame to which you wish to add a sound.
- Expand Wave Banks and double-click Wave Bank in the panel on the left
- Expand Sound Banks and double-click Sound Bank in the panel on the left
- Go to Wave Banks->Insert Wave File(s)...
- Select the file to import i.e."@/MiniGame/Content/Audio/MySound.wav" and click OK.
- Drag the newly-added file to the Cue Name section in the Sound Bank:Sound Bank window
- Assign the audio file to be either a Music or Effect sound
- Go to File->Build
- Save and close XACT
- Open game.sln with Visual Studio
- Browse to the Content\Sounds folder in the Solution Explorer
- Right-click the Sounds folder and select Add->Existing Item...
- Select "MySound.wav" and click OK
Load an Audio Project
This needs to be done before you play any sound or effect. SoundManager.LoadAudioProject("AudioProject.xgs");
Play an Effect
SoundManager.PlayEffect("Pew"); // No file extension
Play Music
SoundManager.PlayMusic("MyMusic");
Use the Particle Engine
Particles are handled by the TACParticleEngine, a separate library that uses the AC_GraphicsEngine that has been modified to better fit the needs of the Autism Game. Features are added to it on an as-needed basis so if a new feature needs to be added and any problems arise in its integration into the current particle engine contact Brian Murphy.
Quick layout of TACParticleEngine:
The ParticleManager contains references to all loaded ParticleEngines. ParticleEngines contain a series of Emitters. Emitters contain a heap of Particles, which are the objects that actually get drawn.
Make sure to include these packages so that we can create and access our particle engine objects:
using TACParticleEngine; using TACParticleEngine.Particles;
Inside the class declaration make these global variables:
ParticleManager mParticleManager; ParticleEngine mTestEffect;
Since the TACParticleEngine makes use of the Camera class from the AC_GraphicsEngine, we will need to create and initialize an instance of the Camera class if we are to render our particles, so let's get our camera set before we initialize the ParticleManager.
Add the following line to the list of global variables at the beginning of the class:
Camera mActiveCamera;
This will be whatever kind of camera we are currently using for drawing. (We may want other cameras, too, for whatever reason.)
Next we need to initialize the camera to any specific type of camera that derives from class Camera. At the time of this writing (January 2009) these types are limited to FollowCamera, OrthographicCamera, PerspectiveCamera2D, and PerspectiveCamera3D. For now we'll use a PerspectiveCamera3D as our active camera.
mActiveCamera = new Perspective3DCamera(new Vector3(0, 0, -5), Vector3.Zero, Vector3.Up, MathHelper.Pi/5, 1, 1, 100);
If we ever need to change the camera, be certain to update the active camera for the particle manager by calling
mParticleManager.SetActiveCamera(newActiveCamera);
where newActiveCamera is the camera that has just been changed to.
Now that we have a camera, make sure to initialize the particle manager (and optionally, some particle effects) in the class's initialize method:
mParticleManager = new ParticleManager(Game, mActiveCamera); // Initialize the particle manager object with a reference to the current // game and to the current active camera mTestEffect = mParticleManager.Load("ParticleEffects/Explosion"); // Load in the given particle effect file by giving the // location at which it is compiled
Once this has been done, you'll have an effect loaded into the Particle Engine object mTestEffect via the Particle Manager. However the Particle Engine isn't worth much if it's never called on to do anything, so let's set up the rest of the code that's needed for updating and drawing:
To accomplish this, all we need to do is add the particle manager to the Game's list of components. This is done as follows:
AddComponent(mParticleManager);
Aside from this we need to set the draw order of the effects, at least generally by calling
mParticleManager.DrawOrder = DrawOrder; // The second DrawOrder being whatever draw order is desired
This will draw and update any particles that have been loaded by the Particle Manager and have been set active. However, the particle engine that we just created hasn't yet been set active, so do that now.
This is done by calling the following line whenever you would want drawing of that Particle Engine to occur.
mTestEffect.SetActive(true);
The particle engine instance mTestEffect is now active. If it were already active, its lifetime would have been reset to 0. (The lifetime of a particle engine starts at zero and increases until its maximum lifetime is reached, in which case the particle engine "dies" and becomes inactive.)
This same method can be used to stop the particle engine from creating any more particles, by supplying false as its parameter instead:
mTestEffect.SetActive(false);
A series of methods allow us to modify the drawing of the ParticleEngine:
SetSplineScale(float scale) // Given a float, scales the spline around the origin by the given amount every 1/10 of a second. Note that this only // applies for all spline emitters in the engine.
SetEnginePositions(Vector3[] Positions) // Given an array of 3D vectors, we can change the shape of all spline emitters in the particle engine.
SetEnginePosition(Vector3 Position) // Given a 3D vector, we can move the whole particle engine to the desired position.
SetEngineColor(Vector4 Color) // Given a 4D vector of float values 0-1 in the form of RGBA, we can change the coloring of the whole particle engine // Keep in mind that this applies that much of the emitters' texture for each value, so a black picture with 1,0,0,1 as // its value will not be red but still black.
SetEngineSize(Vector2 Size) // Given a 2D vector, we can modify the dimensions of the particle image, this is always 2D since particles in 3D are // simply billboard sprites.
SetEngineSpeed(float Speed) // Given a float, changes the speed at which particles initially move at.
SetEngineDirection(Vector3 Direction) // Given a 3D vector, changes the direction in which particles move at. This does not apply to point emitters.
SetEngineParticlesPerSec(float NumPerSec) // Given a float, sets the number of particles created in a second. Note that this value times particle // lifetime should not exceed the amount of particles in order to insure consistent effects.
SetEngineParticleLifetime(float Lifetime) // Given a float, sets how long a particle lives for in seconds. Note that this should never be changed // while an effect is active, otherwise inconsistencies in the effect will most likely occur.
SetRandomDirection(bool Random) // Given a boolean, sets whether or not to make particles move in a random direction.
Also, if needed you can change the draw order of each engine individually by calling
mTestEffect.DrawOrder = DrawOrder; // The second DrawOrder is whatever draw order desired
Whenever a game object that uses a particle effect is being disposed, make sure to call
mTestEffect.SetActive(false); // Making sure to set the effect to no longer being active
on any effect with infinite life span and make sure to call
mTestEffect.ToDestroy = true; // Making sure to set the effect to no longer being alive
so that the particle manager knows that it can clean up the effect.
Create a New Particle Effect
To create a new particle effect, start the TACParticleEditor program. This program presents two windows, one containing a Windows form displaying information about the current particle effect, and the other displaying the particle effect.
There are four main areas of the particle editor form:
List of emitters - The list of all the emitters in the particle effect.
Emitter type - Contains all the different types of emitters that exist in the particle engine.
Row of buttons - Each having a functionality expected from their name: Add - Adds an emitter of the chosen type from the list of emitter types to the particle effect's emitter list. Remove - Removes the currently selected emitter in the particle effect's emitter list from the list. Save - Saves the current particle effect to a specified .particle xml file. Load - Loads a particle effect from a selected .particle xml file.
Emitter Info Grid - Contains all the information that can be modified for whichever emitter in the list of emitters is currently selected.
The modifiable parameters of the emitters are as follows:
For all emitters: textureName - The file path name of the texture to render the particles with. In order to load texture names correctly, there must exist a texture folder in the current project's compiled content folder. The default starting directory is the TACParticleEditor. Whenever a new particle effect is loaded, the current directory is switched to that project's content directory. Anytime a new texture is desired, it must be added manually to the appropriate project. blendEffect - The sprite blend to use when rendering the particles. Can be either None, AlphaBlend, or Additive. The various blend modes work as follows: None - every particle draws exactly as how the texture appears and no alpha values are used. Therefore there will be no transparency. For visual purposes it is highly suggested to not use this mode. AlphaBlend - Averages all of the particles alpha values up to the max value assigned to any particle. This effect is useful in creating effects such as dust, smoke, or gas clouds. Additive - Sums up the colors of all the particles to the maximum value of 1.0 for all values (r,g,b, and a). This effect is useful in creating effects such as fire, lasers, or shields. emitLifetime - The duration of time the emitter continues to emit new particles for in seconds. This can be any duration of time. A negative value denotes that the emitter never dies. particlesPerSec - The amount of particles that are created every second. This can be any nonzero positive integer. particleAmount - The total amount of particles that can appear on screen at one time. This can be any nonzero positive integer. particleLifetime - The amount of time a particle lives for in seconds. This can be any nonzero positive number. minStartSpeed - The slowest possible speed at which a particle can start moving. This can be any number, since a negative value just means that the particle will move in the opposite direction. maxStartSpeed - The fastest possible speed at which a particle can start moving. This can be any number, since a negative value just means that the particle will move in the opposite direction. minEndSpeed - The slowest possible speed at which a particle can end moving . This can be any number, since a negative value just means that the particle will move in the opposite direction. maxEndSpeed - The fastest possible speed at which a particle can end moving. This can be any number, since a negative value just means that the particle will move in the opposite direction. minStartColor - The minimum color values that a particle can start at in r,g,b,a form (i.e. red, green, blue, alpha). These values can be any number between 0.0 and 1.0. maxStartColor - The maximum color values that a particle can start at in r,g,b,a form (i.e. red, green, blue, alpha). These values can be any number between 0.0 and 1.0. minEndColor - The minimum color values that a particle can end at in r,g,b,a form (i.e. red, green, blue, alpha). These values can be any number between 0.0 and 1.0. maxEndColor - The maximum color values that a particle can end at in r,g,b,a form (i.e. red, green, blue, alpha). These values can be any number between 0.0 and 1.0. minstartSize - The smallest size that a particle can start at in width,height form. These values can be any nonzero positive number. maxStartSize - The largest size that a particle can start at in width,height form. These values can be any nonzero positive number. minEndSize - The smallest size that a particle can end at in width,height form. These values can be any nonzero positive number. maxEndSize - The largest size that a particle can end at in width,height form. These values can be any nonzero positive number. isActive - Whether or not the emitter is currently spawning/updating/drawing particles. You can quickly activate all emitters of the loaded/created particle effect by hitting enter while having focus on the particle effect visualization window.
For directional emitters: positions - The position in which particles will spawn in x,y,z form (aka a 3-dimensional point). These values can be any number. minVel - The minimum velocity direction in which particles can move at in x,y,z form (aka a 3-dimensional vector going outward from the position point). These numbers can range from -1.0 to 1.0. maxVel - The maximum velocity direction in which particles can move at in x,y,z form (aka a 3-dimensional vector going outward from the position point). These numbers can range from -1.0 to 1.0.
For point emitters: positions - The position in which particles will spawn in x,y,z form (aka a 3-dimensional point). These values can be any number.
For spline emitters: positions - The positions at/between which particles will spawn in x,y,z form (aka list of 3-dimensional points). These values can be any number. direction - The velocity direction in which particles will move in x,y,z form (aka a 3-dimensional point). (aka a 3-dimensional vector going outward from the position point). These numbers can range from -1.0 to 1.0. scale - The amount of scaling that occurs every time the spline emitter is scaled, that is to say, how much all positions close in/expand from the origin (0,0,0) before any position offset is applied essentially creating an explosion or implosion effect. This value can be any nonzero positive number. 1.5 represents 150% current size, 0.5 represents 50% current size, etc. scaleSpeed - How quickly the scaling occurs in seconds. This can be any nonzero positive number. 1 is a scaling occurs once every second, 0.5 is a scaling occurs every half second, etc.
For spray emitters: positions - The position in which particles will spawn in x,y,z form (aka a 3-dimensional point). These values can be any number. direction - The velocity direction in which particles will move in x,y,z form (aka a 3-dimensional point). (aka a 3-dimensional vector going outward from the position point). These numbers can range from -1.0 to 1.0. sprayRange - The area in which particles can spawn with the center at the set position in +/-x,+/-y,+/-z form. That is to say a cubic area with dimensions width, height, and depth and its origin at the given position. These values be any nonzero positive number.
Quick Reference Table
Parameter Parameter type Unit type Range For all emitters: textureName String N/A Any valid path name works. blendEffect SpriteBlendMode N/A None, AlphaBlend, or Additive. emitLifetime floating-point Seconds Any value. Negative value denotes emitter never dies. particlesPerSec integer Per Second Any nonzero positive number. particleAmount integer N/A Any nonzero positive number. particleLifetime floating-point Seconds Any nonzero positive number. minStartSpeed floating-point Arbitrary Any number. Negative value denotes movement in opposite direction. maxStartSpeed floating-point Arbitrary Any number. Negative value denotes movement in opposite direction. minEndSpeed floating-point Arbitrary Any number. Negative value denotes movement in opposite direction. maxEndSpeed floating-point Arbitrary Any number. Negative value denotes movement in opposite direction. isActive boolean N/A True or False. minVel (x,y,z) vector Arbitrary Any number within -1.0 to 1.0. maxVel (x,y,z) vector Arbitrary Any number within -1.0 to 1.0. positions (x,y,z) vector Arbitrary Any number. direction (x,y,z) vector Arbitrary Any number within -1.0 to 1.0. For spline emitters: scale floating-point % of size Any nonzero positive number. < 1 denotes decrease, > 1 denotes increase. scaleSpeed floating-point Seconds Any nonzero positive number. For spray emitters: sprayRange (width,height,depth) Arbitrary Any nonzero positive number. *Note that all arbitrary values are based on the current camera space.
Keep Score and Give Resources to the Simulator Mode
Use the ScoreCard class to keep track of the score from a minigame. It provides easy ways to add and subtract resources, as well as an easy way to display them and pass them along to the Colony Simulator.
MiniGame has a ColonyScoreCard built into it, accessible by the Score property. Here are some examples of how to use it:
class MyGame : MiniGame { public override void Update(ContentManager content) { Score.Gather(ColonyResources.Money, 500); // Get 500 Monies MyGameObject mgo = new MyGameObject(); mgo.GiveMyGameCarbon(); // Get 1 Carbon Score.IncurDamageCost(100); // On CashOut, Money = Max (Money - DamageCosts, 0) int HowMuchMoneyIHave = Score.QueryResource(ColonyResources.Money); } public void DisplayTheScore() { bool playerWonTheMinigame = true; // Can be set to false if the player lost Score.Display(playerWonTheMinigame ); // Displays a copy of the current score and a message for succses/failure Score.CashOut(); // Transfers resources from MyGame to the Colony Simulator } // ... } class MyGameObject : Entity { public void GiveMyGameCarbon() { ColonyBaseApplication.MiniGame.Score.Gather(ColonyResources.Carbon, 1); } }
- Note: The code provided here is very subject to change as this section is under development.
Write to the Experiment Log
As the game runs, certain actions are recorded and written to a file (My Documents\Autism Collaborative\Users\DefaultUser\LogFiles\ExperimentLog.txt or as specified). In the lab, these codes are also sent through the parallel port to sync the EEG data. Every action that pertains to an experiment must be logged in order to be analyzed. (That's the whole point of this game!)
First define the necessary game codes. This is done to ensure consistency across each mini-game.
- Open EventCodes.cs, or wherever you store the enum for your project.
- Codes in the range 1 - 255 are valid and can be written to the parallel port.
- The name of the code should be chosen at your convenience, and may be included to make the text log file more readable.
- Codes may be assigned outside this range, both positive and negative; these codes may be used in the same way, but will be logged only to the text log file and not to the parallel port.
- Codes in the negative range are considered debugging codes, and can be omitted from the log file by setting the writeDebugEvents property on the logger.
Now those codes are available for logging, thus:
Logger logger = new Logger("ExampleLogFile.txt"); logger.LogCode( (int)Minigame.EventCode.WeaponFiredEvent, "WeaponFired" );
It is also possible to tell the logger to log a code every time a specific key is pressed:
InputHandler inputHandler = new InputHandler(true); inputHandler.Bind(Keys.A, InputHandler.Trigger.Pressed, (int)Minigame.Eventcode.PressedAEvent);
As these assigned events are local to each InputHandler object, your mini-game's event code assignments will not interact with the event code assignments of other mini-games.
Every mini-game should start with its GameBegin and end with its GameEnd[Success/Failure] codes.
It may be helpful to log events for debugging purposes. These codes should have an identifier such as "DEBUG_" and will not be logged unless writeDebugEvents is set to true on the logger. (writeDebugEvents is true by default only when the game is running in Debug mode.) All new DEBUG tags must be explicitly assigned a value less than 0.
Event Code Summary
Event Codes may be any integer value.
- Less than 0 : Debug events, will only be written in Debug Mode.
- 0 : Null, no event.
- 1 - 255 : Experimentation event, will be written to the log and the parallel port.
- Greater then 255 : Cannot be written to the parallel port, will be written to log only.
Use the Game Script
- Note: The LUA scripts are not universally compatible and have been known to crash on some machines. It is highly recommended that C# scripts are used.
The tAC_Engine houses a [Lua] Virtual Machine. This can be used to tweak global parameters at runtime, load them from config files, drive cutscenes, or even save and load levels.
Function callbacks are defined in C# and then invoked from a Lua file or the in-game Debug console. In other words, C# tells Lua "you may use these functions: X,Y,..." and then Lua says "do X, do Y, etc."
Here are a couple of ways to leverage this system:
Make a Cutscene
- Create a new lua file in the Scripts directory
- That file can call any registered function callbacks
- In the Properties window, set Copy to Output Directory to Copy if Newer
- Call that cutscene with:
GenericBaseApplication.GameManager.PlayCutscene(@"Scripts\MyCutscene.lua");
To Register a Function Callback
- Create the function in C# (if the function does not already exist)
- It must be declared public and non-static
- If the need arises to register a static function, declare an instanced function in GenericLuaHelper or ColonyLuaHelper that simply calls the static function.
- Register the function with the Lua Virtual Machine
- Add the special LuaCallback annotation to the function
- Call the RegisterLuaCallbacks function in the class's constructor that contains the function.
- Example:
public MyClass() { // Constructor LuaHelper.RegisterLuaCallbacks(this); } [LuaCallback("SetMyVariable")] public int SetMyVariable(int value) { mMyVariable = value; }
Tweak Game Parameters
Exposing a variable to the Lua Virtual Machine allows it to be accessed by a any script (including config files) or changed at runtime in the drop down console (accessible in Debug mode by hitting "~").
- Expose a variable with a global setter/getter with a LuaCallback annotation
- Make sure to call the RegisterLuaCallbacks function in that class's constructor if the getter/setter is not in the Game Manager
- Set the default value for the variable in the config file (optional)
- There are 3 config files for the 3 configurations of the game builds
- Debug.conf, for development
- StandardRelease.conf, for public releases of the game
- LabRelease.conf, for use in the lab
- There are 3 config files for the 3 configurations of the game builds
Create Local Settings
Programmers may want to change certain properties on their machines without affecting the source-controlled code. They could change the resolution, sound settings, or even have the game bypass the regular startup sequence and launch right into the middle of a MiniGame all with no effect on other developers.
- Create a new file: Autism Collaborative\Game\Game\Scripts\LocalSettings.lua
- The Visual Studio project already has this file included, but VS won't be able to edit it until the file is created manually
- Add Lua commands and save the file
- Visual Studio can now be used to edit the file
- The file is run at the end of the Debug.conf script (if it exists)
- That means that this script is only run in Debug mode
- do NOT add LocalSettings.lua to source control!
Creating Scripts in C# Code
Alternatively, scripts can created using C# code rather than Lua. A C# script either be object oriented or imperative. They are able to both take in objects and return values. The CSharpHelper class can be called to run these scripts using its DoSimpleFile method. This will simply run all the code in the script. The value of this is that commonly edited code, such as configuration files, can be saved in a convenient separate location. The methods for CSharpHelper are well documented within the file itself. An example of a basic call to a C# script is as follows:
CSharpHelper.doSimpleFile(Environment.CurrentDirectory + @"\Configs\DebugConfig.script", this, "game");
This starts a C# file called "DebugConfig.script" which is located in the Configs directory. The second parameter is a Game object. The object passed in can be of any type. The third parameter is the identifier of the object within the script. In this case the identifier is "game". This means that inside the script, lines such as:
game.Update();
will execute the passed-in object's Update function.
Publish the Installer
Create the Installer
We use InnoSetup to create the installer. Checkout their website (http://www.jrsoftware.org/isinfo.php) if you need to change the script, but simply publishing the game does not require any adjustment to the installer script.
- Install InnoSetup if necessary
- Compile the game
- In the second menu bar (immediately below the top menu bar) within Visual Studio, change "Debug" to "Release". (In the box to the right, leave the default "Mixed Platforms".)
- Select Build->Build Solution
- Compile the installer script
- Open Autism Collaborative\Game\Installer\Installer.iss with InnoSetup
- Select Build->Compile
- This creates the file Autism Collaborative\Game\Game\Output\AstropolisSetupLite.exe
- When the compilation is finished, it will ask if you want to test the installer. It is recommended to test it, but not required.
- Repeat the last step with InstallerFull.iss if desired, this will generate AstropolisSetup.exe, which contains the full offline installers for the dependencies. This is necessary for the lab computers which may not have internet access.
Upload the Installer to the Web
- Get a username/password for autismcollaborative.org from Matthew.
- To transfer the file, use an SSH client such as WinSCP (for a graphical interface) or PuTTY's PSCP (from the command line)
- Either download it or run Autism Collaborative\Utilities\WinSCP.exe
- Log in to AutismCollaborative.org (port 22)
- Upload AstropolisSetup.exe to your home directory (for example /home/zinsser)
- Do not overwrite the existing installer (/home/belmonte/autismcollaborative.org/downloads/AstropolisSetup.exe) since that would delete the installer from the web site until the new installer finishes uploading
- Once the upload is complete, ssh into a shell and enter the command "mv /home/{$user}/tAC_Installer.exe /home/belmonte/autismcollaborative.org/downloads/AstropolisSetup.exe" (you may have to open a terminal first, depending on your SSH client)
- If there is a permissions problem, contact Matthew to make certain that your user ID has write and search permission for the autismcollaborative.org/downloads directory.
Using the Mini Game Score Screens
The Mini Game Score Screens are implemented in a class within the tAC_Engine. This class is utilized to encapsulate the behavior for the displaying the scores of mini games uniformly to players, while also allowing a uniform means of exiting the mini game. All mini games utilize the 2 screen approach (one for the menu for the game, one for the actual game) on top of tyhe stack. Because of this, the mini game score screen allows the direct exiting of a mini game after it has been played, returning back to the Colony Simulation or previous game screen on the stack, before the mini game was selected.
This is done by clicking the Exit button in the score screen, which performs 3 Done() operations on the stack.
Use the ErrorLog
When the game encounters an Unhandled Exception (such as when an end user runs into a bug in our code), useful information is dumped to ErrorLog.txt. The user is encouraged to email that file to us so that we can locate the problem. Although the ErrorLog will tell us what function the program died in, it cannot tell us specifically which line was the culprit (although ErrorLogs created when the game is running in Visual Studio will tell us exactly which line).
We do, however, have the ability to log any custom information from a mini-game. This ability may prove invaluable in debugging based on end-user error reports. All that you (the programmer) must do is override the string MiniGame.DebugInfo() function. When ErrorLog.txt is created, it calls that function on the current MiniGame and appends the returned text to the bottom of the file.
Testing Procedure
This is a list of recommended tests to be performed on a regular basis to ensure that the major functionality of the program is intact.
Maritime Defender
- Play through tutorial
Things to Note:
- Text does not run off screen
- Dialog boxes wait for the space bar to be pressed before disappearing
- During the navigation-phase tutorial, input is registered correctly
- Play through main game
Things to Note:
- Collision detection is correct
- Phases are in the correct order
- Navigation phase looks correct: Dots are the correct size and dot correlation fits PEST data. Look for any slowdown or loss of frames.
- Boss fight is correct. Boss takes damage and causes the player damage.
- Player Health is displayed correctly on taking damage.
Colony Simulator
- Check GUI
Things to Note:
- Each button is clickable and causes the appropriate event to occur.
- Make sure that you cannot click through things
- Select each type of building and make sure the pop-up information is appropriate
- Check building placement
- Place each type of building
- Connect a mining building to a factory through a tube
- Connect a residential building to a factory through a road
- Once this is done, resources should increase.
- Connect a residential building to a commercial building
- Once this is done, the player's money should start increasing
- Check the building log to make sure that the build order is correct
- Check that mini-games can be accessed
- Attempt to play each mini-game through the colony simulator, executing all of their tests and checkin their appropriate logs
Stellar Prospector
- Play through the tutorial
Things to Note:
- Make sure that event codes are properly logged.
- Tasks match up with the specified text.
- Text does not run off the display.
- Input events still work when the player is prompted for them.
- Automated events such as energy drain and automatic grab still work.
- Tutorial returns to the main screen after ending.
- Make sure all graphical effects work correctly, i.e. tractor beam, explosion, and flickering.
- Player does not get locked in the game; player remains able to exit through the game menu if ESC is pressed.
- Play through the main game
Things to note:
- Make sure event codes are properly logged.
- Make sure input works correctly
- Phase changes occur correctly and at the right times.
- Energy draining and filling works correctly.
- Pause menu works correctly
- Game ends once energy bar is filled, and returns to the main menu
- Make certain that all graphical effects work correctly, i.e tractor beam, explosion, and flickering.