public void Run() { IEnumerable <Type> consoleTypes = PlugIns(typeof(IGameConsole)); IList <IGameConsole> games = consoleTypes.Select(st => (IGameConsole)Activator.CreateInstance(st)).ToList(); int menuChoice = -1; while (menuChoice != 0) { PrintHighScores(); Console.WriteLine("0 .. Quit"); Console.WriteLine("Or fancy playing one of these games?"); for (int i = 0; i < games.Count; i++) { Console.WriteLine("{0} .. {1}", i + 1, games[i].Name()); } bool numeric = Int32.TryParse(Console.ReadLine(), out menuChoice); if (numeric) { if (menuChoice <= games.Count && menuChoice > 0) { int indexOfGameInList = menuChoice - 1; IGameConsole console = games[indexOfGameInList]; int score = console.Run(); HighScore(console.Name(), score); } } } }
/// <summary> /// Gets the correct instance of the class implementing <see cref="IGameLogic"/> interface. /// </summary> /// <returns>The correct instance of the class implementing <see cref="IGameLogic"/> interface</returns> /// <param name="labyrinth">A non null value of <see cref="ILabyrinthPlayField"/></param> /// <param name="gameConsole">A non null value of <see cref="IGameConsole"/></param> /// <param name="resultsTable">A non null value of <see cref="IResultsTable"/></param> /// <param name="input">A non null value of <see cref="IUserInput"/></param> /// <param name="factory">A non null value of <see cref="IResultFactory"/></param> public IGameLogic GetIGameLogicInstance(ILabyrinthPlayField labyrinth, IGameConsole gameConsole, IResultsTable resultsTable, IUserInput input, IResultFactory factory) { if (labyrinth == null || gameConsole == null || resultsTable == null || input == null || factory == null) { throw new ArgumentNullException("GetGameLogic class in IFactory has some null arguments"); } return(new GameLogic(labyrinth, gameConsole, resultsTable, input, factory)); }
public static IGameConsole RerouteConsole() { if (GameConsoleWriter == null) { IGameConsole GameConsole = NativeInterface.Load <IGameConsole>("gameui.dll"); GameConsole.Activate(); Console.SetOut(GameConsoleWriter = new IGameConsoleTextWriter(GameConsole)); } return(GameConsoleWriter.GameConsole); }
/// <summary> /// Initializes a new instance of the <see cref="GameLogic"/> class /// </summary> /// <param name="labyrinth">Receives a non null <see cref="ILabyrinthPlayField"/></param> /// <param name="gameConsole">Receives a non null <see cref="IGameConsole"/></param> /// <param name="resultsTable">Receives a non null <see cref="IResultsTable"/></param> /// <param name="input">Receives a non null <see cref="IUserInput"/></param> /// <param name="factory">Receives a non null <see cref="IResultFactory"/></param> public GameLogic(ILabyrinthPlayField labyrinth, IGameConsole gameConsole, IResultsTable resultsTable, IUserInput input, IResultFactory factory) { if (labyrinth == null || gameConsole == null || resultsTable == null || input == null || factory == null) { throw new ArgumentNullException(); } this.labyrinth = labyrinth; this.gameConsole = gameConsole; this.resultsTable = resultsTable; this.input = input; this.Exit = false; this.factory = factory; this.movesCount = 0; this.isTopResult = false; }
/// <summary> /// Initializes a new instance of the <see cref="GameEngine"/> class /// </summary> /// <param name="width">Integer value for the width</param> /// <param name="height">Integer value for the height</param> /// <param name="factory">A non null instance of <see cref="IFactory"/></param> public GameEngine(int width, int height, IFactory factory) { if (width < 1) { throw new ArgumentException("The value of the width must be more than 0"); } if (height < 1) { throw new ArgumentException("The value of the height must be more than 0"); } if (factory == null) { throw new ArgumentNullException("The factory must not be null"); } this.windowWidth = width; this.windowHeight = height; this.factory = factory; this.input = this.factory.GetIUserInputInstance(); this.labyrinth = this.factory.GetILabyrinthPlayFieldInstance(factory, this.factory.GetIMoveHandlerInstance()); this.gameConsole = this.factory.GetIGameConsoleInstance(this.factory.GetILanguageStringsInstance()); this.resultsTable = this.factory.GetIResultsTableInstance(); this.resultsTable.Table.Changed += (sender, e) => { this.factory.GetFileSerializationManagerInstance().Serialize(sender); }; var fileAppender = this.factory.GetFileIAppenderInstance("Log.txt"); this.simpleLoggerFileAppender = this.factory.GetSimpleILoggerInstance(fileAppender); this.consoleGraphicFactory = this.factory.GetIConsoleGraphicFactoryInstance(); this.renderer = this.consoleGraphicFactory.GetConsoleRenderer(); this.scene = this.factory.GetISceneInstance(this.renderer); this.labyrinthGraphic = this.consoleGraphicFactory.GetLabyrinthConsoleGraphic(this.labyrinth, this.consoleGraphicFactory.GetCoordinates(2, 1), this.renderer); this.gameConsoleGraphic = this.consoleGraphicFactory.GetGameConsoleGraphic(this.gameConsole, this.consoleGraphicFactory.GetCoordinates(2, this.labyrinth.LabyrinthSize + 2), this.renderer); this.tableGraphic = this.consoleGraphicFactory.GetResultsTableConsoleGraphic(this.resultsTable, this.consoleGraphicFactory.GetCoordinates(2, 1), this.renderer); this.gameLogic = factory.GetIGameLogicInstance(this.labyrinth, this.gameConsole, this.resultsTable, this.input, this.factory); }
//The composition route for a console application static void Main(string[] args) { /* Issues with using an Ioc Container:- * .1) All dependancies need to be registered with the container * .2) Registered dependancies need to be released from the container * after use or memory problems could arise * .3) Threading issues can arise from life style choices * .4) Only use resolve in the composition root * .5) Compiler can't help with finding missing dependancies */ //Using an ioc var container = new UnityContainer(); //Creates a new instance of the game console each time is is resolved container.RegisterType <IGameConsole, SuperNes>(new TransientLifetimeManager()); container.RegisterType <IGame, SuperMarioWorld>(); container.RegisterType <IWeapon, Hammer>(); IGameConsole consolefromIoc = container.Resolve <IGameConsole>(); container.Dispose(); //Poor man's dependancy injection SuperNes superNes = new SuperNes( new ZeldaLinkToThePast(new Sword())); superNes.LoadGame(); //Trapped dependancy HandheldSingleGameConsole gameConsole = new HandheldSingleGameConsole(); gameConsole.LoadGame(); Console.ReadKey(); }
/// <summary>Creates a new target, logging to the console of the specified game, at the specified level.</summary> /// <param name="game">the game to create the console for.</param> /// <param name="level">the log level starting at which to output messages.</param> public GameConsoleTarget(Game game, LogLevel level) { _console = (IGameConsole)game.Services.GetService(typeof(IGameConsole)); if (_console == null) { throw new ArgumentException("Game does not have an IGameConsole service.", "game"); } // Set a nicer layout. Layout = new SimpleLayout("${date:format=yyyy-MM-dd HH\\:mm\\:ss} [${level:uppercase=true}] ${logger:shortName=true}: ${message}\n${exception:format=tostring}"); // Add as a target, or make it the default target if there are none. if (LogManager.Configuration != null) { LogManager.Configuration.AddTarget("GameConsole", this); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", level, this)); LogManager.Configuration.Reload(); } else { SimpleConfigurator.ConfigureForTargetLogging(this, level); } }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // Not initialized yet in constructor Game1.DefaultGraphicsDevice = GraphicsDevice; // global access to camera Game1.Camera = new Camera(); // console stuff GameConsole.Initialize(this, "Consolas", Color.Black, Color.White, 0.8f, 10); Game1.console = (IGameConsole)Services.GetService(typeof(IGameConsole)); // interpreter Game1.interpreter = new Interpreter(); Game1.interpreter.run("run startup"); /* * _testDialogue = new DialogueManager( * DefaultGraphicsDevice.Viewport.Width - 40, (DefaultGraphicsDevice.Viewport.Height / 4) - 20, * 20, 530); * _testDialogue.AddLines( * "To be, or not to be: that is the question: " + * "Whether 'tis nobler in the mind to suffer the slings and arrows of outrageous fortune, " + * "or to take arms against a sea of troubles, and by opposing end them? " + * "To die, to sleep; To sleep: perchance to dream: ay, there's the rub; " + * "For in that sleep of death what dreams may come when we have shuffled off this mortal coil, " + * "Must give us pause: there's the respect that makes calamity of so long life; " + * "For who would bear the whips and scorns of time, " * ); */ //add screens to screenManager Game1.screenManager.AddScreen("blank", new BlankScreen()); base.Initialize(); }
public override void Initialize() { // create our content manager content = new ContentManager(IService, "Content"); IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)IService.GetService(typeof(IGraphicsDeviceService)); GraphicsDevice graphicsDevice = graphicsDeviceService.GraphicsDevice; // create our spritebatch spriteBatch = new SpriteBatch(graphicsDevice); // get the game console console = (IGameConsole)IService.GetService(typeof(IGameConsole)); // get the audio manager audioManager = (IAudioManager)IService.GetService(typeof(IAudioManager)); // setup camera camera = new Camera(graphicsDevice.Viewport); camera.Limits = WorldUnitsToPixels(new RectangleF(-WorldSize / 2, -WorldSize / 2, WorldSize, WorldSize)); camera.LookAt(Vector2.Zero); graphicsDevice.DeviceReset += GraphicsDeviceReset; base.Initialize(); }
/// <summary> /// Initializes a new instance of the <see cref="GameConsoleConsoleGraphic"/> class. /// </summary> /// <param name="gameConsole">Game console for the graphic.</param> /// <param name="coords">Coordinates of the console.</param> /// <param name="renderer">Renderer for the console game.</param> public GameConsoleConsoleGraphic(IGameConsole gameConsole, IntPoint coords, IRenderer renderer) : this(gameConsole, coords, renderer, DefaultVisibleLinesCount) { }
/// <summary> /// Initializes a new instance of the <see cref="GameConsoleConsoleGraphic"/> class. /// </summary> /// <param name="gameConsole">Game console for the graphic.</param> /// <param name="coords">Coordinates of the console.</param> /// <param name="renderer">Renderer for the console game.</param> /// <param name="visibleLines">Visible lines of the game console.</param> public GameConsoleConsoleGraphic(IGameConsole gameConsole, IntPoint coords, IRenderer renderer, int visibleLines) : base(gameConsole, coords, renderer) { this.gameConsole = gameConsole; this.visibleLinesCount = visibleLines; }
public IGameConsoleTextWriter(IGameConsole console) { GameConsole = console; }
/// <summary> /// Updates any input to the console /// </summary> /// <param name="gameTime">The current game time</param> public override void Update(GameTime gameTime) { if (!isEnabled) { #if !XBOX //TODO: Needs refactoring IGameConsole console = (IGameConsole)Game.Services.GetService(typeof(IGameConsole)); if (!console.IsOpen && InputCore.IsNewKeyPress(Keys.OemTilde)) { console.Open(Keys.OemTilde); } #endif return; } mCurrentTime = gameTime; // handle cursor blinking mCursorTimer -= (float)gameTime.ElapsedGameTime.TotalSeconds; if (mCursorTimer <= 0) { mDrawCursor = !mDrawCursor; mCursorTimer = mCursorBlinkSpeed + mCursorTimer; } // handle notify blinking mNotifyTimer -= (float)gameTime.ElapsedGameTime.TotalSeconds; if (mNotifyTimer <= 0) { mDrawNotify = !mDrawNotify; mNotifyTimer = mNotifyBlinkSpeed + mNotifyTimer; } KeyboardState kb = Keyboard.GetState(); // Close the console if the close key was pressed //if ((kb[mCloseKey] == KeyState.Down) // && (mLastKeyboardState[mCloseKey] == KeyState.Up)) if (InputCore.IsNewKeyPress(mCloseKey)) { isEnabled = false; return; } // handle input cursor movement if cursor is enabled if (mCursorEnabled) { if ((kb[Keys.Left] == KeyState.Down) && (mLastKeyboardState[Keys.Left] == KeyState.Up)) { if (mInputPosition > 0) { mInputPosition--; } } if ((kb[Keys.Right] == KeyState.Down) && (mLastKeyboardState[Keys.Right] == KeyState.Up)) { if (mInputPosition < mCurrentText.Length) { mInputPosition++; } } } // handle paging up and down if ((kb[Keys.PageUp] == KeyState.Down) && (mLastKeyboardState[Keys.PageUp] == KeyState.Up)) { mCurrentLine = (int)MathHelper.Clamp(mCurrentLine - mVisibleLineCount, 0, mLog.Count - 1); } if ((kb[Keys.PageDown] == KeyState.Down) && (mLastKeyboardState[Keys.PageDown] == KeyState.Up)) { mCurrentLine = (int)MathHelper.Clamp(mCurrentLine + mVisibleLineCount, 0, mLog.Count - 1); } if ((kb[Keys.Up] == KeyState.Down) && (mLastKeyboardState[Keys.Up] == KeyState.Up)) { mCurrentLine = (int)MathHelper.Clamp(mCurrentLine - 1, 0, mLog.Count - 1); } if ((kb[Keys.Down] == KeyState.Down) && (mLastKeyboardState[Keys.Down] == KeyState.Up)) { mCurrentLine = (int)MathHelper.Clamp(mCurrentLine + 1, 0, mLog.Count - 1); } // Process each pressed key for a key down event foreach (Keys key in kb.GetPressedKeys()) { // if its a repeat key, skip it if (mLastKeyboardState[key] != KeyState.Up) { continue; } char ch = new char(); KeyModifier mod = KeyModifier.None; // check for shift modifiers if ((kb[Keys.LeftShift] == KeyState.Down) || (kb[Keys.RightShift] == KeyState.Down)) { mod = KeyModifier.Shift; } if (ConsoleKeyMap.GetCharacter(key, mod, ref ch)) { mCurrentText.Insert(mInputPosition, new char[] { ch }); mInputPosition++; } } // check for backspace if (kb[Keys.Back] == KeyState.Down && mLastKeyboardState[Keys.Back] == KeyState.Up) { if (mInputPosition > 0) { mCurrentText.Remove(mInputPosition - 1, 1); } mInputPosition = (int)MathHelper.Clamp(mInputPosition - 1, 0, mCurrentText.Length); } // check for entered text if ((kb[Keys.Enter] == KeyState.Down) && (mLastKeyboardState[Keys.Enter] == KeyState.Up)) { mInputPosition = 0; // if the text is length 0, we won't log it if (mCurrentText.Length == 0) { return; } // build the current text input string string input = mCurrentText.ToString(); // break the text into a command and arguments for any command handlers that // might be registered for it #if XBOX string[] command = input.Split(new char[] { ' ', '\t' }); #else string[] command = input.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); #endif // nothing useful... if (command.Length == 0) { return; } // log it if echo is enabled if (mEchoEnabled) { Log(input, mEchoLogLevel); } // let the raw input handlers do their thing if (TextEntered != null) { TextEntered(input, gameTime); } // remove the command part from the input, leaving the arguments input = input.Remove(0, command[0].Length + ((command.Length > 1) ? (1) : (0))); // clear the current text mCurrentText.Remove(0, mCurrentText.Length); // call any command handlers registered to the command if (mCommandHandlers.ContainsKey(command[0])) { string[] args = new string[] { input }; if (mCommandHandlers[command[0]].ArgumentSeparators.Length > 0) { #if XBOX args = input.Split(mCommandHandlers[command[0]].ArgumentSeparators); #else args = input.Split(mCommandHandlers[command[0]].ArgumentSeparators, StringSplitOptions.RemoveEmptyEntries); #endif } mCommandHandlers[command[0]].Handler(gameTime, args); } else if (mAlertOnUnrecognizedCommand) { Log(string.Format("Unrecognized Command: '{0}'", command[0]), 0); } } // save last keyboard state mLastKeyboardState = kb; base.Update(gameTime); }
/// <summary> /// Gets the correct instance of the <see cref="GetGameConsoleGraphic"/> class. /// </summary> /// <param name="gameConsole">Game for render.</param> /// <param name="coords">Coordinates of the game.</param> /// <param name="renderer">Renderer for the game.</param> /// <returns>Instance of the <see cref="GetGameConsoleGraphic"/> class.</returns> public IRenderable GetGameConsoleGraphic(IGameConsole gameConsole, IntPoint coords, IRenderer renderer) { return(new GameConsoleConsoleGraphic(gameConsole, coords, renderer)); }
private void SetupGameConsole() { GameConsole.Initialize(this, "DiagnosticFont", Color.White, Color.Black, 0.5f, 15); IGameConsole console = (IGameConsole)Services.GetService(typeof(IGameConsole)); console.LoadStuff(); console.Log("Type '?' for help"); console.BindCommandHandler("?", delegate(GameTime time, string[] args) { console.Log("Commands"); console.Log("--------"); //console.Log("PrintArgs [arg1] [arg2] [arg3] ... - Prints the list of arguments passed to it, one per line"); //console.Log("PrintLine [text] - Prints the specified text to the console"); //console.Log("SetDefaultLogLevel [level] - Sets the default log level to the specified level"); //console.Log("SetEchoLogLevel [level] - Sets the log level for echoed output from user input"); //console.Log("SetLogLevelThreshold [threshold] - Sets the log level threshold to the specified threshold value"); //console.Log("SetDisplayLevelThreshold [threshold] - Sets the display level threshold to the specified threshold value"); //console.Log("ToggleEchoEnabled - Toggles the auto input echo feature"); //console.Log("ToggleTimestamp - Toggles the display of each message's timestamp"); //console.Log("ToggleLogLevel - Toggles the display of each message's log level"); //console.Log("SetTextColor [r] [g] [b] - Sets the default text color of console text, where r, g, and b are in the range 0-255"); //console.Log("SetLogLevelColor [level] [r] [g] [b] - Sets the text color for the specified log level, where r, g and b are in the range 0-255"); console.Log("SetGameBackgroundColor [r] [g] [b] - Sets the game back color, where r, g and b are in the range 0-255"); console.Log("SceneStats - Displays the stats of the currently active scene"); }); console.BindCommandHandler("PrintArgs", delegate(GameTime time, string[] args) { foreach (string arg in args) { console.Log(arg); } }, ' '); console.BindCommandHandler("SceneStats", delegate(GameTime time, string[] args) { string _str = ""; _str = "Scene Items Count : " + SceneManager.ActiveScene.SceneItems.Count.ToString(); console.Log(_str); }, ' '); console.BindCommandHandler("SetGameBackgroundColor", delegate(GameTime time, string[] args) { if (args.Length < 3) { return; } try { byte r = byte.Parse(args[0]); byte g = byte.Parse(args[1]); byte b = byte.Parse(args[2]); console.TextColor = new Color(r, g, b, 255); } catch { } }, ' '); console.BindCommandHandler("PrintLine", delegate(GameTime time, string[] args) { if (args.Length == 0) { return; } console.Log(args[0]); }); console.BindCommandHandler("SetDefaultLogLevel", delegate(GameTime time, string[] args) { if (args.Length == 0) { return; } try { console.DefaultLogLevel = uint.Parse(args[0]); } catch { } }, ' '); console.BindCommandHandler("SetEchoLogLevel", delegate(GameTime time, string[] args) { if (args.Length == 0) { return; } try { console.EchoLogLevel = uint.Parse(args[0]); } catch { } }, ' '); console.BindCommandHandler("SetLogLevelThreshold", delegate(GameTime time, string[] args) { if (args.Length == 0) { return; } try { console.LogLevelThreshold = int.Parse(args[0]); } catch { } }, ' '); console.BindCommandHandler("SetDisplayLevelThreshold", delegate(GameTime time, string[] args) { if (args.Length == 0) { return; } try { console.DisplayLevelThreshold = int.Parse(args[0]); } catch { } }, ' '); console.BindCommandHandler("ToggleEchoEnabled", delegate(GameTime time, string[] args) { console.EchoEnabled = !console.EchoEnabled; }); console.BindCommandHandler("ToggleTimestamp", delegate(GameTime time, string[] args) { if ((console.DisplayOptions & ConsoleDisplayOptions.TimeStamp) == ConsoleDisplayOptions.TimeStamp) { console.DisplayOptions &= ~ConsoleDisplayOptions.TimeStamp; } else { console.DisplayOptions |= ConsoleDisplayOptions.TimeStamp; } }); console.BindCommandHandler("ToggleLogLevel", delegate(GameTime time, string[] args) { if ((console.DisplayOptions & ConsoleDisplayOptions.LogLevel) == ConsoleDisplayOptions.LogLevel) { console.DisplayOptions &= ~ConsoleDisplayOptions.LogLevel; } else { console.DisplayOptions |= ConsoleDisplayOptions.LogLevel; } }); console.BindCommandHandler("SetTextColor", delegate(GameTime time, string[] args) { if (args.Length < 3) { return; } try { byte r = byte.Parse(args[0]); byte g = byte.Parse(args[1]); byte b = byte.Parse(args[2]); console.TextColor = new Color(r, g, b, 255); } catch { } }, ' '); console.BindCommandHandler("SetLogLevelColor", delegate(GameTime time, string[] args) { if (args.Length < 4) { return; } try { uint level = uint.Parse(args[0]); byte r = byte.Parse(args[1]); byte g = byte.Parse(args[2]); byte b = byte.Parse(args[3]); console.SetLogLevelCustomColor(level, new Color(r, g, b, 255)); } catch { } }, ' '); }
public override void Initialize() { // get our graphics device graphicsDevice = Game.GraphicsDevice; // create our content manager content = new ContentManager(Game.Services, Game.Content.RootDirectory); // create our spritebatch spriteBatch = new SpriteBatch(graphicsDevice); // get the game console console = (IGameConsole)Game.Services.GetService(typeof(IGameConsole)); // setup camera camera = new Camera(graphicsDevice.Viewport); camera.Limits = WorldUnitsToPixels(new RectangleF(-WorldSize / 2, -WorldSize / 2, WorldSize, WorldSize)); camera.LookAt(Vector2.Zero); graphicsDevice.DeviceReset += GraphicsDeviceReset; ServerLink.MessageReceivedEvent += HandleReceivedMessage; base.Initialize(); }