【发布时间】:2023-03-13 12:34:01
【问题描述】:
以下是 WPF 中 Conway 的生命游戏的(非常幼稚的)实现。这只是一个演示......
xaml:
<Window x:Class="wpf_conway_life_2013_05_19.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="500">
<Grid>
<Canvas Name="canvas"
Width="auto"
Height="auto"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</Canvas>
</Grid>
</Window>
后面的代码:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace wpf_conway_life_2013_05_19
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var random = new Random();
var data = new int[100, 100];
var dataB = new int[100, 100];
Func<int, int, int> at = (x, y) =>
{
if (x < 0) x = 100 + x;
if (x >= 100) x = x % 100;
if (y < 0) y = 100 + y;
if (y >= 100) y = y % 100;
return data[x, y];
};
for (var x = 0; x < 100; x++)
for (var y = 0; y < 100; y++)
data[x, y] = random.Next(2);
var rectangles = new Rectangle[100, 100];
for (var x = 0; x < 100; x++)
for (var y = 0; y < 100; y++)
{
rectangles[x, y] = new Rectangle();
canvas.Children.Add(rectangles[x, y]);
}
canvas.SizeChanged += (s, e) =>
{
for (var x = 0; x < 100; x++)
{
for (var y = 0; y < 100; y++)
{
rectangles[x, y].Width = canvas.ActualWidth / 100;
rectangles[x, y].Height = canvas.ActualHeight / 100;
Canvas.SetLeft(rectangles[x, y], (canvas.ActualWidth / 100) * x);
Canvas.SetTop(rectangles[x, y], (canvas.ActualHeight / 100) * y);
}
}
};
Action macroStep = () =>
{
dataB = new int[100, 100];
for (var x = 0; x < 100; x++)
{
for (var y = 0; y < 100; y++)
{
var neighbors = 0;
for (var i = -1; i <= 1; i++)
for (var j = -1; j <= 1; j++)
if (i == 0 && j == 0)
continue;
else
neighbors += at(x + i, y + j);
dataB[x, y] = data[x, y];
if (neighbors < 2) dataB[x, y] = 0;
if (neighbors == 3) dataB[x, y] = 1;
if (neighbors > 3) dataB[x, y] = 0;
rectangles[x, y].Fill = dataB[x, y] == 0 ? new SolidColorBrush(new Color()) : Brushes.Black;
}
}
data = dataB;
};
var timer = new DispatcherTimer();
timer.Tick += (s, e) => macroStep();
timer.Start();
}
}
}
它是这样的:
如果我将new SolidColorBrush(new Color()) 替换为Brushes.White,程序运行速度会慢得多。为什么?
我正在使用 2010 Express 在 Windows 7 64 位上进行测试。
【问题讨论】:
-
为了缩小是渲染还是检索问题,如果您在循环之外保留对画笔的缓存引用并使用该引用代替
Brushes.White,速度会受到影响吗?系统画笔缓存在Dictionary<uint, SolidColorBrush>中,每次检索项目时都必须将其锁定。 -
你和
Brushes.Transparent有同样的行为吗? -
@SimonMcKenzie 好建议。但是,我尝试了它,它没有任何区别。 (顺便说一句,祝贺 MapSnap;非常酷的 WP7 应用!)
-
谢谢!你必须试一试;)虽然我不知道,但我想知道 WPF 是否会并行一些渲染,如果所有项目共享相同的画笔,这可能会受到影响。如果在循环外创建新的画笔实例,性能一样吗?
-
@Rachel
Brushes.Transparent也很慢。有趣的是,它一开始并不像Brushes.White那样慢,但经过大约 5 次迭代后,它变得慢得多。
标签: c# wpf conways-game-of-life brushes