我对这种编程风格很陌生,所以我正在尝试它。
我需要让广场左右移动而不是上下移动,我如何改变代码才能做到这一点?
代码
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;
}
}
}
}
答案 0 :(得分:2)
您的方块移动的位置由FillRectangle函数的第二个和第三个参数定义。
第二个参数是水平位置,第三个参数是垂直位置。
要让你的方块水平移动,你必须改变第二个参数的值(即水平位置)
变化
g.FillRectangle(Brushes.CornflowerBlue, 300, square, 10, 60);
到
g.FillRectangle(Brushes.CornflowerBlue, square, 300, 10, 60);