c#和python互操作实现排序算法可视化

Bar

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsPythonScript
{
     public class Bar
    {
        public int Value { get; set; }
        public int X { get; set; }
        public int Width { get; set; } = 20;
        public Color Color { get; set; } = Color.Blue;

        public void Draw(Graphics g, int canvasHeight)
        {
            int barHeight = Value;
            int y = canvasHeight - barHeight;

            using (var brush = new SolidBrush(Color))
            {
                g.FillRectangle(brush, X, y, Width, barHeight);
            }
        }
    }
}

Form

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;


namespace WinFormsPythonScript
{
    public partial class Form1 : Form
    {
        public List<Bar> Bars = new List<Bar>();
        public ScriptEngine Engine;
        public ScriptScope Scope;

        public Form1()
        {
            InitializeComponent();
            this.DoubleBuffered = true;
            this.Width = 800;
            this.Height = 600;

            GenerateBars();

            var runBtn = new Button() { 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);
        }

        private void GenerateBars()
        {
            var rand = new Random();
            Bars.Clear();
            for (int i = 0; i < 15; i++)
            {
                Bars.Add(new Bar
                {
                    Value = rand.Next(50, 300),
                    X = i * 25 * 2
                });
            }
        }

        private void RunScript(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Python Scripts (*.py)|*.py";
            string script = "";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                script = ofd.FileName;
            }
            Thread thread = new Thread(() =>
            {
               
                Engine.ExecuteFile(script, Scope);
            });
            thread.Start();
        }

        private void RefreshAndWait()
        {
            this.Invalidate();               // 重绘
            Application.DoEvents();         // 强制刷新 UI
            Thread.Sleep(500);              // 等待动画
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            foreach (var bar in Bars)
            {
                bar.Draw(e.Graphics, this.ClientSize.Height);
            }
        }

        private void Form1_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)

安装依赖

复制代码
Install-Package IronPython
相关推荐
天远数科12 分钟前
零信任架构实战:基于天远车辆过户详版查询构建自动化抵押车权属合规审查网关
人工智能·python·架构·自动化
badhope36 分钟前
3 个 Agent 并行发文章:我用 SQLite 任务表止住重复
后端·python·ai编程
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
databook1 小时前
马尔可夫链入门:状态、转移概率与无记忆性
python·机器学习·数据分析
郝学胜-神的一滴2 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy
SummerJokes3 小时前
Java 多线程专项实验|两种创建线程方式、synchronized 线程同步、银行存取款实战
java·开发语言·python
艾派森3 小时前
Python帕累托分析实战:用二八法则找出贡献80%营收的核心商品
android·开发语言·python
向科→向总工→空间动态计系统4 小时前
剃刀明盒:几何与时序双验证
大数据·开发语言·人工智能·python
临床数据科学和人工智能兴趣组4 小时前
2026 年,医学研究更应该选 R 而不是 Python
python·机器学习·数据挖掘·r语言·r语言-4.2.1·临床研究
SummerJokes4 小时前
Java 异常处理完整详解|try‑catch‑finally、throws、throw、自定义异常实战
java·开发语言·python