以下代码未显示任何结果。有什么不对或缺少? [英] The following code is not showing any result. What is wrong or missing?

查看:61
本文介绍了以下代码未显示任何结果。有什么不对或缺少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手。我正在研究这个计划。该程序编译但不显示任何结果。请帮帮忙!



我的尝试:



I am new to C#. I was working on this program. The program compiles but does not show any result. Please help!

What I have tried:

using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace ProgrammingAssignment3
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        const int WindowWidth = 800;
        const int WindowHeight = 600;

        Random rand = new Random();
        Vector2 centerLocation = new Vector2(
            WindowWidth / 2, WindowHeight / 2);

        // STUDENTS: declare variables for 3 rock sprites
        Texture2D sprite0;
        Texture2D sprite1;
        Texture2D sprite2;
        // STUDENTS: declare variables for 3 rocks
        Rock rock0;
        Rock rock1;
        Rock rock2;
        // delay support
        const int TotalDelayMilliseconds = 1000;
        int elapsedDelayMilliseconds = 0;

        // random velocity support
        const float BaseSpeed = 0.15f;
        Vector2 upLeft = new Vector2(-BaseSpeed, -BaseSpeed);
        Vector2 upRight = new Vector2(BaseSpeed, -BaseSpeed);
        Vector2 downRight = new Vector2(BaseSpeed, BaseSpeed);
        Vector2 downLeft = new Vector2(-BaseSpeed, BaseSpeed);

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // change resolution
            graphics.PreferredBackBufferWidth = WindowWidth;
            graphics.PreferredBackBufferHeight = WindowHeight;
        }

        /// <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()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // STUDENTS: Load content for 3 sprites
            sprite0 = Content.Load<texture2d>(@"Graphics/greenrock");
            sprite1 = Content.Load<texture2d>(@"Graphics/magentarock");
            sprite2 = Content.Load<texture2d>(@"Graphics/whiterock");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {


            // STUDENTS: update rocks
            if (rock0 != null)
                rock0.Update(gameTime);
            if (rock1 != null)
                rock1.Update(gameTime);
            if (rock2 != null)
                rock2.Update(gameTime);


            // update timer
            elapsedDelayMilliseconds += gameTime.ElapsedGameTime.Milliseconds;
            if (elapsedDelayMilliseconds >= TotalDelayMilliseconds)
            {
                // STUDENTS: timer expired, so spawn new rock if fewer than 3 rocks in window
                // Call the GetRandomRock method to do this

                if (rock0 == null)
                    GetRandomRock();
                if (rock1 == null)
                    GetRandomRock();
                if (rock2 == null)
                    GetRandomRock();

                // restart timer
                elapsedDelayMilliseconds = 0;
            }

            // STUDENTS: Check each rock to see if it's outside the window. If so
            // spawn a new random rock for it by calling the GetRandomRock method
            // Caution: Only check the property if the variable isn't null

            if (rock0 != null && rock0.OutsideWindow == true)
                GetRandomRock();
            if (rock1 != null && rock1.OutsideWindow == true)
                GetRandomRock();
            if (rock2 != null && rock2.OutsideWindow == true)
                GetRandomRock();


            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // STUDENTS: draw rocks
            spriteBatch.Begin();
            if(rock0!=null)
                rock0.Draw(spriteBatch);
            if (rock0 != null)
                rock1.Draw(spriteBatch);
            if (rock0 != null)
                rock2.Draw(spriteBatch);
            spriteBatch.End();

            base.Draw(gameTime);
        }



        /// <summary>
        /// Gets a rock with a random sprite and velocity
        /// </summary>
        /// <returns>the rock</returns>
        private Rock GetRandomRock()
        {
            // STUDENTS: Uncomment and complete the code below to randomly pick a rock sprite by calling the GetRandomSprite method
            Texture2D sprite = GetRandomSprite();

            // STUDENTS: Uncomment and complete the code below to randomly pick a velocity by calling the GetRandomVelocity method
            Vector2 velocity = GetRandomVelocity();

            // STUDENTS: After completing the two lines of code above, delete the following two lines of code
            // They're only included so the code I provided to you compiles

            // return a new rock, centered in the window, with the random sprite and velocity
            return new Rock(sprite, centerLocation, velocity, WindowWidth, WindowHeight);
        }

        /// <summary>
        /// Gets a random sprite
        /// </summary>
        /// <returns>the sprite</returns>
        private Texture2D GetRandomSprite()
        {
            // STUDENTS: Uncommment and modify the code below as appropriate to return
            // a random sprite
            int spriteNumber = rand.Next(0, 3);
            if (spriteNumber == 0)
            {
                return sprite0;
            }
            else if (spriteNumber == 1)
            {
                return sprite1;
            }
            else
            {
                return sprite2;
            }

            // STUDENTS: After completing the code above, delete the following line of code
            // It's only included so the code I provided to you compiles
        }

        /// <summary>
        /// Gets a random velocity
        /// </summary>
        /// <returns>the velocity</returns>
        private Vector2 GetRandomVelocity()
        {
            // STUDENTS: Uncommment and modify the code below as appropriate to return
            // a random velocity
            int velocityNumber = rand.Next(0, 4);
            if (velocityNumber == 0)
            {
                return upLeft;
            }
            else if (velocityNumber == 1)
            {
                return upRight;
            }
            else if (velocityNumber == 2)
            {
                return downRight;
            }
            else
            {
                return downLeft;
            }

            // STUDENTS: After completing the code above, delete the following line of code
            // It's only included so the code I provided to you compiles
        }
    }
}



------------------ -------------------------------------------------- -------------------

摇滚课

------------- -------------------------------------------------- ------------------------


---------------------------------------------------------------------------------------
rock class
---------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ProgrammingAssignment3
{
    /// <summary>
    /// A rock
    /// </summary>
    public class Rock
    {
        #region Fields

        // drawing support
        Texture2D sprite;
        Rectangle drawRectangle;

        // moving support
        Vector2 velocity;

        // window containment support
        int windowWidth;
        int windowHeight;
        bool outsideWindow = false;

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="sprite">sprite for the rock</param>
        /// <param name="location">location of the center of the rock</param>
        /// <param name="velocity">velocity of the rock</param>
        /// <param name="windowWidth">window width</param>
        /// <param name="windowHeight">window height</param>
        public Rock(Texture2D sprite, Vector2 location, Vector2 velocity,
            int windowWidth, int windowHeight)
        {
            // save window dimensions
            this.windowWidth = windowWidth;
            this.windowHeight = windowHeight;

            // save sprite and set draw rectangle
            this.sprite = sprite;
            drawRectangle = new Rectangle((int)location.X - sprite.Width / 2,
                (int)location.Y - sprite.Height / 2, sprite.Width, sprite.Height);

            // save velocity
            this.velocity = velocity;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Sets the rock's velocity
        /// </summary>
        public Vector2 Velocity
        {
            set
            {
                velocity.X = value.X;
                velocity.Y = value.Y;
            }
        }

        /// <summary>
        /// Gets whether or not the rock is outside the window
        /// </summary>
        public bool OutsideWindow
        {
            get { return outsideWindow; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Updates the rock
        /// </summary>
        /// <param name="gameTime">game time</param>
        public void Update(GameTime gameTime)
        {
            // STUDENTS: Only update the rock if it's inside the window
           

            if(outsideWindow==false)
                drawRectangle.X+= (int)velocity.X;
                drawRectangle.Y += (int)velocity.Y;
            // STUDENTS: Update the rock's location


            // STUDENTS: Set outsideWindow to true if the rock is outside the window
            if (drawRectangle.X < 0)
                outsideWindow = true;
            if (drawRectangle.Y < 0)
                outsideWindow = true;
            if (drawRectangle.X > windowWidth)
                outsideWindow = true;
            if (drawRectangle.Y > windowHeight)
                outsideWindow = true;
        }

        /// <summary>
        /// Draws the rock
        /// </summary>
        /// <param name="spriteBatch">sprite batch</param>
        public void Draw(SpriteBatch spriteBatch)
        {
            Console.WriteLine("out"+outsideWindow);
            // STUDENTS: Only draw the rock if it's inside the window
            if (outsideWindow == false)
                spriteBatch.Draw(sprite, drawRectangle, Color.White);
            // STUDENTS: Draw the rock
            // Caution: Don't include spriteBatch.Begin or spriteBatch.End here

        }

        #endregion
    }
}

推荐答案

我们不能。

部分是因为我们不知道它的意图(你的导师没有告诉我们),部分是因为我们不知道如何该课程以外的世界使用它 - 或者即使它也使用它。



编译并不意味着你的代码是正确的! :笑:

将开发过程想象成编写电子邮件:成功编译意味着您使用正确的语言编写电子邮件 - 例如英语而不是德语 - 而不是电子邮件包含您的邮件想发送。



所以现在你进入第二阶段的发展(实际上它是第四或第五阶段,但你将在之后的阶段进入):测试和调试。



首先查看它的作用,以及它与你想要的有何不同。这很重要,因为它可以为您提供有关其原因的信息。例如,如果程序旨在让用户输入一个数字并将其翻倍并打印答案,那么如果输入/输出是这样的:

We can't.
Partly because we have no idea what it's meant to do (Your tutor didn't tell us that) and partly because we have no idea how the world outside that class uses it - or even if it does.

Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16

然后很明显问题出在将它加倍的位 - 它不会将自身加到自身上,或者将它乘以2,它会将它自身相乘并返回输入的平方。

所以,你可以查看代码和很明显,它在某处:

Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:

private int Double(int value)
   {
   return value * value;
   }



因此,请开始使用调试器找出代码无法满足您需求的原因。在你的线上设一个断点:


So start using the debugger to find out why your code doesn't do what you want. Put a breakpoint on your line:

this.windowWidth = windowWidth;

在Update和Draw方法的第一行挖一个并运行你的应用程序。然后当它到达断点时,它将停止并让你控制。您可以查看变量,看看它们持有什么,您可以逐行运行代码。在执行代码之前,请考虑代码中的每一行应该做什么,并将其与使用Step over按钮依次执行每一行时实际执行的操作进行比较。它符合您的期望吗?如果是这样,请转到下一行。

如果没有,为什么不呢?它有何不同?



这是一项非常值得开发的技能,因为它可以帮助你在现实世界和发展中。和所有技能一样,它只能通过使用来改善!

试一试!

Pit another on the first line of your Update and Draw methods and run your app. Then when it hits the breakpoints, it will stop and let you have control. You can look at the variables, and see what they hold, you can run your code line by line. Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?

This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
Give it a go!


这是一个DIY解决方案,因为你的代码太大而无法工作它。我通常会得到报酬来做这样的工作。



你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]



Complimentary to using the debugger, you should also put some checkpoints in your code. each Checkpoint putting informations in a log file telling that execution crossed a given point at a timestamp. Log analyze can help you to spot that a part of the code is not called.
Here is a DIY solution, because your code is too big to work on it. I usually get paid to do such work.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

Complimentary to using the debugger, you should also put some checkpoints in your code. each Checkpoint putting informations in a log file telling that execution crossed a given point at a timestamp. Log analyze can help you to spot that a part of the code is not called.


The problems with the code are:



1)

The problems with the code are:

1)
if (rock0 == null)
                  GetRandomRock();
              if (rock1 == null)
                  GetRandomRock();
              if (rock2 == null)
                  GetRandomRock();



As GetRandomRock() has a return type you need to save the returned value at a particular place.For example \"


As GetRandomRock() has a return type you need to save the returned value at a particular place.For example "

<pre>




rock0= GetRandomRock();





2)



The Vector velocity in the first class is 0.15f which in the following class is converted to int type, resulting to 0 velocity



2)

The Vector velocity in the first class is 0.15f which in the following class is converted to int type, resulting to 0 velocity


这篇关于以下代码未显示任何结果。有什么不对或缺少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆