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
相关推荐
2301_805054563 分钟前
Python训练营打卡Day59(2025.7.3)
开发语言·python
万千思绪28 分钟前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
2401_858286111 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
微风粼粼2 小时前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
云天徽上2 小时前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5
你怎么知道我是队长3 小时前
python-input内置函数
开发语言·python
叹一曲当时只道是寻常3 小时前
Python实现优雅的目录结构打印工具
python
hbwhmama4 小时前
python高级变量XIII
python
昏睡红猹4 小时前
C#脚本化(Roslyn):如何在运行时引入nuget包
c#
费弗里4 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(3)
python·dash