Making a NxN tic tac toe GUI wpf c#

前端 未结 3 1095
夕颜
夕颜 2020-12-18 14:58

I am making a NxN tic tac toe game in WPF c#. I want user to enter Rows and Column count(NxN), and my code will generate those number of columns and rows. I can\'t figure it

3条回答
  •  天涯浪人
    2020-12-18 15:28

    ItemsControl + UniformGrid as a Panel is a good choice to display a rectangular game board. I have already posted similar solution (How to create and use matrix of (color) boxes C# WPF) but it is missing Rows and Columns binding. Here is a more elaborated example for TicTacToe.

    Let's create view model classes:

    public class BoardCell : INotifyPropertyChanged
    {
        private string _sign;
        private bool _canSelect = true;
    
        public string Sign
        {
            get { return _sign; }
            set
            {
                _sign = value;
                if (value != null)
                    CanSelect = false;
                OnPropertyChanged();
            }
        }
    
        public bool CanSelect
        {
            get { return _canSelect; }
            set
            {
                _canSelect = value;
                OnPropertyChanged();
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
    public class Board
    {
        public int Rows { get; set; }
        public int Columns { get; set; }
    
        private ObservableCollection _cells;
        public ObservableCollection Cells
        {
            get
            {
                if (_cells == null)
                    _cells = new ObservableCollection(Enumerable.Range(0, Rows*Columns).Select(i => new BoardCell()));
                return _cells;
            }
        } 
    }
    

    and then create a view:

    
        
            
        
        
            
                
                    
                
            
    
            
                
                    

    in the code-behind we have one method to allow 2 players make thier moves in turn:

    private bool _firstPlayer = true;
    private void CellClick(object sender, RoutedEventArgs e)
    {
        var cell = (sender as Button).DataContext as BoardCell;
        cell.Sign = _firstPlayer ? "X" : "O";
        _firstPlayer = !_firstPlayer;
        // TODO check winner 
    }
    

    to follow MVVM pattern this method should be wrapped into a command (ICommand), moved to Board class and attached to view via Button.Command binding.

    summary: separate logic and presentation. work with data. let controls generate their content based on bindings and provided templates.

提交回复
热议问题