Simple Update loop to show questions one at a time

Someone asked on Game Development:

I have two lists which work with an XML file which holds questions and answers. At the moment the project displays all the questions at the same time so they “flicker” on the screen and iterate between each item in the list.

Whats the easiest way (coding) to pause the random generated list on any particular questions?

Question class:

class question
{
    public string questionString;
    public string apple;
    public string pear;
    public string orange;

    //the ? indicate the int can be nullable so it can accept the string item
    int? correctAnswer;

    public question(string newquestionString)
    {
        parseQuestion(newquestionString);
    }

    public void parseQuestion(string newquestionString)
    {
        List<string> questionComponents = newquestionString.Split('|').ToList<string>();

        questionString = questionComponents[0];
        apple = questionComponents[1];
        pear = questionComponents[2];
        orange = questionComponents[3];

        correctAnswer = Int32.Parse(questionComponents[4]);

    }

In Game1:

    Random q = new Random();
    int i = q.Next(questions.Count);



    spriteBatch.Begin();
    spriteBatch.DrawString(myfont, questions[i], new Vector2(100 + 100 *i, 100), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].questionString, new Vector2(100 + 100, 100), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].apple, new Vector2(100 + 100, 200), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].orange, new Vector2(100 + 100, 300), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].pear, new Vector2(100 + 100, 400), Color.Black);
    spriteBatch.End();

I posted the following answer, which was chosen as the accepted answer and received 3 upvotes:

Does the code labeled “Game1” occur in the Draw(GameTime gameTime) method? If so, the problem looks as though you draw a different question each frame not that you need to draw slower. If you draw the same thing every frame, there should be no flicker; I would adjust the code like this:

// private class level variable
int currentQuestion = 0;


// in the Update(GameTime gameTime) method
if(userChoseAnswer) // check input and see if you should advance to the next question
{
    Random q = new Random();
    // might want to add code here to avoid showing 
    // questions already shown? unless that wont help your game
    currentQuestion = q.Next(questions.Count);  
}


// in the Draw(GameTime gameTime) method
spriteBatch.Begin();
spriteBatch.DrawString(myfont, questions[currentQuestion], new Vector2(100 + 100 *i, 100), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].questionString, new Vector2(100 + 100, 100), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].apple, new Vector2(100 + 100, 200), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].orange, new Vector2(100 + 100, 300), Color.Black);
spriteBatch.DrawString(myfont, myQuestions[currentQuestion].pear, new Vector2(100 + 100, 400), Color.Black);
spriteBatch.End();
Notable comments

Nate (0 upvotes): @Roy a good point on keypress.


Originally posted on Game Development — 3 upvotes (accepted answer). Licensed under CC BY-SA.

serial port added in one form not accessible from another class vb.net

Someone asked on Stack Overflow:

I added a serial port com1 to my vb.net form. I created a new class and wrote a method to open the com1 and created its object in the main form and called the method and its opening.

THen i created another class wrote a method to write data to the com and same way created an object and called it but i am getting the error as port is closed. What am i doing wrong.

To open the port

public class openport public sub opencom mainform.com1.open end sub end class

//in the mian form

dim cc as openport

cc.opencom

‘The above stuff works

But when i do same thing in another class for writing using

mainform.com1.write(data)

i am getting an error as port closed.

I posted the following answer, which was chosen as the accepted answer and received 1 upvote:

It looks like you are defining one comport, then opening a different one. Check that, if you still have issues post your complete code.

'Form1
public SP as SerialPort;
' Form1 Load Event
SP = New SerialPort("COM##", ...)
' Form1 Loads New Form
dim newForm as New Form2()
newForm.OldForm = Me
newForm.Show();

'Form2
public OldForm as Form1
'Form2 Minipulate COM port
OldForm.SP.Write(data) 
Notable comments

Nate (0 upvotes): I don’t understand the problem.. can you be more specific?


Originally posted on Stack Overflow — 1 upvotes (accepted answer). Licensed under CC BY-SA.

XNA GameTime before first Update

Someone asked on Game Development:

Using XNA, is it possible to access the GameTime object before Update is called for the first time?

Can it be used in the game constructor, Initialize or LoadContent methods?

I posted the following answer, which was chosen as the accepted answer and received 5 upvotes:

I don’t believe this is possible:

The GameTime object received by Draw and Update isn’t technically owned by anyone, but is instead re-created each Game.Tick and passed to Update and Draw from there.

Internally, Tick fills the value of the Total/ElapsedRealTime properties based off of the current high performance counter value as reported by Stopwatch.GetTimestamp(). If the PC the program is running on does not have a high performance counter, then it returns DateTime.Now.Ticks.

The Game Time properties (as opposed to real-time) also use the Stopwatch.GetTimestamp, however elapsed time since application launch and last frame are computed internally and then filled in before GameTime is passed to Draw or Update - so there’s no external way to compute those values directly.

Source: http://forums.create.msdn.com/forums/t/10587.aspx, bold mine. Also included there are several work arounds, similar to what you’ve already outlined though.

Notable comments

Nate (0 upvotes): Yes, that is likely, but it still doesn’t remove having a line in the Update method which passes gameTime somewhere else.


Originally posted on Game Development — 5 upvotes (accepted answer). Licensed under CC BY-SA.

&quot;Delete Files Older Than&quot; Batch Script

Someone asked on Server Fault:

So in the work of doing backups, I need a batch script that would allow me to delete files in a specified directory, that are older than lets say, 3 days. This script will be set as a scheduled task to run at a specified time every day.

I posted the following answer, which was chosen as the accepted answer and received 8 upvotes:

If powershell is acceptable (should be, as its enabled by default on Server 2008+) try this:

$numberOfDays = 3
$Now = Get-Date
$TargetFolder = "C:\myoldfiles"
$LastWrite = $Now.AddDays(-$numberOfDays)
$Files = get-childitem $TargetFolder -include *.bak, *.x86 -recurse | Where {$_.LastWriteTime -le "$LastWrite"} 

foreach ($File in $Files)
{
    write-host "Deleting File $File" -foregroundcolor "Red";
    Remove-Item $File | out-null
} 

Souce here.


Originally posted on Server Fault — 8 upvotes (accepted answer). Licensed under CC BY-SA.

Figuring out what&#39;s causing a server to slow down

Someone asked on Server Fault:

I have a potential client that has a php site that performs fine most of the time. However, every week or so, it will experience lag (slow page loading). I am sure there are a myriad of things that can be causing this (network issues, bad installation, a specific php file, increased traffic load). However, I need a way to deduce what is causing this. Is there any server monitoring software that is made especially to handle these situations?

PS: The server is linux

I posted the following answer, which was chosen as the accepted answer and received 3 upvotes:

I would find out the following:

  • Does this “slow down” effect all users?
  • Is this slow down for the entire site, or just a specific set of functions within the site?
  • Does it happen at the same time every day and the same day each week?

If the slowdown is always on Friday at quitting time and the application is used for users to enter their time card data for the week, it might simply be the server needs more CPU/Memory and or Bandwidth to take the load of all the last-minute users. Suffice it to say, those type of patterns will be hard to track down without knowing the ins and outs of the application and its users and uses.

In order to recommend tools, we’d need to know what OS your app is running on? Windows/IIS, Linux/Apache? However, in my anecdotal experience, site slowdown is caused by one of a few things:

  • Poor database programming
    • SELECT * FROM TableXYZ
    • Queries to un-indexed columns
  • Server Issues
    • Not enough memory
    • Not enough bandwidth
      • Server —> User
      • Server —> Database

The most common things to check (for performance related problems) are

  • Database Server
    • CPU Load
    • Available Memory
    • Disk Queue Length (is your disk IO maxed out?
  • Web Server
    • CPU Load
    • Memory Usage
    • Bandwidth to end users
    • Bandwidth to database server
Notable comments

Nate (1 upvotes): Have you been through this thread for Linux Performance monitoring tools: serverfault.com/questions/74863/…


Originally posted on Server Fault — 3 upvotes (accepted answer). Licensed under CC BY-SA.

How detailed and/or complete is/are your game design documents before starting a project?

I asked this on Game Development:

What I’m wondering is how complete your design documents typically are before beginning the implementation of a project? I’m talking about medium to very small projects with a very small team here where even fully fleshed out the entire document may only be a few dozen pages.

Do you start with a rough framework and start fleshing out the details at the same time implementation is starting?

Do you completely flesh out every section completely before any implementation is even started? If so, what percentage change have you seen after implementation starts?

If you have experience with one of the two scenarios I outlined, I’d love to hear your opinion on what issues going that particular route caused and what obstacles you feel it helped you avoid.


Vasiliy Sharapov answered (7 upvotes):

If the game idea is heavily based on some unusual gameplay concept, I prototype that right away from scratch, using a previous project as a template. 95% of the time this leads to realizing that it’s not as fun as I imagined, and to make it fun would require more resources than it’s worth.

If I’m working on another project in the meantime, I take my time, make a doodle to get an idea of what the prototype should look like (try not to get distracted by sketch art). Then I share it with friends, partly to see if they have any input, but mostly to make myself think of things that are not obvious right away (there are always tonnes of things, even for the smartest people thinking out the simplest ideas). After a couple hours like this, I’ll jot down some key concepts that have to be in the architecture, literally ~20 words. Then I can build a prototype when I have time.

Notable comments

Leniency (5 upvotes): Design documents? What are those? ;-)


Originally posted on Game Development — 12 upvotes. Licensed under CC BY-SA.

C# Serialize a class with a List data member

Someone asked on Stack Overflow:

I have this c# class:

public class Test
{
    public Test() { }

    public IList<int> list = new List<int>();
}

Then I have this code:

        Test t = new Test();
        t.list.Add(1);
        t.list.Add(2);

        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
        StringWriter sw = new StringWriter();
        XmlSerializer xml = new XmlSerializer(t.GetType());
        xml.Serialize(sw, t);

When I look at the output from sw, its this:

<?xml version="1.0" encoding="utf-16"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

the values 1,2 I added to the list member variable dont show up.

  1. So how can I fix this ? I made the list a property but it still doesnt seem to work.
  2. I am using xml serialization here, are there any other serializers ?
  3. I want performance! Is this the best approach ?

--------------- UPDATE BELOW -------------------------

So the actual class I want to serialize is this:

public class RoutingResult
    {
        public float lengthInMeters { get; set; }
        public float durationInSeconds { get; set; }

        public string Name { get; set; }

        public double travelTime
        {
            get
            {
                TimeSpan timeSpan = TimeSpan.FromSeconds(durationInSeconds);
                return timeSpan.TotalMinutes;
            }
        }

        public float totalWalkingDistance
        {
            get
            {
                float totalWalkingLengthInMeters = 0;
                foreach (RoutingLeg leg in Legs)
                {
                    if (leg.type == RoutingLeg.TransportType.Walk)
                    {
                        totalWalkingLengthInMeters += leg.lengthInMeters;
                    }
                }

                return (float)(totalWalkingLengthInMeters / 1000);
            }
        }

        public IList<RoutingLeg> Legs { get; set; } // this is a property! isnit it?
        public IList<int> test{get;set;} // test ...

        public RoutingResult()
        {
            Legs = new List<RoutingLeg>();
            test = new List<int>(); //test
            test.Add(1);
            test.Add(2);
            Name = new Random().Next().ToString(); // for test
        }
    }

But the XML produced by the serializer is this:

<RoutingResult>
  <lengthInMeters>9800.118</lengthInMeters>
  <durationInSeconds>1440</durationInSeconds>
  <Name>630104750</Name>
</RoutingResult>

???

its ignoring both of those lists ?

I posted the following answer, which was chosen as the accepted answer and received 4 upvotes:

1) Your list is a field, not a property, and the XmlSerializer will only work with properties, try this:

public class Test
{    
    public Test() { IntList = new List<int>() }    
    public IList<int> IntList { get; set; }
}

2) There are other Serialiation options, Binary the main other one, though there is one for JSON as well.

3) Binary is probably the most performant way, since it is typically a straight memory dump, and the output file will be the smallest.


Originally posted on Stack Overflow — 4 upvotes (accepted answer). Licensed under CC BY-SA.

Sprite sheet or multiple resources

Someone asked on Game Development:

When animating for the Android platform is it a better practice to create a sprite sheet with multiple states for each sprite on a single picture or should I instead export individual images for each character/state/etc.? Which option gives me a smaller file size for resources and which is easier for the programmer to animate?

I posted the following answer, which was chosen as the accepted answer and received 4 upvotes:

It depends how many you have and how many of those would be in use at any given time.

I would break it down as follows:

For each “sprite” I would have one sheet, each WxH section is a single frame. If there are only a few states, I’d keep those all in the same image file, and just make a map of

  1. Walking is sprites 0-9
  2. Jumping is 10-15
  3. Crouching is 15-20

If you have many states per sprite, I would consider breaking up each state animation into its own file.

If you only have a few sprites and a few states, it might be best to simply have it all on a single image file, and use the maping I have above, but include it per sprite. This will keep the amount of memory usage to a minimum, since you’re targeting android, memory is a premium resource and should be conserved where possible.


Originally posted on Game Development — 4 upvotes (accepted answer). Licensed under CC BY-SA.

Multiplayer game with Cocos2d-Javascript and Node.js

Someone asked on Game Development:

It is possible to make a multiplayer browser based game using cocos2d-javascript + node.js? If so, is there any tutorial about that?

I posted the following answer, which was chosen as the accepted answer and received 2 upvotes:

I’d recommend you check into http://nodejs.org/ and https://github.com/joyent/node/wiki/ for information on what you can do with node.js.

cocos2d-javascript has a tutorials section on their website: http://cocos2d-javascript.org/tutorials/ which I recommend you start with.

Without significantly more detail, there isn’t much more I can recommend you look at.


Originally posted on Game Development — 2 upvotes (accepted answer). Licensed under CC BY-SA.

Making game constants/tables available to game logic classes/routines in a modular manner

Someone asked on Game Development:

Suppose I have a game where there are several predefined constants and charts (a XP chart, cost of goods and so on). Those could be defined at runtime, or load from files at start-up. The question is how should those logic routines access the constants and charts?

For example, I could try using global variables, but that cause all classes relying on the variables to be tightly coupled with them.

I posted the following answer, which was chosen as the accepted answer and received 3 upvotes:

It really depends upon what type (and quantity/size) of data you’re talking about. If it is a small bit of data that can be safely kept in memory for the duration of execution, something like a static class would be my recommendation.

public static class Constants
{
    public static int[] Levels = { 0, 100, 200, 400, 800, 1600, 3200, 6400 }
}

This way, the experience required to get to Level X is Constatns.Levels[X - 1]; and accessing other data is easy as well, if you need a collection of Items, you can add it here too, if your Items data is too large to store in memory, you can also implement caching logic within the static class.

Making it static keeps a single copy in memory, and ensures that every client of this class is getting the same data.

While this does “tightly couple” your classes together, tight coupling is not a bad thing if the design really needs it, which in the case of Item stats and XP charts, it is, IMHO, reasonable to tightly couple these. I always try to keep it simple, until something forces it to be complicated.


Originally posted on Game Development — 3 upvotes (accepted answer). Licensed under CC BY-SA.

signed letter b

Dad. Geek. Gamer. Software developer. Cloud user. Old Car enthusiast.  Blogger.


Top Posts


profile for Nate on Stack Exchange, a network of free, community-driven Q&A sites
a proud member of the blue team of 512KB club
Thoughts, opinions, and ideas shared here are my own. © 2026 Nate Bross.