我试图在c#windows窗体中制作一场紫雨,就像这个视频中的那个https://www.youtube.com/watch?v=KkyIDI6rQJI Hes使用一个名为java编程语言处理的ide。
到目前为止,这是我的代码:
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace PurpleRain
{
public partial class MainForm : Form
{
public MainForm()
{
}
float x=150;
float y=1;
float yspeed=1;
public void fall()
{
y=y+yspeed;
if (y>=350)
{
y=0;
}
}
public void show(float a,float b)
{
Graphics g;
g = this.CreateGraphics();
Pen myPen = new Pen(Color.MediumPurple);
myPen.Width = 2;
Pen myErase = new Pen(Color.Lavender);
myErase.Width = 2;
g.DrawLine(myErase, a, b-1, a, b+15);
g.DrawLine(myPen, a, b, a, b+15);
}
void draw()
{
for (int i=0;i<10;i++){
show(x,y);
fall();
}
}
void Timer1Tick(object sender, EventArgs e)
{
draw();
}
}
这段代码的作用是绘制一条紫色线,并通过删除上一条绘制线使其落到底部。我的问题是添加这条紫色线可能是一百来模拟视频中的雨,并让它们也随机开始x和y位置。我试过循环,列表无济于事。
答案 0 :(得分:0)
不是最好的代码,但它可以是更好的开端:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<Drop> rain = new List<Drop> (); // keeps all drops in one place
Random rnd = new Random (); // for generating random numbers
public Form1 ()
{
InitializeComponent ();
for (int i = 0; i < 100; i++) // creates 100 drops at random position and with random speed
rain.Add (CreateRandomDrop ());
}
private Drop CreateRandomDrop ()
{
return new Drop // create drop with random position and speed
{
Position = new PointF (rnd.Next (this.Width), rnd.Next (this.Height)),
YSpeed = (float) rnd.NextDouble () * 3 + 2 // 2..5
};
}
private void UpdateRain () // changes Y position for each drop (falling), also checks if a drop is outside Main form, if yes, resets position to 0
{
foreach (var drop in rain)
{
drop.Fall ();
if (drop.Position.Y > this.Height)
drop.Position.Y = 0;
}
}
private void RenderRain ()
{
using (var grp = this.CreateGraphics ()) // using will call IDisposable.Dispose
{
grp.Clear (Color.DarkBlue);
foreach (var drop in rain)
grp.DrawLine (Pens.White, drop.Position, new PointF (drop.Position.X, drop.Position.Y + 3));
}
}
private void timer1_Tick (object sender, EventArgs e)
{
UpdateRain ();
RenderRain ();
}
}
class Drop
{
public PointF Position;
public float YSpeed;
public void Fall () => Position.Y += YSpeed;
}
}