Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.00 KB | None | 0 0
  1. using Microsoft.Xna.Framework;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5.  
  6. namespace TestGame
  7. {
  8.     public sealed class Npc
  9.     {
  10.         // FIFO collection for storing tasks.
  11.         public Queue<KeyValuePair<NpcTasks, object[]>> Tasks;
  12.  
  13.         private Vector2[] path;
  14.         private bool stopThread;
  15.         private Thread thread;  // Task update thread
  16.  
  17.         public Npc()
  18.         {
  19.             Tasks = new Queue<KeyValuePair<NpcTasks, object[]>>();
  20.             path = new Vector2[0];
  21.  
  22.             InitThread();
  23.         }
  24.  
  25.         public void Load()
  26.         {
  27.             if (thread.ThreadState == ThreadState.Running) throw new InvalidOperationException();
  28.             if (thread.ThreadState != ThreadState.Unstarted) InitThread();
  29.  
  30.             thread.Start();
  31.         }
  32.  
  33.         public void UnLoad()
  34.         {
  35.             stopThread = true; // Request a thread stop
  36.         }
  37.  
  38.         public void Update()
  39.         {
  40.             // gamelogic update
  41.         }
  42.  
  43.         private void InitThread()
  44.         {
  45.             // Set thread to its function
  46.             thread = new Thread(RunThread);
  47.         }
  48.  
  49.         private void RunThread()
  50.         {
  51.             // message loop
  52.             while (!stopThread)
  53.             {
  54.                 if (Tasks.Count > 0) TickThread();  // tick when task is available
  55.                 else Thread.Sleep(100);             // do nothing for 100 ms
  56.             }
  57.         }
  58.  
  59.         private void TickThread()
  60.         {
  61.             KeyValuePair<NpcTasks, object[]> task = Tasks.Dequeue();    // get current task.
  62.  
  63.             switch (task.Key)
  64.             {
  65.                 case NpcTasks.Walk:
  66.                     lock(path)      // lock path to prevent interthread exceptions
  67.                     {
  68.                         path = new Vector2[] { Vector2.Zero, Vector2.One };
  69.                     }
  70.                     break;
  71.             }
  72.         }
  73.     }
  74.  
  75.     public enum NpcTasks
  76.     {
  77.         Walk
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement