⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dodger.cs

📁 学习Managed directx3d的很好的资料,VC#源码实例,共包括6章,其中第四章为:创建三维地形
💻 CS
📖 第 1 页 / 共 2 页
字号:

            // Remove any obstacles that are past the car
            // Increase the score for each one, and also increase
            // the road speed to make the game harder.
            Obstacles removeObstacles = new Obstacles();
            foreach(Obstacle o in obstacles)
            {
                if (o.Depth > car.Diameter - (Car.Depth * 2))
                {
                    // Add this obstacle to our list to remove
                    removeObstacles.Add(o);
                    // Increase roadspeed
                    RoadSpeed += RoadSpeedIncrement;

                    // Make sure the road speed stays below max
                    if (RoadSpeed >= MaximumRoadSpeed)
                    {
                        RoadSpeed = MaximumRoadSpeed;
                    }

                    // Increase the car speed as well
                    car.IncrementSpeed();

                    // Add the new score
                    score += (int)(RoadSpeed * (RoadSpeed / car.Speed));
                }
            }
            // Remove the obstacles in the list
            foreach(Obstacle o in removeObstacles)
            {
                obstacles.Remove(o);
                // May as well dispose it as well
                o.Dispose();
            }
            removeObstacles.Clear();

            // Move our obstacles
            foreach(Obstacle o in obstacles)
            {
                // Update the obstacle, check to see if it hits the car
                o.Update(elapsedTime, RoadSpeed);
                if (o.IsHittingCar(car.Location, car.Diameter))
                {
                    // If it does hit the car, the game is over.
                    isGameOver = true;
                    gameOverTick = System.Environment.TickCount;
                    // Stop our timer
                    Utility.Timer(DirectXTimer.Stop);
                    // Check to see if we want to add this to our high scores list
                    CheckHighScore();
                }
            }

            // Now that the road has been 'moved', update our car if it's moving
            car.Update(elapsedTime);
        }

        /// <summary>
        /// Render our scene here
        /// </summary>
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            // Before this render, we should update any state
            OnFrameUpdate();

            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

            device.BeginScene();

            // Draw the two cycling roads
            DrawRoad(0.0f, 0.0f, RoadDepth0);
            DrawRoad(0.0f, 0.0f, RoadDepth1);

            // Draw the current location of the car
            car.Draw(device);

            // Draw any obstacles currently visible
            foreach(Obstacle o in obstacles)
            {
                o.Draw(device);
            }

            if (hasGameStarted)
            {
                // Draw our score
                scoreFont.DrawText(null, string.Format("Current score: {0}", score), 
                    new Rectangle(5,5,0,0), DrawTextFormat.NoClip, Color.Yellow);
            }

            if (isGameOver)
            {
                // If the game is over, notify the player
                if (hasGameStarted)
                {
                    gameFont.DrawText(null, "You crashed.  The game is over.", new Rectangle(25,45,0,0), DrawTextFormat.NoClip, Color.Red);
                }
                if ((System.Environment.TickCount - gameOverTick) >= 1000)
                {
                    // Only draw this if the game has been over more than one second
                    gameFont.DrawText(null, "Press any key to begin.", new Rectangle(25,100,0,0), DrawTextFormat.NoClip, Color.WhiteSmoke);
                }

                // Draw the high scores
                gameFont.DrawText(null, "High Scores: ", new Rectangle(25,155,0,0), 
                    DrawTextFormat.NoClip, Color.CornflowerBlue);

                for (int i = 0; i < highScores.Length; i++)
                {
                    gameFont.DrawText(null, string.Format("Player: {0} : {1}", highScores[i].Name, 
                        highScores[i].Score), 
                        new Rectangle(25,210 + (i * 55),0,0), DrawTextFormat.NoClip, Color.CornflowerBlue);
                }

            }
            device.EndScene();

            device.Present();

            this.Invalidate();
        }

        private void DrawRoad(float x, float y, float z)
        {
            device.Transform.World = Matrix.Translation(x, y, z);
            for (int i = 0; i < roadMaterials.Length; i++)
            {
                device.Material = roadMaterials[i];
                device.SetTexture(0, roadTextures[i]);
                roadMesh.DrawSubset(i);
            }
        }

        /// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			base.Dispose( disposing );
		}

        /// <summary>
        /// Handle key strokes
        /// </summary>
        protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        {
            // Handle the escape key for quiting
            if (e.KeyCode == Keys.Escape)
            {
                // Close the form and return
                this.Close();
                return;
            }

            // Ignore keystrokes for a second after the game is over
            if ((System.Environment.TickCount - gameOverTick) < 1000)
            {
                return;
            }

            // Handle left and right keys
            if ((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.NumPad4))
            {
                car.IsMovingLeft = true;
                car.IsMovingRight = false;
            }
            if ((e.KeyCode == Keys.Right) || (e.KeyCode == Keys.NumPad6))
            {
                car.IsMovingLeft = false;
                car.IsMovingRight = true;
            }
            // Stop moving
            if (e.KeyCode == Keys.NumPad5)
            {
                car.IsMovingLeft = false;
                car.IsMovingRight = false;
            }
            if (isGameOver)
            {
                LoadDefaultGameOptions();
            }

            // Always set isGameOver to false when a key is pressed
            isGameOver = false;
            hasGameStarted = true;
        }

        /// <summary>
        /// Check to see what the best high score is.  If this beats it, 
        /// store the index, and ask for a name
        /// </summary>
        private void CheckHighScore()
        {
            int index = -1;
            for (int i = highScores.Length - 1; i >= 0; i--)
            {
                if (score >= highScores[i].Score) // We beat this score
                {
                    index = i;
                }
            }

            // We beat the score if index is greater than 0
            if (index >= 0)
            {
                for (int i = highScores.Length - 1; i > index ; i--)
                {
                    // Move each existing score down one
                    highScores[i] = highScores[i-1];
                }
                highScores[index].Score = score;
                highScores[index].Name = Input.InputBox("You got a high score!!", 
                    "Please enter your name.", defaultHighScoreName);
            }
        }

        /// <summary>
        /// Load the high scores from the registry
        /// </summary>
        private void LoadHighScores()
        {
            Microsoft.Win32.RegistryKey key = 
                Microsoft.Win32.Registry.LocalMachine.CreateSubKey(
                "Software\\MDXBoox\\Dodger");

            try
            {
                for(int i = 0; i < highScores.Length; i++)
                {
                    highScores[i].Name = (string)key.GetValue(
                        string.Format("Player{0}", i),  string.Empty);

                    highScores[i].Score = (int)key.GetValue(
                        string.Format("Score{0}", i),  0);
                }
                defaultHighScoreName = (string)key.GetValue(
                    "PlayerName", System.Environment.UserName);
            }
            finally
            {
                if (key != null)
                {
                    key.Close(); // Make sure to close the key
                }
            }
        }

        /// <summary>
        /// Save all the high score information to the registry
        /// </summary>
        public void SaveHighScores()
        {
            Microsoft.Win32.RegistryKey key = 
                Microsoft.Win32.Registry.LocalMachine.CreateSubKey(
                "Software\\MDXBoox\\Dodger");

            try
            {
                for(int i = 0; i < highScores.Length; i++)
                {
                    key.SetValue(string.Format("Player{0}", i), highScores[i].Name);
                    key.SetValue(string.Format("Score{0}", i), highScores[i].Score);
                }
                key.SetValue("PlayerName", defaultHighScoreName);
            }
            finally
            {
                if (key != null)
                {
                    key.Close(); // Make sure to close the key
                }
            }
        }

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
        static void Main() 
        {
            using (DodgerGame frm = new DodgerGame())
            {
                // Show our form and initialize our graphics engine
                frm.Show();
                frm.InitializeGraphics();
                Application.Run(frm);
                // Make sure to save the high scores
                frm.SaveHighScores();
            }
        }
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -