Showing posts with label Gamedev. Show all posts
Showing posts with label Gamedev. Show all posts

Tuesday, 12 January 2016

Monday, 14 September 2015

Making Audio go private

Today I have been working on getting my Audio system implemented, mostly in order to keep the Activity Lifecycle happy- ie ensuring that media is paused, resumed and released appropriately. The initial implementation I made was an Audio class which was built up of static methods, each able to do a specific function, and if necessary call each other to use pre-existing functionality. The class worked, and is in a small project not a bad model, but I have been reading up on ways to setup a game View and it seems that the Audio class needs to be less public.

Honestly, my first reason for making methods static was that I read that using getters and setters was potentially heavy on resources, but in further reading I have found that for my audio needs this won't be an issue.

The main root of my game framework is now a base activity which is able to create and switch between views, the views themselves after a little experimentation are now extensions of the SurfaceView, and are able to take a pre-initialised Audio instance as a parameter. What this does is allow the main activity to set up the audio environment in one place, passing in itself for context rather than having the Audio being setup in the beginning of a new "screen".

The audio environment is now also much more encapsulated, and as such should only be passed to one screen and any reference will be lost as that screen dies. The activity itself can also ensure that the correct settings are in place for the audio-stream, should the app framework be used for other app types.

The project I have been working on is a soundboard which emulates the character select screen of Mortal Kombat 3, a childhood favourite of mine. So far I have been able to load the 15 game characters names and corresponding "introduction" speech files from the game, and I have it set up to play a random one from this list and display the name on each touch event.
The names themselves exist in an array which is organised in the order that the game presents them on the screen, however it may be necessary at a later date to have them sorted alphabetically- which we will do if needed. One string array (in the strings.xml resource) holds these names, and another array holds the filenames for the audio files in the same order. The reason I have kept the two seperate instead of trying to parse one array into an audio filename, is that I am able to localize the name strings and they will still line up with the sound files whose names are written in english. While the game characters names are the same in any language, it may not be the same in character based languages, and if I ever work on supporting those it would be great to not have to rewrite my audio file loading.

There are probably many other ways to link the names in an array to specific sound files but for now this seems to be the simplest and works well for this project.

The next step will be to load in a music track to loop in the background and then I can begin working on graphics!

Monday, 7 September 2015

MediaPlayer experiments

When working with the media player there are some little things I have found that you need to keep an eye out for. The first is that the MediaPlayer object is quite happy to continue playing your media track after you have closed the app itself. This is an example of how important it is to release all resources and to monitor which ones persist in the memory of the device! While bumming around on the android developer website, I started looking into the billing API and found another example in the Google Payments "Binding" when an in-app purchase is attempted. When an app closes, if that binding is not released, it can use up system resources and degrade performance.

My experiments with the media player began with finding a question on the learnandroid subreddit, which asked about pausing media with a touchevent. From my reading I could see that the poster had not prepared the media track after stopping it, something which is unique to that circumstance but not the pause method. The poster also had a bit of confusion about the touch event itself and where to trigger the media playing. After posting a quick suggestion I decided that I should try to implement a music player in a test app too to get to grips with the little things that might be confusing for a beginner.

Following on from my blank screen SurfaceView test, I used VLC to convert a ripped mp3 into the OGGVorbis format with reduced sound quality (to save on memory) and added that into a new assets folder. From my previous experiemnts with Soundpool (An app with pikachu on it that says pikachu when you touch the screen, and plays a computer booting up sfx from pokemon firered on launch), I knew that sound files can be retrieved using the AssetManager in android. I made the first mistake in not putting the new directory in the right place in the file structure, but that didn't become apparent until it was fully set up.

My first set up was to have all of the media player implemented in the SurfaceView class itself, which is a Runnable in a class called Screen. The implementation included instantiating an asset manager, trying to get the file i wanted an AssetFileDescriptor which I could pass into a new instance of MediaPlayer. The process itself was all set up and the data source set and media started, but the app itself didn't work. After adding some Log notes and an exception message for the try-catch block I found that the asset manager wasn't retrieving the files in the folder, and looked back to my original pikachu app to find the structure difference. 

Once the file was able to load and play I ran the app and lo and behold, the music played, (Nine Inchnails- Satellites for those who need to know!). I was elated, then I closed the app and hmm.. still music.
I knew this had something to do with releasing the resources and the activity life cycle so I started to look there for ways to control my music. I started with onStop, onPause and onResume methods inside my SurfaceView which were called from the main activity, and implemented checks for if the media player was valid and playing etc, and stopped the music and restarted it as I expected. This did not work. The app was happy enough to stop the music but not to restart it when the app was loaded up again. I understood that the app was saved in temporary memory when the app was minimized or obscured, so the app was going through the onPause method, but I didn't realize the onStop method was being called also!

Going back I was able to debug my app and place appropriate boolean flags to control the music playing. In the onPause method, the music is (if it is not already) paused, and on resume the music is (if not null such as on initial bootup of the app) started again. The call to onStop was moved into an if block which checked that the app was not being closed fully (isFinishing()) and if so, stopped playback and also released the media player.
With my experiment finally performing the way I wanted it to, I was finally able to begin abstracting the audio into a seperate class. I created an Audio class that could handle music using static methods, which would mean it is accessible throughout my app. Instead of using a default constructor to set up the Audio environment, I opted instead to use static methods that only initialize variables if they are going to be used. I currently have a method that is needed to pass in a context for use in attaining the assets, but later on I will access this statically from a core class that handles the game.

The Audio class also has onPause, onResume and onStop methods which can be called to ensure that any active media, be it sound FX from the soundPool or music from MediaPlayer are paused and resumed correctly, and destroyed on closing the app.

I am really quite happy with the progress I am making in understanding these (albeit simple) aspects of app development. I want to be able to say not only that I understand the theory, but that I can put code on paper to describe the processes and show that I understand the way these systems work together on a more holistic level.

The code for my Audio and Screen app are linked below for viewing.

MainActivity Class
Audio Class
SurfaceView Class

Thursday, 27 August 2015

Return to Game Development

Recently I have moved away from the Udacity course and tried to get back on track with the game development that I have wanted to do all along. I have returned my studies to Beginning Android Games, an Apress book I got a while back. When I first started trying to learn from this book I found the information to be far too heavy, I was not experienced enough with the Android OS to get it. Now that I have a better understanding, the pieces are coming together much easier.

While working through the examples, I have been playing around with the code and finding out the OTHER methods that some of the classes do. While I had made a game on Android following a "For Dummies" book in the past, this time I actually understand the process, the effect that the Activity Life Cycle has, and can see where the ideas I have fit into the code.

To help me keep notes and have an "in my own words" reference, I have been typing up  notes into Google Keep, an app I have had on my phone for a long time and rarely used. Being able to type quickly has always prevented me from note-taking on my phone. I am a terrible touch screen typist! Using the in-browser version of Google Keep has been a lifesaver- actual keyboard typing, and sync to my phone for on the go note revision. I have found myself memorizing key concepts quicker with these notes, and can now comfortably say that an extremely basic framework in a regular View can flow pretty quickly from my fingers. I do enjoy making notes and even updating them to make them more precise, but I can't always be at my laptop- for this reason I have contemplated buying a bluetooth for a while. (I have planned to buy a tablet for myself for quite a while now and really wanted a keyboard for it- so I have been watching Amazon and Bestbuy for a deal daily!) I finally ordered myself a keyboard last night, and hopefully that gives me more opportunities to be productive- either in writing up ideas, taking notes or coding when I am not limited by the amount of time I can comfortably sit at the computer.

As an example of the notes I have been keeping, here is my first entry!


Soundpool is a RAM based storage for small soundFX files, ideally in .ogg format and shorter than about 5 seconds. Setting up a SoundPool requires the parameters indicating how many sounds can play simultaneously (20 is a good default), which sound stream is being used (AudioManager.STREAM_MUSIC for media of any type), and a final unused parameter, default 0.

SoundPool sp = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
The SoundPool default constructor has been deprecated with the release of Lollipop, and now utilises a Builder for instantiating a SoundPool object.

SoundPool sp = SoundPool.Builder()  
.setUsage(audioAttributes)  
.setStream()  
.build();

 To load a soundFX file to the Pool, you have to get an AssetFileDescriptor from the Asset file.

AssetManager assetManager = context.getAssets();
AssetFileDescriptor asset1 = assetManager.openFD("dir/filename.extension");

When adding the descriptor to the soundpool, it will return an integer which identifies the sound loaded, which can be used as a parameter later. It is vital therefore that any files loaded be done so in an integer expression. the load method itself will take in the AssetFileDescriptor and a sound priority int as parameters. The sound priority is currently unused as is default as 1 (similar I guess to the weight attribute in xml layouts, having them all at 1 gives uniform importance).

int asset1IdNum = sp.load(asset1, 1);

This asset can later be played using the SoundPool instance, by referencing the identifier for the resource, as well as some other parameters.

sp.play(identifierInt, float leftChannelVolume, float rightChannelVolume, int priority, int looping, float playbackSpeed)

The channelVolume parameters allow a sound to be set on one ear or the other. The priority again is unused and is defaulted to 0. Looping is often not a good idea for a sound effect and is thus set to 0, and playback speed will be 1 by default, less for slow play and more for fast playback.
When all use of the SoundPool is done, it is best practice to release the resources directly by using either specific calls to soundPool.unload(identifierInt) or to all resources using soundPool.release();


I have made notes on MusicStream, working with the View and onDraw() method (invalidating as a method of continuous graphics rendering), setting the application to keep the screen on, go fullscreen and hide the notification bar and working in SurfaceView and Threads.

I'm hoping that my notes will not only enable me to retain information better, but also that they may help me to guide others if they ask me for advice on starting on a similar path!

There are notes I have to include after todays coding to describe how to set a listener for loading files, as I wanted to have a specific sound effect play as my testing app opens (computer booting up sound effect from a monster catching game you may have heard of!)

Sunday, 28 June 2015

A bit of background

Self learning ain't easy

Being a self taught programmer and game designer is definitely not going to be easy, I am already finding the task of finding good material to learn from to be a problem. Often when I am finished with one resource, the next either assumes a greater level of knowledge or falls back to basics.

My main resources for learning Java have so far been:
  • Codecademy: My first look at coding was the Javascript track which I began playing with just from curiosity. While this is not the best track to learn programming, at the time this was the only one available. Ruby and Python came later with redesigned tracks to support the programming route as a whole.
  • CS106A Stanford Programming Methodology: Lectures by Professor Mehran Sahami
    This series of lectures is available on Youtube and has assignment material available via the Stanford website. This course first introduced me to Java with Karel, the little robot.
  • Java - An introduction to Problem Solving and Programming: Walter Savitch (5th Edition)
    This textbook was donated to me by a work colleague who had taken the course as part of her university education but had no interest in pursuing it further. The book helped me to move away from the safe environment of Stanford's custom Java work space and onto making my own applications within Eclipse. I am currently using Eclipse Luna version 4.4.1
  • TheCherno: Youtube Game Programming series
    This series was a love/hate one, I enjoyed the coding and following along with a project and being able to tinker was very fun, but I think while the aim was for newer programmers to use this series as an introduction to game programming, it sometimes left me wondering what the heck I was doing. I stopped following this series after about 60 episodes but it definitely contributed to inspiring my continuation of studies.
  • After a period of stagnation and loss of direction, I finally found Head First Java, which took a couple of attempts for me to work with. At first I found the quirky sense of humor to be annoying and tired of it. It took another couple of months before I gave it another try (following some reddit advice) and got through my brick wall.

Recently my studies in Java and Android have also been accompanied by a read through of Fundamentals of Game Design by Ernest Adams. Reading this has helped me to pin down the vocabulary I need for my designs and also given me new ways to examine the games I draw inspiration from. So far I'm into the third chapter. I plan to give the book a good read through and then return to it when I put my ideas down to make sure I am doing what I need in an industry standard way.

The game I am working on designing and coding is an economic simulation in a food service setting. My ideas have been littered around my apartment in different forms without any direction, but the book is helping me to organize my approach. It's still important to write down or doodle my ideas, but I am now trying to keep the wild "this feature would be amazing!" type ideas from taking up too much time. Once I have a working prototype and my core mechanics working properly, then the features will be tested and discarded or developed as necessary.

I have also been looking into keeping an offline private wiki as a means to keep all ideas and documents I write accessible from one place. For this I have started learning to use a program called Wikidpad. With such little organization so far, there's not much to put into a wiki but as I bring my design ideas together and throw away the garbage, I intend to post snippets of wiki pages for people to read here too.

Simulations

My main interest is in simulations, and as I have gained new skills I have done my best to create small scenarios in code that behave in ways typical of simulations. For instance, once I learned about ArrayList and the QueueBlocking Arrays, I put together a background service in the mini restaurant testing program I have to create parties of guests at random intervals, assigning them to different Queues based on the size of the party, and limiting the combined total number of queueing parties. When a "table" became available, the service (nicknamed the Hostess) would assign an appropriate sized party to the empty table and free up a space in the queue.

More recently, while learning about serialization techniques, I created a mini simulation based on the classic fantasy triangle of damage. Warrior > Ranger > Magic User > Warrior. This is a common strengths/weakness model, most notably for me found in Runescape. The simulation pitted armies of each type into a war where each of the three types is randomly paired into a skirmish with a member of one of the other armies. Their fight gave an outcome and eventually all members of an army died and the results were saved out to a text file.

An example of the output is shown to the right, of a battle between 50 "mobs" per army. It was very fun to tweak some of the stats I had given each class to see how the outcome was affected. Getting the numbers to become pretty fair was surprisingly sensitive, as even a slight increase or decrease to a stat sometimes swung the outcome a completely different direction.

This type of simulation taught me a lot about how to work with arrays and random number generation. Having to check the arrays for "dead" mobs and delete them, creating damage and damage absorption that is calculated on the fly in each skirmish and even adding in a dodge and accuracy stat really mixed up the outcomes.

Starting simulation: Number of Combatants per army = 500
Ending simulation: Number of Skirmishes = 2806
Time taken: 0.279sec


Moving forward

My intention with this blog is to create a place for new programmers to look to see my trials and tribulations. If anyone can gather any knowledge, resources or inspiration from me then this blog will have served a purpose. For my own needs, I want to use this as a place to summarize my studies, hold myself accountable, and also to see where I was at a particular stage of my journey. Please feel free to get in touch if you have any questions or comments. Thanks for reading!

Saturday, 22 November 2014

Github, the Git and The Table State

At the suggestion of a guest at my own place of work, I got myself looking at Git this week. While I admit so far I have been using it as a GUI based, upload my work when I fancy it machine with no branches, I do plan to make fuller use of it soon. While in the super early stages of my concept, I have no need of branches as I am literally treating my gamedev environment as a bouncy house for programming. I'm having fun creating and solving problems and the future is still hazy as to the end product. While I would love for the program to be a success, I have not given myself any promises that this will be a masterpiece. Should my interest head in a different direction based on what I learn during the course of this work, I'm happy to let it go and move on.

While unfinished work is probably the biggest time waste for many programmers, I have taken the view that any time spent working on my project is constructive. Any ideas that make it into the program are successes and the failed ones are lessons.

So, this week I have been working a lot IRL so my time has been spent planning the Table Service aspect of my game. Working with time in Java was an initial hurdle but didn't require too much googling to ensure I was getting the numbers I needed in the format that worked for me. Each guest will be able to generate a set of times which state how long an aspect of their stay will take. John might take two minutes to eat, but Sally might take twenty five. Using this knowledge, the game is able to check for an "all ready" like state, by comparing the state of each guest and acting when all of them match. Using this system requires a set of enum types for the Guest and also for the Table to use as state markers which can be looked at by the other Entities. States in this way happen to be far more effective for the long list of possible states than boolean values had been, as rather than turning one value to true and another to false, the overall state simply switches. This makes a list of instructions much more safe to run as the state can only be one at a time, and no accidentally crosslined booleans will throw me off.


 if(!isActive){  
return;
}
elapsedTime = timeSat + System.currentTimeMillis();

if(state == guestState.sat){
if(startOrderTimer <= 0) startOrderTimer = System.currentTimeMillis();
if(startDrinkOrderTimer <= 0){
startDrinkOrderTimer = System.currentTimeMillis();
}
if(System.currentTimeMillis() - startDrinkOrderTimer > drinkOrderTime){
state = guestState.drinkOrderReady;
}
} else {
return;
}

if(state == guestState.drinkOrderReady){
// when Orders system implemented, fill in order creation here
}


if(state == guestState.drinkOrderTaken){
if(startOrderTimer <= 0){
startOrderTimer = System.currentTimeMillis();
}
if(System.currentTimeMillis() - startOrderTimer >= orderTime){
state = guestState.foodOrderReady;
}
}
In this early example of a guests update method you can see that the state is modified when criteria are met such as an elapsed time and manage progression through a typical service by acting as flags that the table can look for in each guest to create a Task that can then be acted upon by a Staff entity.

The table itself is able to scan through any number of occupying guests in order to check that all guests are in the same state, as shown here.
 private void getGuestStates() {  
if(guests[0].getState() == guestState.sat){
return;
}
Guest.guestState[] states = new Guest.guestState[guests.length];
for (int i = 0; i < guests.length; i++) {
states[i] = guests[i].getState();
}

Guest.guestState temp1 = guests[0].getState();
for (Guest.guestState state : states) {
Guest.guestState temp = state;
if (temp1 == temp) {
temp1 = temp;
} else {
return;
}

System.out.println("Table has determined that all guests' states match: " + state);
}
}
The initial state of guestState.sat will progress from within the Guest so if this state is in place then we save cpu time by exiting the getGuestStates() method. Checking against a fixed array index guests[0] is not a problem as a guests array is not able to have fewer than 1 entry, as 1 is the minimum number of guests in a group (which seems redundant to have a group of 1, but this is simply a container for the guests to proceed into the restaurant queuing system).

Once the basic framework for the states is finished I will make all new table placeholder sprites to help show the state visually. This may be a layered approach using the base table and then an "items on table" type layer such as is used in RPGMaker, but that will come in its own time. I have 3 days booked off this coming week and hope to spend a good chunk of them coding. Until then!

Sunday, 16 November 2014

Mouse Input and UI Ideas

Today I managed to finish implementing a simple mouse tracker for my game. It takes the location of the mouse on the game window, applies the offset made by the "player" movement, and adjusts for the scale of the game (since the game is a small scale and scaled up into a larger window).

An issue I was having was that as the update method for each table is run at 60 Updates per second, the actions taken when the mouse is clicked were also happening 60 times. To avoid this I added a clickLock, which disables a table from being clicked again for a second. The update method then decreases the lock each cycle until it hits zero.

           if(Mouse.getButton() == 1 && clickLock <= 0){  
if(Mouse.getX() + Screen.getxOffset() >= x
&& Mouse.getX() + Screen.getxOffset() < x + sprite.SIZE
&& Mouse.getY() + Screen.getyOffset() >= y
&& Mouse.getY() + Screen.getyOffset() < y + sprite.SIZE){
timer += 300;
clickLock += 60;
}
}

This snippet is my way of debug adding a state change to the table that is clicked. At the moment the tables update based on an increment per update and switched based on time passed in this manner. In future the tables cycle will update state based on the time and the personal preferences of the guests.
Each guest will be created with a set of randomly generated times such as how long it takes them to make an order, to eat and any "sitting and chilling" time after the service ends. These numbers will create some variation between tables as they will not all sit and end in a predictable pattern. If your group consists of two guests and one takes longer to order, they will both have to wait for an order to be placed. If you have a table of four people and they all decide quickly, the amount of time before an order can be made could be much shorter. In many games based on "cafe" or "restaurant" settings, the guests are very copy paste and fall into guest "types". I would rather have a guest be defined by their own set of preferences and also variables such as cash on hand and time available. A guest who is trying to get a quick bite should be seen to be ordering, eating and leaving quicker than a guest who is in for a social meal.

My noteboook, ideas on UI and button themes
My first notebook page was taken up by some brief ideas on how to add buttons to my UI. I had been playing around with MouseListener and when I hit a bump (NOO! Don't run that code nine thousand times a second!) I took some time off to doodle down some ideas. I hadn't given much thought to the buttons layout yet since I started this project off wanting to make an android app with touch controls (and notably smaller screen space for UI). When I began to narrow down what my influences for the game were, I thought about the way those games handled buttons. The left column of my notes tackle how I can keep a status bar accessible at all times for the player to see general information. Things like a clock and a rating, a countdown timer for timed goals, maybe even an income target and percentage to target bar. While some information is useful in all views, I had the idea that it could present slightly tailored information depending on the object or actor in focus. For example, if I click a manager, or a bartender, or a guest I should see different information that relates to their role and state. If i have nothing selected, a rating bar could show my overall rating, for a waiter, their individual performance rating for the day/week/month, and for a guest perhaps a rating on their experience so far.

Keeping this information in the lower left will keep it away from the main action in center screen but not out of the way enough to be a hindrance to glance at. Keeping status related, non-interactive information at the base of the screen should be natural for many users, while any modifiable or quick changing status on the upper portion of the screen.

The right side of the page was a few ideas I had about button types(management, lists, menu edits etc), while the next doodle was an idea I had about using Aura Buttons such as in World of Warcraft and other RPG games to switch between styles of play. For example a moving around mode, an inspection and statistics mode or simply a way to switch between controls relating to staff, management and logistics. This may add a way to switch input without having to find and select certain actor types, and instead control the game as a whole. An example of this could be that in "waiter" mode, you are able to click on flagged tables and service stations to prompt a staff member to act sooner on that task, while in management mode you are able to dish out morale or efficiency buffs to staff and boost the happiness of a group of guests with some fun product knowledge.

Thursday, 13 November 2014

Thinking about input

I've been thinking about input a lot lately as I definitely want to be able to be flexible in my controls. The use of the traditional WASD keys for movement is always going to be a feature when in control of a game avatar, but I would like to have Mouse input form a large part of the core game play too. While the game will be a simulator, I will create opportunities for the player to have direct influence such as placing objects in the environment, selecting other avatars, highlighting objects for inspection etc.

My game design is based on creating a world as interactive as Rollercoaster Tycoon was, with access to menus to control prices, individual guest dialogs, construction and also access to things like staff lists and skills. The restaurant world is not necessarily a fun environment that people aspire to be a part of from afar, in all fairness it is a stressful and tiresome, but managing one and having influence on design, staffing and item names etc will make the experience more engaging.

While the player controlled aspects of the game will ultimately be on the simpler, more holistic side, I would like to have a much beefier simulation running under the hood that advanced players can tap into at will, without having it interfere too much with the core gameplay. The game will hopefully be a good blend of time-management style point and click gameplay, with a rich economic engine that doesn't bog it all down. I have picked up a small notebook for writing down ideas on the go, whenever possible I will try to add pagescans so that you can see my thought processes and doodles!

Tuesday, 11 November 2014

Implementing graphics

Working on my Sim tonight has been a trial. The graphics setup that I have been using is heavily based on the Game Programming videos by TheCherno on You tube. Up until now I have been able to add graphics for the Tables in my gym using a simple render method, but tonight I set out to add a background array of tiles to represent the ground and walls. At first I wanted to figure some of it out on my own based on the memory of implementing this method previously. It turns out I wasn't as prepared to work through the code as I'd like. Revisiting the video tutorials I started to write down and analyze the code a little better. Working out the way that each design decision fed into another, I was able (with a little tweaking) to get my code running and bring up a simple grid of tiles.

The next step involved creating a "map" from pixels, where the colors represented tiles of different types that the program could read in and create the full map from. Using hexadecimal colors and a small (64px X 64px) "map", I was able to feed this into the level loader and move around the screen with the avatar. Lining my tables up was a second issue which meant I had to rethink and refactor my code to take the tables from an Array and build an Arraylist instead. Once the level loader read my map and encountered a "table" tile, it added a new Table instance to my ArrayList and set its x and y variables to match the tile.

Here the dark lines represent walls and the orange pixels are Tables

The next task will be to work on collision so that solid objects will be impassable. I will later add features for the sprites so that the level loader will determine if a table has adjacent tables and extending the length and capacity of the table accordingly. This will also involve some new sprites and logic to determine orientation, waiter interaction points etc. Once I get around to AI, I hope that the tile grid based system will work in my favor!

I imagine that in the final version of this program, the levels will be generated and packed before release rather than having the program read from the image files. Perhaps creating the initialized level and serializing it so that it can be read into memory, preventing tampering. If my final implementation also includes using a bitmap style mapping system, it may open up the door for creating my own modding tools or level editor, placing walls, computers, tables and other features that are checked by the program for compatibility against a set of game rules.

Larger level with Waiter star icon as placeholder. All tables occupied by debug mode options

Smaller level with pixel map overlay. Green pixel represents the Waiter starting position

Wednesday, 5 November 2014

Helping the binman out

Tonight ive been reading up on something that struck me while i was pondering the options I have for storing game data. If I create a new guest object at regular intervals, how do I make sure they arent sticking around, especially if I intend to simulate large numbers with any combination of ai activities.
Luckily there are some great summaries of the Java garbage collector that didnt get too science heavy for me. When a reference to a variable is lost, either through scope, reassignment or to lack of use, Java checks the programs memory for any variables or methods that may still have access to that memory address. Those suffering from abandonment are removed from memory by a low priority thread in the jvm. My problem was then, are my guests being deleted when they leave or were they living on. In order to figure it out I had to have my guest class increment a static counter each time its Constructor was called, and my Hostess class keep a tab on the number of guests at active tables. The first revelation found was that the hostess was creating groups even when the queue was full, and discarding them when they were rejected. While this wouldnt have been a huge memory problem, it was a simple fix to ensure the groupGenerator was not called unless the queue had room for more groups. After that I went about cutting ties to any groups that were done eating and had 'paid'. To do this I created a method in the Guest class to null any modified variables. This method was probably overkill! After any guests were gutted, the Group itself breaks ties with the Guest array, and the table breaks ties with the Group by disbanding. While any performance changes are probably negligible, it was good to think about the data being stored and how I want any large objects to kill their data before disconnecting from use in the game.
Today I also began sketching out a plan for the task system and how it could be implemented. Using tasks and a queue will allow me to break ai into much smaller chunks and simply list the steps needed to complete a task. It also allows me the future ability to add task transfer from one ai to another, effectively creating a means for waiters to really communicate and help each other out. I want to really have a good plan laid out before any of that system goes into the code though, id rather get the head scratching done before than during!

Monday, 3 November 2014

Working with the Hostess, queues and delta time

So ive got a small gym running for my program, a set of tables with placeholder art to show states and a non-viewable 'hostess' controller.
The hostess consists of a set of queues, which are offered a group of random guest size at random intervals. The hostess offers the group to a queue of matching description (those waiting for a table of 3 go into the queue for 3's and 4's) etc, using a best fit approach.
While the tables dont show any difference for max seating yet, eventually i will create different sprites for tables of various sizes and shapes.
Implementing the "arrival" of guests could lead to a more detailed look at the state of the performance, time of day and use of marketing strategies. Looking back at rct and its publicity options for gaining more guests, i may be able to add these kinds of features later on once the core gameplay is set.
At the moment the Hostess class is not intended to be a child of Staff, and is instead simply a controller of the flow of guests. If i later decide to have the option of a graphic representation, i would be able to give it a limited set of information and control to simulate human behaviour. (For instance, StaffHostess could have only limited view of the tables availability, and have to check around regularly to find which tables are taken.)
The Table class is currently maintaining itself by running update and incrementig a counter variable if the table isOccupied. Future implementations will take into account timed intervals for each state based on the guests and check against delta time for a change. (For instance, 4 guests will finish 2 shared meals quicker than 2 guests habing a meal each.)
My next step is to add StaffWaiter and a Computer to take orders and deliver Consumables to the table.

4/8 Tables Sat in various states

Tuesday, 13 May 2014

Design Concept Notebook

This is my first post to document my game design and development for the Restaurant Simulation.

After reading an interesting post via reddit recently, i started defining my game concept in terms of its main mechanic, secondary mechanics and the progression which will dictate my games direction. Thinking about my game idea in this way helped me to understand where I needed to concentrate in order to make an experience fun and engaging. As a simulation, I originally wanted the program to not even be about fun, but rather a realistic representation of a restaurant. An exercise in designing and implementing an eco-system, where input is random but the outputs represent the realities of a small business.

The future may lead to me implementing more features from this original vein, but narrowing the scope is for now a better route for me to see through and finish the project.

Today I have been working on writing up a description of the main view, what a "level" should look like and what is interactive. The game will be at first a player directed "time management" style game. Think Diner Dash or Barrr. As I learn more about programming I'd like to be able to implement an automatic mode where the agents are able to act independently, allowing the player to switch between agents.

I'll be working on my own art for the game so I've been doodling little sketches, which help me to think about the way I want to implement things such as menus, game state indicators and of course the layout and style of art.

Next step, continue learning from the Cherno and get a Level up and running, and put some alpha art tiles in this blog!