Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Threading;
- class Program
- {
- static void Main(string[] args)
- {
- var player1 = new Player("player 1");
- var player2 = new Player("player 2");
- var game = new Game1();
- var running = true;
- while (running)
- {
- game.Update();
- game.Draw();
- Thread.Sleep(100);
- }
- }
- }
- public class Game1
- {
- public delegate void UpdateDelegate();
- public delegate void DrawDelegate();
- public static event UpdateDelegate UpdateHandler;
- public static event DrawDelegate DrawHandler;
- public void Update()
- {
- //the ? is a null check
- UpdateHandler?.Invoke();
- }
- public void Draw()
- {
- DrawHandler?.Invoke();
- }
- }
- public abstract class Entity
- {
- // static fields
- public static List<Entity> entities = new List<Entity>();
- //static constructor, run before anything is instantiated
- static Entity()
- {
- //adding the update methods to the game events
- Game1.UpdateHandler += UpdateAll;
- Game1.DrawHandler += DrawAll;
- }
- // static methods
- public static void UpdateAll() // called from game1 event invocation
- {
- foreach (Entity entity in entities) entity.Update();
- }
- public static void DrawAll() // called from game1 event invocation
- {
- foreach (Entity entity in entities) entity.Draw();
- }
- // instance fields
- public string name;
- //public Vector3 position;
- //...
- //constructor
- public Entity()
- {
- Console.WriteLine("Entity " + name + " added to entities list");
- entities.Add(this);
- }
- //abstract intsance methods, these must be inherited
- public abstract void Update();
- public abstract void Draw();
- }
- public class Player : Entity
- {
- public Player(string name)
- {
- //base class is also run to add it to the entities list in the base class
- Console.WriteLine("new player:" + name);
- this.name = name;
- }
- public override void Update()
- {
- Console.WriteLine("update:" + name);
- //this is called via the Entity UpdateAll() static method
- }
- public override void Draw()
- {
- Console.WriteLine("draw: " + name);
- //this is called via the Entity UpdateAll() static method
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement