一、實驗目的
- 掌握運算符重載。
- 掌握索引符的編寫。
- 掌握常用非泛型集合類和集合類的使用;
- 掌握可空類型的使用
二、實驗內容
- 改進“畫樹”的例子程序,畫出不同風格的“樹”來。
原先的例子中,兩棵子樹的生長點都在(x1,y1),我們改進一下,將兩棵子樹的生長點不同,在(x1,y1)及(x2,y2)。
程序中可以加上一些控件(如滾動條、文本框等),以方便用戶修改角度(例子中是35及30度)、長度(例子中是per1,per2),這裏又加了兩子樹的位置的係數(即點0至點2的長度是點0至點1的長度的多少倍k)。
(例子中,x1=x0+leng*cos(th), 這裏要加個x2=x0+leng*k*cos(th) )。
還可以加上顏色、粗細、是否隨機等選項,全在於發揮你的想像力!
源代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Homework18
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.AutoScaleBaseSize = new Size(6, 14);
this.ClientSize = new Size(500, 400);//窗體大小
this.Paint += new PaintEventHandler(this.Form1_Paint);
this.Click += new EventHandler(this.Redraw);//重畫
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
graphics = e.Graphics;
drawTree(10, 250, 350, 100, -PI / 2);
drawTree(10, 150, 350, 100, -PI / 2);
}
private void Redraw(object sender, EventArgs e)
{
this.Invalidate();
}//鼠標點擊,重新畫
private Graphics graphics;
const double PI = Math.PI;
double th1 = 40 * Math.PI / 180;
double th2 = 30 * Math.PI / 180;
double per1 = 0.6;
double per2 = 0.7;
Random rnd = new Random();
double rand()
{
return rnd.NextDouble();
}
void drawTree(int n, double x0, double y0, double leng, double th)
{
if (n == 0) return;
double x1 = x0 + leng * Math.Cos(th);
double y1 = y0 + leng * Math.Sin(th);
drawLine(x0, y0, x1, y1, n / 3);
drawTree(n - 1, x1, y1, per1 * leng * (0.5 + rand()), th + th1 * (0.5 + rand()));
drawTree(n - 1, x1, y1, per2 * leng * (0.4 + rand()), th - th2 * (0.5 + rand()));//遞歸調用
if (rand() > 0.6)
drawTree(n - 1, x1, y1, per2 * leng * (0.4 + rand()), th - th2 * (0.5 + rand()));//畫出第三個分支
}
void drawLine(double x0, double y0, double x1, double y1, double width)
{
if ((int)width * 3 <= 1)
graphics.DrawLine(new Pen(Color.Red, (int)width), (int)x0, (int)y0, (int)x1, (int)y1);
else
graphics.DrawLine(new Pen(Color.Green, (int)width), (int)x0, (int)y0, (int)x1, (int)y1);
}
}
}
運行結果
三、實驗心得與體會
- 掌握運算符重載。
- 掌握索引符的編寫。
- 掌握常用非泛型集合類和集合類的使用;
- 掌握可空類型的使用