I'm having issues with generating tokens for the game of nim. Currently all im trying to do is get the generation of the tokens down in the canvas. I recently figured out that you can not add an object of the same name to a children collection if that object already exists in the collection. I need help figuring out an alternative. The tokens need to be generated dynamically so I cannot simply add the shapes through xaml.

Thanks in advance for your help, The following is what im working with now.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Lab8
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        int[] tokenArray = new int[] { 5, 4, 3, 2, 1 };
        Brush tokenColor = new SolidColorBrush(Colors.LightGoldenrodYellow);
        Brush selectColor = new SolidColorBrush(Colors.LightCyan);
        int tokenRows, maxTokensInRow;

        public MainWindow()
            Loaded += delegate

        public void drawTokens() 
            tokenRows = tokenArray.Length;
            maxTokensInRow = tokenArray.Max();


            Ellipse token = new Ellipse();
            token.Stroke = System.Windows.Media.Brushes.Black;
            token.StrokeThickness = 1;
            token.Fill = tokenColor;
            token.Width = (Canvas1.ActualWidth/ (double)maxTokensInRow);
            token.Height = (Canvas1.ActualHeight / (double)tokenRows);
            token.HorizontalAlignment = HorizontalAlignment.Left;
            token.VerticalAlignment = VerticalAlignment.Top;



            double distFromLeft = 5;
            double distFromTop = 5;

            for (int j = 0; j < tokenRows; j++)

                for (int i = 0; i < tokenArray[j]; i++)
                    token.Margin = new Thickness(distFromLeft, distFromTop, 5, 5);

                    Canvas1.Children.Add(token);   //cant add token more than once.

                    distFromLeft += token.Width;
                distFromTop += token.Height;
                distFromLeft = 5;




Nevermind, figured it out. Needed to call a new ellipse token for every children.add.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.