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
相关推荐
小白银子13 小时前
零基础从头教学Linux(Day 53)
linux·运维·python
小白杨树树13 小时前
【C++】力扣hot100错误总结
c++·leetcode·c#
skywalk816313 小时前
基于频域的数字盲水印blind-watermark
linux·开发语言·python
applepie_max13 小时前
GraphRAG本地部署 v2.7.0
python·rag·graphrag
Tiger_shl13 小时前
三大并发集合ConcurrentDictionary、ConcurrentBag、ConcurrentQueue
开发语言·c#
sulikey14 小时前
从零配置一个规范的 Python Git 仓库(适用于 Gitee / GitHub)
git·python·pycharm·gitee·github
shaominjin12314 小时前
android在sd卡中可以mkdir, 但是不可以createNewFile
android·开发语言·python
我是华为OD~HR~栗栗呀14 小时前
华为od-22届考研-测试面经
java·c++·python·功能测试·华为od·华为·面试
学习路上_write15 小时前
神经网络初次学习收获
人工智能·python
时光追逐者15 小时前
一个使用 WPF 开发的 Diagram 画板工具(包含流程图FlowChart,思维导图MindEditor)
c#·.net·wpf·流程图