在Windows窗体上无法通过用户输入来移动圆

时间:2019-07-14 20:04:11

标签: c# input

我正在自学编程,所以我认为制作一个简单的太空射击游戏会很有趣。我有一些代码在图片框中画了一个圆圈,但是我无法使用箭头键来移动它。这是我所拥有的:

internal class Input
{
    //Load list of available Keyboard buttons
    private static Hashtable keyTable = new Hashtable();

    //perform a check to see if a particular button is pressed
    public static bool KeyPressed(Keys key)
    {
        if (keyTable[key] == null)
        {
            return false;
        }
        return (bool)keyTable[key];
    }

    //detect if a keyboard button is pressed
    public static void ChangeState(Keys key, bool state)
    {
        keyTable[key] = state;
    }
}

 enum Direction { None, Up, Down}
class Circle
{
    public static int X { get; set; }
    public static int Y { get; set; }
    public static Direction Direction { get; set; }

    public Circle()
    {
        X = 0;
        Y = 0;
        Direction = Direction.None;
    }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        new Circle();
        gameTimer.Interval = 1000;
        gameTimer.Tick += UpdateScreen;
        gameTimer.Start();
    }

    private void UpdateScreen(object sender , EventArgs e)
    {
        if (Input.KeyPressed(Keys.Down))
        {
            Circle.Direction = Direction.Down;
            Circle.Y += 5;
        }

        else if (Input.KeyPressed(Keys.Up))
        {
            Circle.Direction = Direction.Up;
            Circle.Y -= 5;
        }

        pbCanvas.Invalidate();
    }

    private void pbCanvas_Paint(object sender , PaintEventArgs e)
    {
        Graphics canvas = e.Graphics;
        Brush brush;
        brush = Brushes.Aqua;
        canvas.FillEllipse(brush,
            new Rectangle(Circle.X, Circle.Y, 20, 20));
    }

    private void Form1_KeyDown(object sender , KeyEventArgs e)
    {
        Input.ChangeState(e.KeyCode, true);
    }

    private void Form1_KeyUp(object sender , KeyEventArgs e)
    {
        Input.ChangeState(e.KeyCode, false);
    }
}

我认为问题是我以某种方式错误地执行了Input类,但是我找不到它。感谢您的关注。

0 个答案:

没有答案