usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceWinFormsPythonScript{publicclassBar{publicint Value {get;set;}publicint X {get;set;}publicint Width {get;set;}=20;publicColor Color {get;set;}= Color.Blue;publicvoidDraw(Graphics g,int canvasHeight){int barHeight = Value;int y = canvasHeight - barHeight;using(var brush =newSolidBrush(Color)){
g.FillRectangle(brush, X, y, Width, barHeight);}}}}
Form
usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.Threading;usingSystem.Windows.Forms;usingIronPython.Hosting;usingMicrosoft.Scripting.Hosting;namespaceWinFormsPythonScript{publicpartialclassForm1:Form{publicList<Bar> Bars =newList<Bar>();publicScriptEngine Engine;publicScriptScope Scope;publicForm1(){InitializeComponent();this.DoubleBuffered =true;this.Width =800;this.Height =600;GenerateBars();var runBtn =newButton(){ Text ="Run Sort", Top =10, Left =10, Width =100};
runBtn.Click += RunScript;this.Controls.Add(runBtn);// 初始化 Python
Engine = Python.CreateEngine();
Scope = Engine.CreateScope();
Scope.SetVariable("bars", Bars);
Scope.SetVariable("refresh",(Action)this.RefreshAndWait);}privatevoidGenerateBars(){var rand =newRandom();
Bars.Clear();for(int i =0; i <15; i++){
Bars.Add(newBar{
Value = rand.Next(50,300),
X = i *25*2});}}privatevoidRunScript(object sender,EventArgs e){OpenFileDialog ofd =newOpenFileDialog();
ofd.Filter ="Python Scripts (*.py)|*.py";string script ="";if(ofd.ShowDialog()== DialogResult.OK){
script = ofd.FileName;}Thread thread =newThread(()=>{
Engine.ExecuteFile(script, Scope);});
thread.Start();}privatevoidRefreshAndWait(){this.Invalidate();// 重绘
Application.DoEvents();// 强制刷新 UI
Thread.Sleep(500);// 等待动画}protectedoverridevoidOnPaint(PaintEventArgs e){base.OnPaint(e);foreach(var bar in Bars){
bar.Draw(e.Graphics,this.ClientSize.Height);}}privatevoidForm1_Load(object sender,EventArgs e){}}}
排序python脚本
import time
def swap(i, j):
bars[i].Value, bars[j].Value = bars[j].Value, bars[i].Value
refresh()
n = len(bars)
for i in range(n):
for j in range(0, n - i - 1):
if bars[j].Value > bars[j + 1].Value:
swap(j, j + 1)