2

我正在尝试使用 WPF 使用 WiiMote 创建一个非常简单的游戏 Simon 版本。我坚持的是如何使它基于转动,程序阻塞,直到 GUI 完成显示序列。

这是我到目前为止的代码(主要基于这里的答案:WPF - 顺序动画简单示例):

public partial class Window1 : Window
{

    public enum SimonSquare { BLUE = 1, GREEN = 3, RED = 5, YELLOW = 7 };

    List<int> _correctSequence;
    int _currentLevel = 1;
    Random random = new Random();
    Wiimote _wiiMote;
    List<int> _squaresEntered;
    private IEnumerator<Action> _actions;
    Rectangle blueRect;
    Rectangle redRect;
    Rectangle greenRect;
    Rectangle yellowRect;

    AutoResetEvent autoEvent;

    public Window1()
    { 
        InitializeComponent(); 
        blueRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Blue, Name = "Blue"};
        redRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Red, Name = "Red" }; 
        greenRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Green, Name = "Green" };
        yellowRect = new Rectangle() { Fill = 
            System.Windows.Media.Brushes.Yellow, Name = "Yellow" };

        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(blueRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(redRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(greenRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        UniformGrid1.Children.Add(yellowRect);
        UniformGrid1.Children.Add(new Rectangle() { Fill = 
            System.Windows.Media.Brushes.LightGray });
        //connectWiiRemote();

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _actions = AnimationSequence().GetEnumerator();
        autoEvent = new AutoResetEvent(false);
        Thread thread = new Thread(RunNextAction);
        thread.Start();
        autoEvent.WaitOne(); // need to block here somehow!
        int x = 5;
    }   

    IEnumerable<Action> AnimationSequence() 
    {
        getSequence();
        foreach(int square in _correctSequence)
        {
            if(square == (int) SimonSquare.BLUE)
                yield return () => animateCell(blueRect, Colors.Blue); 
            else if(square == (int) SimonSquare.RED)
                yield return () => animateCell(redRect, Colors.Red);
            else if (square == (int)SimonSquare.GREEN)
                yield return () => animateCell(greenRect, Colors.Green);
            else if (square == (int)SimonSquare.YELLOW)
                yield return () => animateCell(yellowRect, Colors.Yellow);
        }
    }

    private void animateCell(Rectangle rectangle, Color fromColor)
    {
        this.Dispatcher.BeginInvoke(new Action(delegate
        {
            Color toColor = Colors.White;
            ColorAnimation ani = new ColorAnimation(toColor, 
                new Duration(TimeSpan.FromMilliseconds(300)));
            ani.AutoReverse = true;
            SolidColorBrush newBrush = new SolidColorBrush(fromColor);
            ani.BeginTime = TimeSpan.FromSeconds(2);
            rectangle.Fill = newBrush;
            ani.Completed += (s, e) => RunNextAction();
            newBrush.BeginAnimation(SolidColorBrush.ColorProperty, ani);

        }));
    }

    private void RunNextAction()
    {
        if (_actions.MoveNext())
            _actions.Current();
        else
        {
            autoEvent.Set();
            _currentLevel++;
        }
    }

    private void getSequence()
    {
        _correctSequence = new List<int>();
        int[] values = 
            Enum.GetValues(typeof(SimonSquare)).Cast<int>().ToArray();
        for (int i = 0; i < _currentLevel + 2; i++)
        {
            _correctSequence.Add(values[random.Next(values.Length)]);
        }

    }
}

但是,autoSet 的 waitOne/set 不能正常工作。它当前调用 RunNextAction 一次,但随后无限期地阻塞在 waitOne 上。我究竟做错了什么?

编辑:让我试着改写这个问题。如果我取出 Threading 和 AutoResetEvent,在 Window_Loaded 我有:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        _actions = AnimationSequence().GetEnumerator();
        RunNextAction(); // shows all of the flashing squares
        // need to wait here until the flashing squares are all shown
        // process player's events etc.
    }

当我运行上面的代码时,它会调用一次 RunNextAction,它会一直调用自己,直到所有的方块都显示出来(它似乎在它自己的线程上),但是 WindowLoaded 方法会继续运行。在我调用 RunNextAction() 之后,我需要 Window_Loaded 阻止,直到 RunNextAction 完全完成。

4

4 回答 4

1

您不应该在 Dispatcher Thread 上调用 WaitOne !

您在 Dispatcher Thread 本身上调用 WaitOne,调度程序线程是 WPF APP 的主线程,如果您阻塞它,任何对 Dispatcher.BeginInvoke 或 Invoke 的调用将永远不会被调用,它将无限期地等待。

相反,更好的方法是将动画移动到另一个名为“AnimationDialog”的窗口并将其加载为模态对话框。

private void window_loaded(object sender, EventArgs e){

    AnimationDialog dialog = new AnimationDialog();
    dialog.Owner = this;
    dialog.ShowDialog(); // this will wait here 

}

在动画对话框窗口...

private void Window_Loaded(object sender, EventArgs e){
    StartAnimationThread();
    // dont do any wait or block here at all...
}

// in your end of animation call "EndAnimation()"

private void EndAnimation(){
    Dispatcher.BeginInvoke()((Action)delegate(){
        this.DialogResult = true; 
        // this will stop this dialog and
        // and execute the parent window's
        // code where showdialog was called... 
    }
    )
}
于 2009-10-03T06:27:38.433 回答
0

我可能误解了你的问题,因为这看起来很简单。在 Window_Loaded 事件中,删除thread.Start();. 添加一个名为 的类级变量_ImDoneSimonizing,并将其初始化为false。对于任何接收用户输入的方法,将其包装在代码中:

if (_ImDoneSimonizing)
{
    // do whatever
}

动画完成后,设置_ImDoneSimonizingtrue

另外两点:

  1. 很酷,你把西蒙带回来了。自 Twister 以来最好的游戏。
  2. 您可以使用 WPF 为 Wii 创建游戏吗?先生,你震撼了我的世界。
于 2009-10-03T02:28:37.790 回答
0

AutoResetEvent 正在做它设计的事情,阻止线程执行,直到调用 Set()。这可能只是意味着您没有调用 Set()。也许您的迭代器没有按照您期望的方式工作(尽管没有测试它看起来还可以)。

您在其他地方调用 Window_Loaded 吗?

于 2009-10-03T02:42:01.380 回答
0

您可以通过抽取 Windows 消息队列来解决此问题。基本上,如果您向消息队列发布回调,则调用线程将阻塞,直到渲染完成。这是一篇解释如何做到这一点的文章:http: //graemehill.ca/wpf-rendering-thread-synchronization

于 2009-10-03T22:18:47.507 回答