public LevelManager(int stageWidth, int stageHeight) { mCollideables = new List<Rectangle>(); mBoundingBox = new List<Rectangle>(); mSprites = new List<Sprite>(); mUnits = new List<Unit>(); eCurrLevel = CurrentLevel.None; mGoal = Rectangle.Empty; mInput = new InputManager(); mInput.Alias("left", Keys.A); mInput.Alias("right", Keys.D); mInput.Alias("up", Keys.W); mInput.Alias("down", Keys.S); mInput.Alias("action", Keys.Space); StageHeight = stageHeight; StageWidth = stageWidth; }
void OnTriggerEnter(Collider collider) { if (CurrentLevel.LevelInitialized()) { if ((collider.tag == "Snow") || (collider.tag == "Ice") || (collider.tag == "Reverse") || (collider.tag == "Straight")) { SpawnPool pool; if (pool_name == "Current Level") { pool = PoolManager.Pools[CurrentLevel.GetCurrentLevelPoolName()]; } else { pool = PoolManager.Pools[CurrentLevel.GetGeneralPoolName()]; } Quaternion rotation = collider.transform.rotation * Quaternion.Euler(rotation_angle_x, rotation_angle_y, rotation_angle_z); pool.Spawn(effect, transform.position, rotation); } } }
// Handle user input and transition to new level if needed public void HandleInput(ConsoleKeyInfo key) { LevelTransition newLevel = null; // Different user actions switch (key.Key) { case ConsoleKey.W: newLevel = CurrentLevel.MovePlayer(Player, Constants.DIRECTION.NORTH); break; case ConsoleKey.A: newLevel = CurrentLevel.MovePlayer(Player, Constants.DIRECTION.WEST); break; case ConsoleKey.S: newLevel = CurrentLevel.MovePlayer(Player, Constants.DIRECTION.SOUTH); break; case ConsoleKey.D: newLevel = CurrentLevel.MovePlayer(Player, Constants.DIRECTION.EAST); break; case ConsoleKey.Spacebar: Player.Attack(CurrentLevel); break; case ConsoleKey.Escape: DisplayMenu(); break; default: break; } if (newLevel != null) { TransitionToLevel(newLevel); } }
private void _EndOverdrive() { _State = OverdriveState.Available; if (_LastLevelMode == OverdriveMode.Level) { PrevLevel(); CurrentLevel.Mode = OverdriveMode.Multiplier; } else if (_LastLevelMode == OverdriveMode.Multiplier) { CurrentLevel.Normalize(); if (CanPrevLevel) { PrevLevel(); } else { CurrentLevel.Cripple(); _State = OverdriveState.Unavailable; } } }
private void _ApplyOverdrive() { _LastLevelMode = CurrentLevel.Mode; if (_LastLevelMode == OverdriveMode.Level) { if (CanNextLevel) { NextLevel(); } else { //Make multiplier if cant step forward _LastLevelMode = OverdriveMode.Multiplier; CurrentLevel.Mode = _LastLevelMode; CurrentLevel.Overdrive(); } } else if (_LastLevelMode == OverdriveMode.Multiplier) { CurrentLevel.Overdrive(); } }
/// <summary> /// Logic update /// </summary> /// <param name="pDt"></param> public static void OnFrameMove() { // Calc time float dt = CalcDt(); // Calc FPS mFPSCounter++; mTimeCounter += dt; if (mTimeCounter >= 1) { mFPS = mFPSCounter; mFPSCounter = 0; mTimeCounter = 0; } mPlayer.OnFrameMove(dt); if (CurrentLevel != null) { CurrentLevel.OnFrameMove(dt); } }
private void AddPlanets(BackgroundLayer layer) { List <Texture2D> planets = new List <Texture2D>(); planets.Add(Content.Load <Texture2D>("Images/sun")); planets.Add(Content.Load <Texture2D>("Images/earth")); planets.Add(Content.Load <Texture2D>("Images/jupiter")); Random r = new Random(); Rectangle areaSize = CurrentLevel.Bounds; List <Entity> testList = new List <Entity>(); const float minDistance = 1500; for (int i = 0; i < 20; i++) { Planet planet = new Planet(planets[r.Next(planets.Count)], areaSize, CurrentLevel.PhysicsWorld); bool found = false; while (!found) { planet.Position = Interpolations.GetRandomRectanglePoint(areaSize, r); int tooClose = 0; foreach (Entity e in testList) { if (Vector2.Distance(planet.Position, e.Position) < minDistance) { tooClose++; } } found = (tooClose == 0); } planet.Scale = 2.0f; planet.Rotation = (float)r.NextDouble() * MathHelper.PiOver2; planet.PlanetRotation = (float)r.NextDouble() * 0.0005f; CurrentLevel.AddEntity(planet, layer, true); testList.Add(planet); } }
public void SwitchCurrentLevel() { if (PreviousLevel == null) { PreviousLevel = CurrentLevel; } else { PreviousLevel.SetActive(false); CurrentLevel = NextLevel; } LevelBehaviour levelBehaviour = CurrentLevel.GetComponent <LevelBehaviour>(); GameObject nextLevel = levelBehaviour.GetPossibleNextLevel(); LevelBehaviour nextLevelBehaviour = CurrentLevel.GetComponent <LevelBehaviour>(); Vector3 nextLevelPosition = levelBehaviour.GetNextLevelPosition(nextLevelBehaviour); NextLevel = Instantiate(nextLevel); NextLevel.transform.position = nextLevelPosition; //////////////////////////////// USING SINGLETON /////////////////////////////////////// ScoreBehaviour.Instance.UpdateScore(); //////////////////////////////// USING SINGLETON /////////////////////////////////////// }
public void TestLevel() { /// We need to... /// Clear the current UI /// switch to a widget with a stop test button GameObject commandPalette = GameObject.Find("Command Palette"); LevelEditorUI levelEditorUI = GameObject.FindObjectOfType <LevelEditorUI>(); if (CurrentLevel.levelData.LevelReady()) { CurrentLevel.LoadPaddle(); CurrentLevel.LoadSpawner(); CurrentLevel.StartSpawner(); CurrentLevel.levelData.GatherKeys(); commandPalette.SetActive(false); levelEditorUI.HideAllCommands(); CurrentLevel.StartPlaceableAnimations(); } else { Debug.Log("No spawner in level"); } }
protected override void SetChildrenProperties() { regularBackground.Location = Location; regularBackground.Size = Size; detailsBackground.Location = Location; detailsBackground.Size = Size; skillIcon.Location = new Point2D(Location.X + 5, Location.Y + 5); skillIcon.ContentFile = SkillIcon; currentLevelText.Text = CurrentLevel.ToString(); currentLevelText.Location = new Point2D(Location.X + 32, Location.Y + 4); baseLevelText.Text = BaseLevel.ToString(); baseLevelText.Location = new Point2D(Location.X + 44, Location.Y + 16); detailsText.Location = Location; detailsText.Size = Size; detailsText.Text = $"Xp:{Environment.NewLine}{Experience}"; base.SetChildrenProperties(); }
public override void Draw() { Game.Graphics.GraphicsDevice.Clear(BGColor); if (!Player.Dead) { Game.SpriteBatch.Begin(Game.Camera, samplerState: SamplerState.PointClamp); CurrentLevel.Draw(); Player.Draw(); Particles.Effects.Draw(); Game.SpriteBatch.End(); } Game.SpriteBatch.Begin(samplerState: SamplerState.PointClamp); Game.SpriteBatch.Draw(Helper.SquareTexture, topRect, Color.Black * 0.5f); Player.DrawHUD(); if (!Paused) { pauseButton.Draw(); } if (Paused) { pausePopUp.Draw(); } if (Player.Dead) { Game.SpriteBatch.Draw(Helper.SquareTexture, new Rectangle(0, 0, Game.Screen.X, Game.Screen.Y), Color.Black * 0.5f); restartPopUp.Draw(); } ; Game.SpriteBatch.End(); }
public string this[string columnName] { get { if (columnName == "FirstName") { return(string.IsNullOrEmpty(this.FirstName) ? "Required value" : null); } if (columnName == "LastName") { return(string.IsNullOrEmpty(this.LastName) ? "Required value" : null); } if (columnName == "Program") { return(string.IsNullOrEmpty(Program.ToString()) ? "Required value" : null); } if (columnName == "CurrentSemester") { return(string.IsNullOrEmpty(CurrentSemester.ToString()) ? "Required value" : null); } if (columnName == "CurrentLevel") { return(string.IsNullOrEmpty(CurrentLevel.ToString())? "Required value" : null); } if (columnName == "Email") { return(string.IsNullOrEmpty(Email) ? "Required value" : null); } if (columnName == "Agreed") { return(Agreed ? null : "Required value"); } return(null); } }
public bool NextMove() /* TEST преминаваме на следващ ход, ако можем * (т.е.ако не сме убити, ако не сме завършили и т.н.), иначе прекъсва цикъла*/ { if (MyHero.Health <= 0) { State = GameState.GameOver; } else if (CurrentLevel.IsCompleted(MyHero) && LastLevel()) { State = GameState.GameCompleted; } else if (CurrentLevel.IsCompleted(MyHero) && !LastLevel()) { State = GameState.LevelCompleted; } else if (State == GameState.Playing) { MoveNo++; CanSelectMove = !CanSelectMove; OpponentSelection(); return(true); } return(false); }
public static ParseResult <GedcomHeader> Parse(GedcomLine first, ILineProvider lineProvider) { CurrentLevel currentLevel = CurrentLevel.None; var header = new GedcomHeader(); GedcomLine line = default; string currentRawLine; while ((currentRawLine = lineProvider.ReadLine()) != null) { line = ParserHelper.ParseLine(currentRawLine); if (line.Level == 0) { break; } if (line.Level == 1) { switch (line.GetTagOrRef()) { case "SOUR": currentLevel = CurrentLevel.Sour; break; case "GEDC": currentLevel = CurrentLevel.Gedc; break; case "CHAR": header.GedcomCharacterSet = line.GetLineContent(); break; } } else if (line.Level == 2) { if (currentLevel == CurrentLevel.Sour) { switch (line.GetTagOrRef()) { case "NAME": header.SourceName = line.GetLineContent(); break; case "VERS": header.SourceVers = line.GetLineContent(); break; case "CORP": header.SourceCorp = line.GetLineContent(); break; } } else if (currentLevel == CurrentLevel.Gedc) { if (line.GetTagOrRef() == "VERS") { header.GedcomVers = line.GetLineContent(); } } } } return(ParseResult.Create(header, line)); }
public void ReloadLevel() { SceneManager.LoadScene(CurrentLevel.ToString()); }
internal List <Puzzle> GetPuzzles() { return(PlayingRandom ? CurrentLevel.GetRandomPuzzles(CurrentLevel.NumPuzzles) : LevelManager.Instance.GetPuzzles(CurrentLevel)); }
public virtual void Reset() { CurrentLevel.Reset(); }
public string GetName() { return(string.Format("{0} - {1}", FullName, CurrentLevel.GetClass())); }
public override void Serialize(GenericWriter writer) { base.Serialize(writer); int version = writer.SetVersion(1); UID.Serialize(writer); switch (version) { case 1: { writer.Write(SpawnTownGates); writer.Write(TownGates.Count); if (TownGates.Count > 0) { foreach (Moongate gate in TownGates) { writer.Write(gate); } } goto case 0; } case 0: { writer.Write(InvasionName); writer.Write(RegionName); writer.Write(DateStarted); writer.Write((int)Status); writer.Write(_CoreTicks); writer.Write(CurrentLevelKills); writer.Write(Invaders.Count); if (Invaders.Count > 0) { foreach (Mobile invader in Invaders) { writer.Write(invader); } } writer.Write(Levels.Count); if (Levels.Count > 0) { foreach (Level level in Levels) { level.Serialize(writer); } } writer.Write(ParticipantsScores.Count); if (ParticipantsScores.Count > 0) { foreach (KeyValuePair <PlayerMobile, int> score in ParticipantsScores) { writer.Write(score.Key); writer.Write(score.Value); } } CurrentLevel.Serialize(writer); } break; } }
private void SaveInternal(eSaveMode xiSaveMode, string xiFilename) { if (RootChunk == null) { MessageBox.Show("Can't save: no file is open"); return; } string lExceptionWhen = "saving file"; try { long lPreviousSize = -1; if (xiSaveMode == eSaveMode.Binary && File.Exists(xiFilename)) { lPreviousSize = new FileInfo(xiFilename).Length; } using (FileStream fs = File.Create(xiFilename)) { lExceptionWhen = "serialising the file"; if (xiSaveMode == eSaveMode.Binary) { if (RootChunk is VersionList) { CurrentLevel.Serialise(fs); } else { RootChunk.Serialise(fs); } } else if (xiSaveMode == eSaveMode.Xml) { XmlSerializer xs = new XmlSerializer(typeof(Chunk)); if (RootChunk is VersionList) { xs.Serialize(fs, CurrentLevel); } else { xs.Serialize(fs, RootChunk); } } else if (xiSaveMode == eSaveMode.Mmv) { if (RootChunk is VersionList) { VersionList lVersionList = (VersionList)RootChunk; lVersionList.AddLevel(CurrentLevel); RecursiveAddChunkNode(ChunkTreeView.Nodes[0].Nodes, 1, lVersionList.GetLastVersion()); } else if (RootChunk is Level) { VersionList lVersionList = new VersionList( (Level)RootChunk, Path.GetFileNameWithoutExtension(xiFilename), null); RootChunk = lVersionList; } RootChunk.Serialise(fs); } } if (lPreviousSize != -1 && lPreviousSize != new FileInfo(xiFilename).Length) { MessageBox.Show("WARNING: The size of your level has changed. Please check it's not too large, and check MMEd for bugs that have allowed the size to change.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception err) { Trace.WriteLine(err); MessageBox.Show(string.Format("Exception occurred while {0}: {1}", lExceptionWhen, err.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } mLocalSettings.LastSavedFile = xiFilename; mLocalSettings.LastSavedMode = xiSaveMode; mCurrentFile = xiFilename; mCurrentFileMode = xiSaveMode; }
static void Draw_Tiles() { for (int y = 0; y < Level.GRIDH; y++) { for (int x = 0; x < Level.GRIDW; x++) { int imageIndex = -1; //Open floor image Color imageColor = Color.White; Tile thisTile = CurrentLevel.tileArray[x, y]; //Shorthand for this tile Creature player = CurrentLevel.creatures[0]; //Shorthand for the player creature if (CurrentLevel.levelType == "forest") { imageColor = Color.LightGreen; //Grassy forest floor } if (thisTile.lastSeenImage > 0) //If we've seen it { imageIndex = thisTile.lastSeenImage; //Draw the remembered tile imageColor = Color.DimGray; //But washed out } bool LOS = ((CurrentLevel.LineOfSight(player.pos, new Point2D(x, y))) || iCanSeeForever); if (LOS && player.blind <= 0) //If in line of sight and not blind { imageIndex = 46; //Open floor tile if (CurrentLevel.tileArray[x, y].isWall) { imageIndex = 219; //Wall image imageColor = Color.Tan; } if (CurrentLevel.tileArray[x, y].fixtureLibrary.Count > 0) { int topIndex = CurrentLevel.tileArray[x, y].fixtureLibrary.Count - 1; bool visibleTrap = true; if (CurrentLevel.tileArray[x, y].fixtureLibrary[topIndex] is Trap) { Trap t = (Trap)CurrentLevel.tileArray[x, y].fixtureLibrary[topIndex]; if (t.visible) { visibleTrap = true; } else { visibleTrap = false; } } if (visibleTrap) { imageIndex = CurrentLevel.tileArray[x, y].fixtureLibrary[topIndex].imageIndex; imageColor = CurrentLevel.tileArray[x, y].fixtureLibrary[topIndex].color; } //else //{ // imageIndex = 0; //Open floor image // imageColor = Color.White; //} } } if (CurrentLevel.tileArray[x, y].itemList.Count > 0 && //If there's an item here (CurrentLevel.creatures[0].detectItem > 0 || (LOS && player.blind <= 0))) //If detecting items or can see them { int topIndex = CurrentLevel.tileArray[x, y].itemList.Count - 1; if (CurrentLevel.tileArray[x, y].itemList[topIndex] != null) { imageIndex = CurrentLevel.tileArray[x, y].itemList[topIndex].itemImage; //Top item image imageColor = CurrentLevel.tileArray[x, y].itemList[topIndex].color; } } foreach (Creature c in CurrentLevel.creatures) { if (c.pos == new Point2D(x, y) && //If there's a creature here ((LOS && player.blind <= 0 && (c.invisibility <= 0 || player.seeInvisible > 0)) || player.detectMonster > 0)) //And we can see or detect it { imageIndex = c.creatureImage; imageColor = c.color; } } if (imageIndex >= 0 && imageIndex < 256) //If existent { CurrentLevel.tileArray[x, y].lastSeenImage = imageIndex; //Remember image DrawImage(imageIndex, new Point2D(x * TILEWIDTH, y * TILEHEIGHT), imageColor); //Draw this tile's stuff } if (player.pos == new Point2D(x, y)) //PC should always be drawn { imageIndex = player.creatureImage; imageColor = player.color; DrawImage(imageIndex, new Point2D(x * TILEWIDTH, y * TILEHEIGHT), imageColor); //Draw this tile's stuff } //int smellTotal = 0; //foreach (int s in currentLevel.tileArray[x, y].scentMagnitude) //{ // smellTotal += s; //} //DrawText(veraSmall, smellTotal.ToString(), new Vector2(x * TILEWIDTH, y * TILEHEIGHT), Color.Red); } } }
public InGameScreen(ContentManager content, EventHandler theScreenEvent, Game1 game) : base(theScreenEvent) { mPauseBackground = content.Load<Texture2D>("Images/PausedYes"); _game = game; this.content = content; playerLifeFont = content.Load<SpriteFont>(@"Fonts/General"); scoreFont = content.Load<SpriteFont>(@"Fonts/SpriteFont1"); scoreOverlay = content.Load<Texture2D>(@"Images/Score"); playerHealthBar = content.Load<Texture2D>(@"Images/Healthbar"); gameOver = content.Load<Texture2D>(@"Images/GameOver"); difficulty = Difficulty.easy; level = CurrentLevel.level1; }
//Changes the level. Used in cheats. public string ChangeLevel() { if (currentLevel != null) { switch (level) { case CurrentLevel.level2: currentLevel = new Level2(content, _game); return "The level was changed to level 2"; case CurrentLevel.level3: break; case CurrentLevel.bonusLevel: break; default: break; } } var wrongLevel = (int)level; level -= 1; return string.Format("There is no level initiated or level {0} does not exist.", wrongLevel); // Currently not used as i have no way to display messages. }
public void DrawLevel(GameTime gameTime, SpriteBatch spriteBatch, Camera camera) { CurrentLevel.Draw(gameTime, spriteBatch, camera); }
static void Draw_GetPos() { Draw_Main(); SdlGfx.boxColor(screen, 5, 533, 895, (short)(windowSizeY * 0.992), Color.Black.ToArgb()); SdlGfx.rectangleColor(screen, 5, 533, 895, (short)(windowSizeY * 0.992), Color.White.ToArgb()); DrawImage(88, new Point2D(cursorPos.X * TILEWIDTH, cursorPos.Y * TILEHEIGHT), Color.Yellow); //Draw Cursor #region Description int m = 535; Queue <string> messages = new Queue <string>(); Tile thisTile = CurrentLevel.tileArray[cursorPos.X, cursorPos.Y]; if (CurrentLevel.LineOfSight(CurrentLevel.creatures[0].pos, cursorPos)) //If it can be seen { foreach (Creature c in CurrentLevel.creatures) { if (c.pos == cursorPos) //If creature is at this position { messages.Enqueue("There is a " + c.name + " here."); } } if (thisTile.itemList.Count > 0) { messages.Enqueue("There is a " + thisTile.itemList[0].name + " here."); } if (thisTile.fixtureLibrary.Count > 0) { if (thisTile.fixtureLibrary[0] is Trap) { Trap t = (Trap)thisTile.fixtureLibrary[0]; if (t.visible) { messages.Enqueue("There is a " + thisTile.fixtureLibrary[0].type + " here."); } } else { messages.Enqueue("There is a " + thisTile.fixtureLibrary[0].type + " here."); } } if (thisTile.isWall) { messages.Enqueue("This is a " + thisTile.material.name + " wall."); } } else { messages.Enqueue("You cannot see to there at the moment"); } while (messages.Count >= 14) { messages.Dequeue(); //Don't let there be more than fourteen in the queue } if (messages.Count <= 0) { messages.Enqueue("There is nothing noteworthy here."); } foreach (string message in messages.Reverse()) { m -= 15; //Skip up 15 pixels DrawText(veraSmall, message, new Point2D(10, m), Color.White); } messages.Clear(); #endregion }
protected override void UpdatePosition() { var potentialX = X + _changeX; var potentialY = Y + _changeY; var trajectory = GetTrajectory(potentialX, potentialY); // Apply collision logic to tiles var intersecting = from tile in CurrentLevel.CurrentScreen.Tiles from wall in tile.Boundary let intersection = Geometry.GetIntersection(trajectory, wall) where intersection != null let distance = Geometry.GetDistance(new Point(potentialX, potentialY), intersection) orderby distance select new { Tile = tile, Wall = wall, intersection, distance }; var closest = intersecting.FirstOrDefault(); if (closest != null) { var wall = closest.Wall; var tile = closest.Tile; if (Math.Abs(wall.X1 - wall.X2) < FloatTolerance) // vertical wall { if (X < wall.X1 && tile.Boundary.All(w => w.X1 >= wall.X1 && w.X2 >= wall.X1)) // ball --> wall { X = wall.X1 - BallRadius; } else if (tile.Boundary.All(w => w.X1 <= wall.X1 && w.X2 <= wall.X1)) // wall <-- ball { X = wall.X1 + BallRadius; } _changeX = 0; _collisionX = true; _collisionY = false; } else if (Math.Abs(wall.Y1 - wall.Y2) < FloatTolerance) // horizontal wall { if (Y < wall.Y1 && tile.Boundary.All(w => w.Y1 >= wall.Y1 && w.Y2 >= wall.Y1)) // ball ^^ wall { Y = wall.Y1 - BallRadius; } else if (tile.Boundary.All(w => w.Y1 <= wall.Y1 && w.Y2 <= wall.Y1)) { Y = wall.Y1 + BallRadius; } _changeY = 0; _collisionX = false; _collisionY = true; } else // diagonal wall { if (wall.Y1 > wall.Y2) // diagonal \ { if (tile.Boundary.All(w => w.X1 <= wall.X2 && w.X2 <= wall.X2)) // bottom-left filled in { X += BallRadius; Y += BallRadius; } else // top-right filled in { X -= BallRadius; Y -= BallRadius; } } else if (wall.Y1 < wall.Y2) // diagonal / { if (tile.Boundary.All(w => w.X1 <= wall.X1 && w.X2 <= wall.X1)) // top-left filled in { X += BallRadius; Y -= BallRadius; } else // bottom-right filled in { X -= BallRadius; Y += BallRadius; } } _changeX = 0; _changeY = 0; _collisionX = true; _collisionY = true; } } else { _collisionX = false; _collisionY = false; } // If no collision, move ball normally if (!_collisionX) { X = potentialX; } if (!_collisionY) { Y = potentialY; } else { _changeX /= Friction; } // Apply gravity if (Math.Abs(_changeY) > 1 || Y < CurrentLevel.ScreenHeight - BallRadius) { _changeY -= _gravity; } // If edge of screen hit, switch screens and continue Side?side = null; Line boundary = null; if (Y >= CurrentLevel.ScreenHeight) { side = Side.Top; boundary = new Line(0, CurrentLevel.ScreenHeight, CurrentLevel.ScreenWidth, CurrentLevel.ScreenHeight); } else if (Y <= 0) { side = Side.Bottom; boundary = new Line(0, 0, CurrentLevel.ScreenWidth, 0); } else if (X >= CurrentLevel.ScreenWidth) { side = Side.Right; boundary = new Line(CurrentLevel.ScreenWidth, 0, CurrentLevel.ScreenWidth, CurrentLevel.ScreenHeight); } else if (X <= 0) { side = Side.Left; boundary = new Line(0, 0, 0, CurrentLevel.ScreenHeight); } if (side.HasValue) { var intersection = Geometry.GetIntersection(trajectory, boundary); CurrentLevel.MoveBallToScreen(side.Value); CurrentLevel.InitialisePlayerPosition(side.Value, intersection, this); } }
/// <summary> /// Назначить следующий уровень /// </summary> public void ChangeNewLevel() { CurrentLevel.Set(CurrentLevel + 1); }
public void TickCommands(Timer timer) { timer.Tick += (sender, args) => CurrentLevel.Move(); timer.Tick += (sender, args) => CurrentLevel.TransformGameStat(CurrentGameInfo); timer.Tick += (sender, args) => Invalidate(); }
///======================================================================== /// Method : publishToolStripMenuItem_Click /// /// <summary> /// The Publish operation /// </summary> /// <param name="sender"></param> /// <param name="e"></param> ///======================================================================== private void publishToolStripMenuItem_Click(object sender, EventArgs e) { PublishForm lForm = new PublishForm(this); if (RootChunk is VersionList) { //===================================================================== // Use the properties saved on the VersionList as defaults //===================================================================== VersionList lVersionList = (VersionList)RootChunk; if (lVersionList.CDFilename != null && lVersionList.CDFilename != "") { lForm.CourseDropDown.SelectedItem = MMCD.Courses.Find(new Predicate <MMCD.Course>( delegate(MMCD.Course xiCourse) { return(xiCourse.FileName == lVersionList.CDFilename); })); } if (lVersionList.BinaryFilename != null && lVersionList.BinaryFilename != "") { lForm.BinaryFileTextBox.Text = lVersionList.BinaryFilename; } if (lVersionList.CourseName != null && lVersionList.CourseName != "") { lForm.NameTextBox.Text = lVersionList.CourseName; } } if (lForm.ShowDialog() == DialogResult.OK) { FileInfo lBinaryFile = new FileInfo(lForm.BinaryFileTextBox.Text); //===================================================================== // If we want to keep backups, make one now //===================================================================== if (lForm.BackupsCheckBox.Checked && lBinaryFile.Exists) { string lBackupExtension = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss.bak"); string lBackupPath = Path.Combine(Path.GetDirectoryName(lForm.BinaryFileTextBox.Text), "Backups"); if (!Directory.Exists(lBackupPath)) { Directory.CreateDirectory(lBackupPath); } string lBackupFile = Path.Combine(lBackupPath, Path.GetFileNameWithoutExtension(lForm.BinaryFileTextBox.Text) + "." + lBackupExtension); lBinaryFile.CopyTo(lBackupFile); //=================================================================== // Remove any outdated backups //=================================================================== FileInfo[] lAllBackups = Array.ConvertAll <string, FileInfo>(Directory.GetFiles(lBackupPath, Path.GetFileNameWithoutExtension(lForm.BinaryFileTextBox.Text) + ".*.bak"), new Converter <string, FileInfo>(delegate(string xiFilename) { return(new FileInfo(xiFilename)); })); Utils.ArrayStableSort(lAllBackups, x => x.CreationTime); for (int ii = (int)lForm.BackupCountUpDown.Value; ii < lAllBackups.Length; ii++) { lAllBackups[ii].Delete(); } } //===================================================================== // Save the binary file //===================================================================== using (FileStream lFileStream = lBinaryFile.Create()) { CurrentLevel.Serialise(lFileStream); } if (lForm.UpdateCDImageCheckBox.Checked) { //=================================================================== // Update the CD image //=================================================================== FileInfo lCDFile = new FileInfo(lForm.CDImageTextBox.Text); CDImage lImage = new CDImage(lCDFile); MMCD.Course lCourse = (MMCD.Course)lForm.CourseDropDown.SelectedItem; byte[] lBinaryData = new byte[lCourse.CDLength]; lBinaryFile.Refresh(); if (lBinaryFile.Length != lCourse.CDLength) { MessageBox.Show("File is the wrong length! It will be padded with zeros or truncated to fit on the CD.", "Publish Course", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } using (FileStream lFileStream = lBinaryFile.OpenRead()) { lFileStream.Read(lBinaryData, 0, (int)Math.Min(lBinaryData.Length, lBinaryFile.Length)); } lImage.Replace(lBinaryData, lCourse.CDOffset); lImage.WriteFile(lCDFile); byte[] lCourseNameForCD = Encoding.ASCII.GetBytes(lCourse.GetCDCourseName(lForm.NameTextBox.Text)); foreach (long lNameOffset in lCourse.NameOffsets) { lImage.Replace(lCourseNameForCD, lNameOffset); lImage.WriteFile(lCDFile); } } if (RootChunk is VersionList) { //=================================================================== // Update the properties saved on the VersionList //=================================================================== VersionList lVersionList = (VersionList)RootChunk; lVersionList.BinaryFilename = lForm.BinaryFileTextBox.Text; if (lForm.UpdateCDImageCheckBox.Checked) { lVersionList.CDFilename = ((MMCD.Course)lForm.CourseDropDown.SelectedItem).FileName; lVersionList.CourseName = lForm.NameTextBox.Text; } //=================================================================== // Save the VersionList //=================================================================== if (mCurrentFile != null) { SaveInternal(mCurrentFileMode, mCurrentFile); } } } }
/// <summary> /// Permite al juego ejecutar lógica para, por ejemplo, actualizar el mundo, /// buscar colisiones, recopilar entradas y reproducir audio. /// </summary> /// <param name="gameTime">Proporciona una instantánea de los valores de tiempo.</param> protected override void Update(GameTime gameTime) { ButtonState bs = GamePad.GetState(PlayerIndex.One).Buttons.Back; var touch = TouchPanel.GetState().FirstOrDefault(); bool pressed = touch.State == TouchLocationState.Pressed; bool released = touch.State == TouchLocationState.Released; // About transitions ----------------------------> if (fadingScreen < 255) { fadingScreen += rateFade; } switch (STATE) { #region MENU case GameState.MENU: { if (bs == ButtonState.Pressed) { GameSettings.Save(CurrentProgress); Exit(); } else if (touch.State == TouchLocationState.Pressed) { if (recPlay.Contains((int)touch.Position.X, (int)touch.Position.Y)) { STATE = GameState.WORLD; LockExchangeScreens = true; } else if (recSettings.Contains((int)touch.Position.X, (int)touch.Position.Y)) { CurrentProgress.LevelsPuntuations = new Dictionary <int, int>(); CurrentProgress.CurrentLevel = 1; GameSettings.SetCurrentProgress(CurrentProgress); STATE = GameState.WORLD; PathTexture = Content.Load <Texture2D>("Path/Camino1"); } else if (recAbout.Contains((int)touch.Position.X, (int)touch.Position.Y)) { } } DrawMenu(gameTime); break; } #endregion #region WORLD case GameState.WORLD: { if (bs == ButtonState.Pressed) { STATE = GameState.MENU; break; } else { if (released) { if (!LockExchangeScreens) { dragging = false; if (!tooDragNoClick) { int l = cacheLevelsPositions.Count(); for (int i = 0; i < CurrentProgress.CurrentLevel; i++) { if (i < LAST_LEVEL) { if (cacheLevelsPositions[i].Contains((int)touch.Position.X, (int)(touch.Position.Y + touchLocation))) { STATE = GameState.LEVEL; LoadLevel(i + 1); } } } } tooDragNoClick = false; } LockExchangeScreens = false; } else if (pressed) { onDrag = true; dragging = true; } if (onDrag) { touchWorld = touch; onDrag = false; } if (dragging) { float difference = (touch.Position.Y - touchWorld.Position.Y); touchLocation -= difference; if (touchLocation > MAX_POS_START_WORLD_MAP_Y) { touchLocation = MAX_POS_START_WORLD_MAP_Y; } else if (touchLocation < 0) { touchLocation = 0; } touchWorld = touch; if (Math.Abs(difference) > 1) { tooDragNoClick = true; } } DrawWorld(gameTime); break; } } #endregion #region LEVEL case GameState.LEVEL: { if (bs == ButtonState.Pressed) { STATE = GameState.WORLD; } else if (touch.State == TouchLocationState.Pressed) { int pushX = ((int)touch.Position.X - ScreenDistanceX) / CurrentLevel.SizeSquare, pushY = ((int)touch.Position.Y - ScreenDistanceY) / CurrentLevel.SizeSquare; var tappedPoint = new Point { X = (int)touch.Position.X, Y = (int)touch.Position.Y }; if ((pushX >= 0) && (pushX < CurrentLevel.X) && (pushY >= 0) && (pushY < CurrentLevel.Y)) { SquareExploding = CurrentLevel.squares[pushX, pushY]; if (ItemPushed != -1) { if ((ItemPushed == 0) && (SquareExploding.Content < 2)) { transitionStatus = 4; soundEffect.Play(); SquareExploding.RecentChanged = true; SquareExploding.Switch(); CurrentLevel.moves++; CurrentProgress.GameItems[ItemPushed].Substract(); ItemPushed = -1; if (CurrentLevel.IsLevelCompleted(1)) { ActionsWhenLevelCompleted(); } } else if (ItemPushed == 1) { transitionStatus = 4; soundEffect.Play(); var squareList = CurrentLevel.Get5X5AreaSquares(pushX, pushY); ExplodeSquareList(squareList, false); CurrentProgress.GameItems[ItemPushed].Substract(); ItemPushed = -1; if (CurrentLevel.IsLevelCompleted(1)) { ActionsWhenLevelCompleted(); } } else if (ItemPushed == 5) { dragginItemThunder = true; } } else { if (SquareExploding.Content < 2) { transitionStatus = 4; var squareList = CurrentLevel.GetSquareAndAdjacent(pushX, pushY); ExplodeSquareList(squareList, true); } } } if (RecItemsContainer.Contains(tappedPoint)) { var relativePushed = (tappedPoint.X - startXItems) / 80; ItemPushed = (ItemPushed != relativePushed) && (CurrentProgress.GameItems[relativePushed].Amount > 0) ? relativePushed : -1; } else if (recReset.Contains(tappedPoint)) { CurrentLevel = SetCurrentLevel(Levels.Level[CurrentLevel.LevelNumber]); } else if (StarsRectangle.Contains(tappedPoint)) { if (ItemPushed == 2) { if (CurrentLevel.ONE_STAR > CurrentLevel.moves) { CurrentLevel.moves = 0; } else if (CurrentLevel.TWO_STAR > CurrentLevel.moves) { CurrentLevel.moves = CurrentLevel.ONE_STAR / 2; } else if (CurrentLevel.TWO_STAR == CurrentLevel.moves) { CurrentLevel.moves = 0; } else if (CurrentLevel.THREE_STAR > CurrentLevel.moves) { CurrentLevel.moves = CurrentLevel.TWO_STAR / 2; } else if (CurrentLevel.THREE_STAR == CurrentLevel.moves) { CurrentLevel.moves = CurrentLevel.ONE_STAR; } CurrentProgress.GameItems[ItemPushed].Substract(); ItemPushed = -1; } else if (ItemPushed == 3) { if (CurrentLevel.ONE_STAR > CurrentLevel.moves) { CurrentLevel.moves = 0; } else if (CurrentLevel.TWO_STAR > CurrentLevel.moves) { CurrentLevel.moves = CurrentLevel.ONE_STAR; } else if (CurrentLevel.TWO_STAR == CurrentLevel.moves) { CurrentLevel.moves = 0; } else if (CurrentLevel.THREE_STAR > CurrentLevel.moves) { CurrentLevel.moves = CurrentLevel.TWO_STAR; } else if (CurrentLevel.THREE_STAR == CurrentLevel.moves) { CurrentLevel.moves = CurrentLevel.ONE_STAR; } CurrentProgress.GameItems[ItemPushed].Substract(); ItemPushed = -1; } } } if (transitionStatus > 0) { transitionStatus--; } else { SquareExploding = null; SquaresAdjacent = EmptySquares; } DrawLevel(gameTime); break; } #endregion #region ENDLEVEL case GameState.ENDLEVEL: { if (bs == ButtonState.Pressed || touch.State == TouchLocationState.Released) { if (ScreenChange) { ScreenChange = false; } else { if (!gameOver) { if (CurrentProgress.CurrentLevel < CurrentLevel.LevelNumber) { TotalMoves += CurrentLevel.moves; var next = CurrentLevel.LevelNumber + 1; SetCurrentLevel(Levels.Level[next]); } } STATE = GameState.WORLD; gameOver = false; drawEnd = false; } } else { } DrawLevel(gameTime); break; } } #endregion base.Update(gameTime); }
public virtual void HandleInput(InputHelper inputHelper) { CurrentLevel.HandleInput(inputHelper); }
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch) { CurrentLevel.Draw(gameTime, spriteBatch); }
public IEnumerator LoadLevel(string levelName, LevelData levelData) { if (CurrentLevel != null) { CurrentLevel.Clean(); CurrentLevel = null; } CurrentLevel = new Level() { GoalDescription = levelData.GoalDescription, Max4VBatteries = levelData.Max4VBatteries, Max9VBatteries = levelData.Max9VBatteries, MaxBulbs = levelData.MaxBulbs, MaxBuzzers = levelData.MaxBuzzers, MaxMotors = levelData.MaxMotors, MaxSwitches = levelData.MaxSwitches, MaxWire = levelData.MaxWireAvailable, CanBridge = levelData.CanBridge, CanSnap = levelData.CanSnap, CanBranch = levelData.CanBranch, SuccessByShortCircuit = levelData.SuccessByShortCircuit }; var characterController = ApplicationController.Instance.CharacterController; characterController.ClearAllCharacters(); var wireController = ApplicationController.Instance.WireController; wireController.ClearAllWirePieces(); _grid = FindObjectOfType <BulbGrid>(); _grid.LoadSaveData(levelData.Grid); yield return(null); characterController.LoadCharacters <BatteryCharacter, BatteryCharacterData>(levelData.Batteries); characterController.LoadCharacters <LightBulbCharacter, LightBulbCharacterData>(levelData.LightBulbs); characterController.LoadCharacters <ObstructionCharacter, ObstructionCharacterData>(levelData.Obstructions); characterController.LoadCharacters <MotorCharacter, MotorCharacterData>(levelData.Motors); characterController.LoadCharacters <BuzzerCharacter, BuzzerCharacterData>(levelData.Buzzers); characterController.LoadCharacters <SwitchCharacter, SwitchCharacterData>(levelData.Switches); characterController.UpdateAllCharacters(); wireController.LoadSaveData(levelData.WirePieces); _grid.FillZoomGrid(); if (GameState.CurrentState == GameStates.Game) { var instructionPopup = InstructionsPopup.Instance; instructionPopup.SetDescription(levelData.GoalDescription); instructionPopup.TogglePopup(true); } if (OnLevelLoaded != null) { OnLevelLoaded(levelName, levelData); } _grid.SetGridMode(BulbGrid.GridMode.DrawWire); Debug.LogFormat("{0} | Loaded level: {1}", this, levelName); }
public static void SetNextLevel(string NextLevel) { currentLevel = (CurrentLevel)Enum.Parse(typeof(CurrentLevel), NextLevel); LevelHasChanged = true; }