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
相关推荐
覆东流2 小时前
python安装与使用
开发语言·python
玉笥寻珍3 小时前
数字政务安全实战:等保2.0框架下OA系统防护全解析
python·安全·政务
瓦力wow7 小时前
python 绘制3D平面图
开发语言·python·3d·matplotlib
Yu_Mao_Cat8 小时前
数独求解器3.0 增加latex格式读取
开发语言·python·算法
江沉晚呤时9 小时前
GraphQL在.NET 8中的全面实践指南
microsoft·ui·c#·.net·.netcore·graphql
ElvInR9 小时前
冒泡排序详解
c语言·c++·排序算法·冒泡排序
inksci9 小时前
Python web 开发 Flask HTTP 服务
python·flask
熊猫在哪10 小时前
野火鲁班猫(arrch64架构debian)从零实现用MobileFaceNet算法进行实时人脸识别(一)conda环境搭建
linux·人工智能·python·嵌入式硬件·神经网络·机器学习·边缘计算
满怀101510 小时前
【Python中的Socket套接字详解】网络通信的核心基石
开发语言·网络·python·网络编程·socket