使用C#和循环移动形状



我对这种编程风格非常新,所以我正在尝试。

我需要让广场向左和向右移动,而不是向上和向下移动,我将如何更改代码来执行此操作?

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Drawing2D;
namespace BouncingBall
{
    public partial class Form1 : Form
    {
        int square;
        int rect;
        int ball;
        Thread t;
        public Form1()
        {
            InitializeComponent();
            t = new Thread(Run);
            t.Start();
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            this.DoubleBuffered = true;
            Graphics g = e.Graphics;
            g.FillEllipse(Brushes.Red, 0, ball, 20, 20);
            g.FillRectangle(Brushes.BurlyWood, 120, rect, 50, 50);
            g.FillRectangle(Brushes.CornflowerBlue, 300, square, 10, 60);    
        }
        private void button1_Click(object sender, EventArgs e)
        {
            t.Abort();
            t.Join();
        }
        private void Run() {
            int dy = 1;
            int ux = 1;
            int lr = 1;
            ball = 0;
            square = 150;
            rect = 95;
            while (true)
            {
                for (int i = 0; i < 140; i++)
                {
                    ball += dy;
                    Invalidate();
                    Thread.Sleep(10);
                }
                dy = -dy;
                for (int i = 0; i < 100; i++)
                {
                    square -= ux;
                    Invalidate();
                    Thread.Sleep(10);
                }
                ux  = -ux;
                for (int i = 0; i < 100; i++)
                {
                    rect -= lr;
                    Invalidate();
                    Thread.Sleep(10);
                }
                lr = -lr;     
            }
        }
    }
}

您的正方形移动的位置由fillrectangle函数的第二和第三参数定义。

第二个参数是水平位置,第三个参数是垂直位置。

要使您的正方形水平移动,您必须更改第二个参数的值(即水平位置)

更改

g.FillRectangle(Brushes.CornflowerBlue, 300, square, 10, 60);

to

g.FillRectangle(Brushes.CornflowerBlue, square, 300, 10, 60);

相关内容

  • 没有找到相关文章

最新更新