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
相关推荐
linzeyang10 分钟前
Advent of Code 2025 挑战全手写代码 Day 1 - 秘密入口
python·github
阿郎_201122 分钟前
python自动化脚本-下载小说
python·selenium·网络爬虫
ERP老兵-冷溪虎山24 分钟前
Python/JS/Go/Java同步学习(第五十篇半)四语言“path路径详解“对照表: 看完这篇定位文件就通透了(附源码/截图/参数表/避坑指南)
java·javascript·python·golang·中医编程·编程四语言同步学·path路径详解
Data_agent30 分钟前
1688获得1688公司档案信息API,python请求示例
开发语言·数据库·python
qq_3363139339 分钟前
java基础-排序算法
java·开发语言·排序算法
周杰伦fans1 小时前
C#中OrderByDescending 是LINQ扩展方法之一
开发语言·c#·linq
周杰伦fans1 小时前
C# 中 SQL Server 数据库调优指南(小白友好版)
开发语言·数据库·c#
zs宝来了2 小时前
HOT100系列-堆类型题
数据结构·算法·排序算法
vx_vxbs662 小时前
【SSM高校普法系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
android·java·python·mysql·小程序·php·idea
田里的水稻2 小时前
Python_编程中代码注释相关格式 PEP8 — Python 官方代码风格指南
开发语言·python