Con risposta Simple game by some unknown reason using WPF

  • domenica 29 aprile 2012 19:27
     
      Contiene codice

    Hi,

    I had been trying to make a very simple game with Unicode Characters where there's a player that goes throught a maze of walls, enemies and treasures, but I stopped doing that game a while ago. Now, I want to restart buiilding it. It has almost nothing, since some of my work hadn't been saved.

    The game is based on a 2D array of TextBlocks called "mapa". I noticed a big error when I clicked right to move the player. The position shifted from mapa[0, 0] to mapa[1, 0], but when the info was loaded to the StackPanel sp and then to the window's content, the player's symbol (witch is "@") did not appear at all. Bellow are the remainings of the confusing code of the supposed game.

    /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();            
            }
    
            internal TextBlock[,] mapa = new TextBlock[20, 20];
            internal StackPanel sp = new StackPanel();
            private Jogador j1;
            private byte x = 0;
            private byte y = 0;
    
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                /*
                TextBlock[] linha = new TextBlock[20] { textblock0_0, textblock0_1, textblock0_2, textblock0_3, textblock0_4, textblock0_5, textblock0_6, textblock0_7, textblock0_8, textblock0_9, textblock0_10, textblock0_11, textblock0_12, textblock0_13, textblock0_14, textblock0_15, textblock0_16, textblock0_17, textblock0_18, textblock0_19 };
    
                for (int i = 0; i < linha.Length; i++)
                {
                    linha[i].VerticalAlignment = VerticalAlignment.Bottom;
                    linha[i].HorizontalAlignment = HorizontalAlignment.Left;
                    linha[i].Margin = new Thickness(i * 15 + 15, 0, 0, 15);
                    linha[i].Content = " ";
                    linha[i].FontSize = 14;
                    linha[i].Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xff, 0xff));
                }             
                 */            
                
                mapa = new TextBlock[20, 20]/*{ { textblock0_0, textblock0_1, textblock0_2, textblock0_3, ... */;
                
                /**/for (x = 0; x < mapa.GetLength(0); x++)
                {
                    for (y = 0; y < mapa.GetLength(1); y++)
                    {                    
                        mapa[x, y] = new TextBlock(new Run(" "));
                        mapa[x, y].VerticalAlignment = VerticalAlignment.Bottom;
                        mapa[x, y].HorizontalAlignment = HorizontalAlignment.Left;
                        mapa[x, y].Margin = new Thickness(y * 15 + 15, 0, 0, x * 15 + 15);
                        mapa[x, y].Text = " ";
                        mapa[x, y].FontSize = 14;
                        mapa[x, y].Foreground = new SolidColorBrush(Color.FromRgb(0x00, 0xff, 0xff));
                        sp.Children.Add(mapa[x, y]);
                    }
                }
    
                /*for (i = (sbyte)(mapa.GetLength(0) - 1); i >= 0; i--)
                {
                    for (j = (sbyte)(mapa.GetLength(1) - 1); j >= 0; j--)
                    {
                        mapa[i, j] = new TextBlock(new Run(" "));
                        mapa[i, j].VerticalAlignment = VerticalAlignment.Bottom;
                        mapa[i, j].HorizontalAlignment = HorizontalAlignment.Left;
                        mapa[i, j].Margin = new Thickness(j * 15 + 15, 0, 0, i * 15 + 15);
                        mapa[i, j].Text = " ";
                        mapa[i, j].FontSize = 14;
                        mapa[i, j].Foreground = new SolidColorBrush(Color.FromRgb(0x0, 0x00, 0x00));
                        sp.Children.Add(mapa[i, j]);
                    }
                }*/
    
                //j1 = new Jogador(ref mapa[0, 0]);
                mapa[0, 0].Text = "@";
                this.Content = sp;
            }
            private void Window_KeyDown(object sender, KeyEventArgs e)
            {
                try
                {
                    x = y = 0;
    
                    if (e.Key == Key.Up)
                    {
                        
                    }
    
                    if (e.Key == Key.Down)
                    {
                        
                    }
    
                    if (e.Key == Key.Right)
                    {
                        /*
                        for (i = 1; i < linha.Length; i++)
                        {
                            // j1.Posicao = new Thickness(j1.Posicao.Left + i, 0, 0, j1.Posicao.Bottom);
                            j1 = new Jogador(ref linha[i]);
                            linha[i - 1].Content = " ";
                            // j1.Local.Name = "textblock" + j1.Posicao.Left + 1 + j1.Posicao.Right;
                        }*/
                        /*
                        if (i != 0)
                        {
                            mapa[i - 1, j].Text = " ";
                        }*/
    
                            mapa[x, y].Text = " ";
                            x++; // se usarmos y++ j1 muda a posição, mas erradamente
                            // j1 = new Jogador(ref mapa[i, j]);
                            mapa[x, y].Text = "@";
                            // mapa[i, j].Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xff, 0xff));
                    }
    
                    if (e.Key == Key.Left)
                    {
                        x--;
    
                        if (x > mapa.Length)
                        {
                            x = 0;
                        }
    
                        j1 = new Jogador(ref mapa[x, y]);
    
                        if (x < mapa.GetLength(0) - 1)
                        {
                            mapa[x + 1, y].Text = " ";
                            j1 = new Jogador(ref mapa[x, y]);
                        }
    
                        else
                        {
                            x++;
                            x = Convert.ToByte(mapa.GetLength(0) - 1);
                            x--;
                            mapa[x + 1, y].Text = " ";
                        }
                    }
                }
    
                catch
                {
                    /*if (i >= linha.Length)
                    {
                        i = 9;
                    }
    
                    else
                    {
                        i = 0;
                    }*/
                }
    
                finally
                {
                    sp.Children.Clear();
    
                    foreach (TextBlock tb in mapa)
                    {
                        sp.Children.Add(tb);
                    }
                    //       ^
                    //    ^^^^^^^  equivalente ao que está abaixo
                    //  ^^^^^^^^^^^
                    //       \
                    //       \
                    //       \
                    //       \
                    //       \
    
                    /*for (i = 0; i < mapa.GetLength(0); i++)
                    {
                        for (j = 0; j < mapa.GetLength(1); j++)
                        {
                            sp.Children.Add(mapa[i, j]);
                        }
                    }*/
    
                    // this.Content = mapa;
                    this.Content = sp;          // <-- problema!
                }
            }
        }

    P.S.

    I haven't been coding for some time, so please keep your answers simple and explain every detail. Be patient. The program is by some reason in WPF and what's done is done.

    Thank you,


    João Miguel

    • Spostato Rudedog2MVP domenica 29 aprile 2012 20:27 : move to more appropriate forum : (From:Visual C# General)
    •  

Tutte le risposte

  • domenica 29 aprile 2012 19:34
     
      Contiene codice

    Oh, I forgot, there's another file named "Jogador.cs" with the following code:

    public class Jogador
        {
            protected Jogador()
            {
                Local = new TextBlock();
                Local.VerticalAlignment = VerticalAlignment.Bottom;
                Local.HorizontalAlignment = HorizontalAlignment.Left;
                Local.Margin = new Thickness(10, 0, 0, 10);
                Local.Text = "@";
                // Posicao = Local.Margin;
            }
            public Jogador(ref TextBlock local)
            {            
                Local = new TextBlock();
                Local.VerticalAlignment = VerticalAlignment.Bottom;
                Local.HorizontalAlignment = HorizontalAlignment.Left;
                Local.Margin = new Thickness(local.Margin.Left, 0, 0, local.Margin.Bottom);
                Local.Text = "@";
                local.VerticalAlignment = VerticalAlignment.Bottom;
                local.HorizontalAlignment = HorizontalAlignment.Left;
                local.Text = "@";
                // Posicao = local.Margin;
            }
            public Jogador(ref TextBlock local, Color cor)
            {
                Local = new TextBlock();
                Local.VerticalAlignment = VerticalAlignment.Bottom;
                Local.HorizontalAlignment = HorizontalAlignment.Left;
                Local.Margin = new Thickness(local.Margin.Left, 0, 0, local.Margin.Bottom);
                Local.Text = "@";
                Local.Foreground = new SolidColorBrush(cor);
                local.VerticalAlignment = VerticalAlignment.Bottom;
                local.HorizontalAlignment = HorizontalAlignment.Left;
                local.Text = "@";
                local.Foreground = new SolidColorBrush(cor);            
            }
    
            /*public Thickness Posicao
            {
                get
                {
                    return Local.Margin;
                }
    
                set
                {
                    Local.Name = "textblock" + value.Left + value.Top;
                }
            }*/
            public TextBlock Local
            {
                get;
                private set;
            }
        }
    
        public static partial class Util
        {
            public static bool IsParede(this TextBlock l)
            {
                switch (l.Text.ToString())
                {
                    case "@":
                    case " ":
                        return true;
    
                    case "#":
                    default:
                        return false;
                }
            }
            private static bool IsParede(this TextBlock l, Brush jCor)
            {
                return !((l.Text.ToString() == " " || l.Text.ToString() == "@") && jCor != l.Foreground);
            }        
        }

    The class Jogador represents the player, yet, it may not be necessary. It's simply not used. The class Util has extension/static methods that might be useful.


    João Miguel


    • Modificato JMCF125 domenica 29 aprile 2012 19:38 Incomplete description
    •  
  • domenica 29 aprile 2012 19:35
     
     
    Also ignore the comments. Most of them are useless and confusing.

    João Miguel

  • lunedì 30 aprile 2012 17:17
     
     

    I guess this forum has less users than the C# one. I'm used to have replies 10 minutes after the question.

    Well, sometimes the replies may be questions to the question, but at least the replies come up very quickly.

    Thaks for future help,


    João Miguel

  • lunedì 30 aprile 2012 17:37
    Moderatore
     
     

    "I guess this forum has less users than the C# one. I'm used to have replies 10 minutes after the question."

    Well, what you are doing is a bit weird for WPF. :)

    If I understand correctly those TextBlocks are supposed to display in a 10x10 grid. In that case you should use a Grid panel with 10 rows & columns, not a StackPanel. Or you can use a Canvas since you are already computing the coordinates manually (those TextBlock margins you are setting).

  • lunedì 30 aprile 2012 19:25
     
      Contiene codice

    Sorry for the delay (I left the computer, when I came back 40 minutes have passed and I needed to search and try the Canvas),

    The problem is the Canvas can't contain text directly (by what I searched). It has no method or property that defines its text (although the children of Canvas may contain text, such as TextBlock). The TextBlock element is (by what I searched) a simple element that is able to contain any Unicode character.

    I was also going to try the Grid, but after reading this, I see I have to create rows and colums and to each cell add an element like TextBlock, witch doesn't simplify the imaginary grid of TextBlocks I initialy proposed.

    Yet I removed the StackPanel and named the Grid in MainWindow.xaml to replace it. Somehow, now it is all working fine! I removed some trash in the middle, and now the player moves! Here's the current MainWindow.xaml code:

    /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            internal TextBlock[,] mapa = new TextBlock[20, 20];
            // internal Grid cont = new Grid();
            // private Jogador j1;
            private byte x = 0;
            private byte y = 0;
    
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                mapa = new TextBlock[20, 20];
                
                for (x = 0; x < mapa.GetLength(0); x++)
                {
                    for (y = 0; y < mapa.GetLength(1); y++)
                    {
                        mapa[x, y] = new TextBlock();
                        mapa[x, y].Text = "";
                        mapa[x, y].VerticalAlignment = VerticalAlignment.Bottom;
                        mapa[x, y].HorizontalAlignment = HorizontalAlignment.Left;
                        mapa[x, y].Margin = new Thickness(x * 15 + 15, 0, 0, y * 15 + 15);
                        mapa[x, y].Text = " ";
                        mapa[x, y].FontSize = 14;
                        mapa[x, y].Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xff, 0xff));
                        gridPrincipal.Children.Add(mapa[x, y]);
                    }
                }
    
                mapa[0, 0].Text = "@";
                this.Content = gridPrincipal;
                x = y = 0;
            }
            private void Window_KeyDown(object sender, KeyEventArgs e)
            {
                try
                {
                    if (e.Key == Key.Up && y < 19)
                    {
                        mapa[x, y].Text = " ";
                        y++;
                        mapa[x, y].Text = "@";
                    }
    
                    if (e.Key == Key.Down && y != 0)
                    {
                        mapa[x, y].Text = " ";
                        y--;
                        mapa[x, y].Text = "@";
                    }
    
                    if (e.Key == Key.Right && x < 19)
                    {
                        mapa[x, y].Text = " ";
                        x++;
                        mapa[x, y].Text = "@";
                    }
    
                    if (e.Key == Key.Left && x != 0)
                    {
                        mapa[x, y].Text = " ";
                        x--;
                        mapa[x, y].Text = "@";                    
                    }
                }
    
                catch
                {
                    
                }
    
                finally
                {
                    gridPrincipal.Children.Clear();
    
                    foreach (TextBlock tb in mapa)
                    {
                        gridPrincipal.Children.Add(tb);
                    }
                    //       ^
                    //    ^^^^^^^  equivalente ao que está abaixo
                    //  ^^^^^^^^^^^
                    //       \
                    //       \
                    //       \
                    //       \
                    //       \
    
                    /*for (i = 0; i < mapa.GetLength(0); i++)
                    {
                        for (j = 0; j < mapa.GetLength(1); j++)
                        {
                            sp.Children.Add(mapa[i, j]);
                        }
                    }*/
    
                    // this.Content = mapa;
                    // this.Content = cont;
                }
            }
        }

    I hope someone tests this, its funny to watch the "@" symbol go around like if this was some old game. When I saw it moving it seemed like the first time I ever saw a computer game.

    I won't remove the question or mark this reply as the answer. In this kind of thing, I'll get stuck really quickly. This thread can be used to one of those likely future questions.

    Thank you, you didn't give the answer, but by making me search more, I learned. Still, because you said not to use a StackPanel, I changed that and then it worked. The StackPanel was stucking me. I just don't know why.

    Thank you,


    João Miguel


    • Modificato JMCF125 lunedì 30 aprile 2012 19:29 Correcting ortografic mistakes and adding forgotten content
    •  
  • lunedì 30 aprile 2012 19:47
     
      Contiene codice

    Oh and one more thing I think is strange. In the initial code the program didn't pay attention to these 2 sentences:

    mapa[x, y].VerticalAlignment = VerticalAlignment.Bottom; mapa[x, y].HorizontalAlignment = HorizontalAlignment.Left;

    Now, it does That's pretty odd. Actually the program seemed to ignore most of the code and did things at random. How can a StackPanel cause all that?

    Thanks,

    João Miguel


    • Modificato JMCF125 lunedì 30 aprile 2012 19:50 Strange color of the letters out of the code
    •  
  • lunedì 30 aprile 2012 20:21
    Moderatore
     
     

    A stack panel is supposed to arrange its children in a vertical (or horizontal if you set Orientation to Horizontal) list. Obviously, a list is not suitable if what you want is some kind of grid. In general, each type of Panel with the exception of Canvas (StackPanel, WrapPanel, Grid) impose some particular layout on its children. It's true that to some extent this particular layout can be tweaked by using margins/alignment but that doesn't mean that you can force a StackPanel to display its children in a grid layout.

    Also:

    "The problem is the Canvas can't contain text directly" - Well, no panel can contain text directly. You still need to create text blocks even if you use a canvas. The main difference is that instead of setting the margin of the TextBlock you need to set the attached Left/Top property with some code like:

    Canvas.SetTop(mapa[x, y], y * 15); Canvas.SetLeft(mapa[x, y], x * 15);

    "Yet I removed the StackPanel and named the Grid in MainWindow.xaml to replace it. Somehow, now it is all working fine"

    Indeed, that's another possibility. If you don't have columns and rows in a Grid then the left, top margins you set on text blocks will act as position for the text block.

  • martedì 1 maggio 2012 19:27
     
     
    Interesting.

    João Miguel

  • lunedì 7 maggio 2012 19:51
     
      Contiene codice

    Hi,

    As I said, I got stuck again. First some news: I created a class "Mapa" witch represents the 20 per 20 grid in witch the player moves. It implements IDisposable not because it has unmanaged resources, but because I heard a class should release expensive managed resources to save memory. And I think you'll agree with me, a 2-Dimensional 20 by 20 TextBlock array is expensive. Well, proceeding, I also created a species of a singleton called "Jogo" to use as some kind of game profile to use further in the future. It's just an idea and has no elements whatsoever. It'll have the storage capability of string six games (or profiles), so it will be more like a sixleton than a singleton.

    When I create a map ("Mapa"), I need to set each value that is different from a white space character. To assist me in that effort is the class "CoordString" witch reprents the coordinates of the value and the string that will replace it. It is implicitably convertible from the String type (the implicit operator actually calla the extension method ToCoordString() in the class "Util"(Útil means Useful)).

    I want to restore the "Jogador" class (that represents the player) as well, but I don't want it done now, becuse if I want to see if a change in the code works, I won't make 2 changes, or it will be harder to tell is that specific change worked or failed.

    Probably this is an easy error to solve, but here are the files that may be envolved in the error:

    MainWindow.xaml.cs:

        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
            
            internal TextBlock[,] mapa0tb = new TextBlock[20, 20], mapa1tb = new TextBlock[20, 20];
            internal Mapa mapaIntro = new Mapa(ref mapa0tb, "(2,3, #)");
            // internal Grid cont = new Grid();
            // private Jogador j1;
            private byte x = 0;
            private byte y = 0;
    
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {            
                //mapa1 = new TextBlock[20, 20];
                /*
                for (x = 0; x < mapa1.GetLength(0); x++)
                {
                    for (y = 0; y < mapa1.GetLength(1); y++)
                    {
                        mapa1[x, y] = new TextBlock();
                        mapa1[x, y].Text = "";
                        mapa1[x, y].VerticalAlignment = VerticalAlignment.Bottom;
                        mapa1[x, y].HorizontalAlignment = HorizontalAlignment.Left;
                        mapa1[x, y].Margin = new Thickness(x * 15 + 15, 0, 0, y * 15 + 15);
                        mapa1[x, y].FontSize = 14;
                        mapa1[x, y].Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xff, 0xff));
                        gridPrincipal.Children.Add(mapa1[x, y]);
                    }
                }*//*
                string[,] dif = new string[20, 20];
                
                for (byte x2 = 0; x2 < 20; x2++)
                {
                    for (byte y2 = 0; y2 < 20; y2++)
                    {
                        dif[x2, y2] = " ";
                    }
                }
                dif[0, 0] = "@";
                dif[9, 5] = "#";
                dif[9, 6] = "#";
                dif[9, 7] = "#";
                dif[10, 8] = "#";
                dif[9, 9] = "#";
                dif[9, 10] = "#";
                dif[9, 11] = "#";
                dif[9, 12] = "#";
                dif[9, 13] = "#";
                dif[9, 14] = "#";
                dif[9, 15] = "#";
                dif[10, 16] = "#";
                dif[10, 17] = "#";
                dif[10, 18] = "#";
                dif[11, 19] = "#";*/
                // CarregarMapa(out mapa1tb, 20, 20);//, dif);
                mapaIntro.Carrega(out gridPrincipal);
                // mapa0[0, 0].Text = "@";
                /*mapa1tb[0, 0].Text = "@";
                mapa1tb[9, 5].Text = "#";
                mapa1tb[9, 6].Text = "#";
                mapa1tb[9, 7].Text = "#";
                mapa1tb[10, 8].Text = "#";
                mapa1tb[9, 9].Text = "#";
                mapa1tb[9, 10].Text = "#";
                mapa1tb[9, 11].Text = "#";
                mapa1tb[9, 12].Text = "#";
                mapa1tb[9, 13].Text = "#";
                mapa1tb[9, 14].Text = "#";
                mapa1tb[9, 15].Text = "#";
                mapa1tb[10, 16].Text = "#";
                mapa1tb[10, 17].Text = "#";
                mapa1tb[10, 18].Text = "#";
                mapa1tb[11, 19].Text = "#";
                mapa1tb[10, 9].Text = "#";
                mapa1tb[11, 9].Text = "#";
                mapa1tb[12, 9].Text = "#";
                mapa1tb[13, 9].Text = "#";
                mapa1tb[14, 9].Text = "#";
                mapa1tb[15, 10].Text = "#";
                mapa1tb[18, 19].Text = "€";
                mapaIntro.Carrega(out gridPrincipal);
                x = y = 0;*/
            }
            private void Window_KeyDown(object sender, KeyEventArgs e)
            {
                try
                {
                    if (e.Key == Key.Up && y < 19 && mapa1tb[x, y + 1].Text != "#")
                    {
                        if (mapa1tb[x, y + 1].Text == "€")
                        {
                            // CarregarMapa(out mapa0tb, 20, 20);
                        }
    
                        mapa1tb[x, y].Text = " ";
                        y++;
                        mapa1tb[x, y].Text = "@";
                    }
    
                    if (e.Key == Key.Down && y != 0 && mapa1tb[x, y - 1].Text != "#")
                    {
                        mapa1tb[x, y].Text = " ";
                        y--;
                        mapa1tb[x, y].Text = "@";
                    }
    
                    if (e.Key == Key.Right && x < 19 && mapa1tb[x + 1, y].Text != "#")
                    {
                        mapa1tb[x, y].Text = " ";
                        x++;
                        mapa1tb[x, y].Text = "@";
                    }
    
                    if (e.Key == Key.Left && x != 0 && mapa1tb[x - 1, y].Text != "#")
                    {
                        mapa1tb[x, y].Text = " ";
                        x--;
                        mapa1tb[x, y].Text = "@";
                    }
                }
    
                catch
                {
    
                }
    
                finally
                {
                    /*gridPrincipal.Children.Clear();
    
                    foreach (TextBlock tb in mapa1)
                    {
                        gridPrincipal.Children.Add(tb);
                    }*/
                    //       ^
                    //    ^^^^^^^  equivalente ao que está abaixo
                    //  ^^^^^^^^^^^
                    //       \
                    //       \
                    //       \
                    //       \
                    //       \
    
                    /*for (i = 0; i < mapa.GetLength(0); i++)
                    {
                        for (j = 0; j < mapa.GetLength(1); j++)
                        {
                            sp.Children.Add(mapa[i, j]);
                        }
                    }*/
    
                    // this.Content = mapa;
                    // this.Content = cont;
                }
            }/*
            private void CarregarMapa(out TextBlock[,] mapaBase, byte tamX, byte tamY)//, string[,] mapa)
            {
                mapaBase = new TextBlock[tamX, tamY];
    
                for (byte x = 0; x < mapaBase.GetLength(0); x++)
                {
                    for (byte y = 0; y < mapaBase.GetLength(1); y++)
                    {
                        mapaBase[x, y] = new TextBlock();
                        mapaBase[x, y].Text = " ";
                        mapaBase[x, y].VerticalAlignment = VerticalAlignment.Bottom;
                        mapaBase[x, y].HorizontalAlignment = HorizontalAlignment.Left;
                        mapaBase[x, y].Margin = new Thickness(x * 15 + 15, 0, 0, y * 15 + 15);
                        mapaBase[x, y].FontSize = 14;
                        mapaBase[x, y].Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xff, 0xff));
                        gridPrincipal.Children.Add(mapaBase[x, y]);
                    }
                }
                /*
                for (byte x = 0; x < mapaBase.GetLength(0); x++)
                {
                    for (byte y = 0; y < mapaBase.GetLength(1); y++)
                    {
                        mapaBase[x, y] = new TextBlock();
                        if (mapa[x, y] != null && mapa[x, y] != null)
                        {
                            mapaBase[x, y].Text = mapa[x, y];
                        }
                    }
                } * /
            }*/
        }
    
        public static partial class Util
        {
    
        }

    Mapa.cs:

        public class Mapa : IDisposable
        {
            private bool disposed = false;
            private CoordString[] valSubst;
            internal string[,] valores;
    
            private Mapa()
            {
    
            }
            public Mapa(string[,] valores)
            {
    
            }
            public Mapa(ref TextBlock[,] mapaBase, params CoordString[] valoresSubst)
            {
                valSubst = valoresSubst;
                MapaBase = mapaBase;
            }
    
            public TextBlock[,] MapaBase
            {
                get;
                set;
            }
    
            public void Carrega(out Grid grid)
            {
                grid = new Grid();
    
                for (byte x = 0; x < MapaBase.GetLength(0); x++)
                {
                    for (byte y = 0; y < MapaBase.GetLength(1); y++)
                    {
                        MapaBase[x, y] = new TextBlock();
                        MapaBase[x, y].Text = " ";
                        MapaBase[x, y].VerticalAlignment = VerticalAlignment.Bottom;
                        MapaBase[x, y].HorizontalAlignment = HorizontalAlignment.Left;
                        MapaBase[x, y].Margin = new Thickness(x * 15 + 15, 0, 0, y * 15 + 15);
                        MapaBase[x, y].FontSize = 14;
                        MapaBase[x, y].Foreground = new SolidColorBrush(Color.FromRgb(0xff, 0xff, 0xff));
    
                        foreach (CoordString cs in valSubst)
                        {
                            if (cs.X == x && cs.Y == y)
                            {
                                MapaBase[x, y].Text = cs.Substituidor;
                            }
                        }
    
                        grid.Children.Add(MapaBase[x, y]);
                    }
                }
    
    
            }
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
            protected virtual void Dispose(bool disposing)
            {
                // Check to see if Dispose has already been called.
                
                if (!this.disposed)
                {
                    // If disposing equals true, dispose all managed
                    // and unmanaged resources.
                    if (disposing)
                    {
                        // Dispose managed resources.
                        // valSubst.Dispose();
                        /*valSubst = null;
                        valores = null;
                        MapaBase = null;*/
                        ((IDisposable)(object)valSubst).Dispose();
                        ((IDisposable)(object)valores).Dispose();
                        ((IDisposable)(object)MapaBase).Dispose();
                    }
    
                    // Call the appropriate methods to clean up
                    // unmanaged resources here.
                    // If disposing is false,
                    // only the following code is executed.
    
                    // CloseHandle(handle);
                    // handle = IntPtr.Zero;
    
                    // Note disposing has been done.
                    disposed = true;
                }
            }
    
            ~Mapa()
            {
                Dispose(false);
            }
        }
    
        /**
         * 
         * <summary>Representa um valor a substituir num mapa.</summary>
         * <example>(2, 3, "#")</example>
         */
        public class CoordString
        {
            public CoordString(byte x, byte y, string subst)
            {
                X = x;
                Y = y;
                Substituidor = subst;
            }
            public CoordString(string sCoordString)
            {
                CoordString c = ((CoordString)sCoordString);
                X = c.X;
                Y = c.Y;
                Substituidor = c.Substituidor;
            }
    
            public byte X
            {
                get;
                set;
            }
            public byte Y
            {
                get;
                set;
            }
            public string Substituidor
            {
                get;
                private set;
            }
    
            public override string ToString()
            {
                return "(" + X + ", " + Y + ", \"" + Substituidor + "\")";
            }
    
            public static implicit operator CoordString(string scs)
            {
                return scs.ToCoordString();
            }
        }
    
        public static partial class Util
        {
            internal static CoordString ToCoordString(this string scs)
            {
                try
                {
                    scs = scs.Replace('(', '\uabcd');
                    scs = scs.Replace(')', '\uabcd');
                    scs = scs.Replace('\"', '\uabcd');
                    scs = scs.Replace(' ', '\uabcd');
                    // por alguma razão, \u0000 introduz um 0 em vez do caracter nulo
                    string s = "";
    
                    for (int i = 0; i < scs.Length; i++)
                    {
                        if (scs.ToCharArray()[i] != '\uabcd') // se um espaço fosse usado como comparação, os espaços postos de propósito seriam eliminados
                        {
                            s += scs.ToCharArray()[i];
                        }
                    }
    
                    string[] array = s.Split(',');
    
                    return new CoordString(Convert.ToByte(array[0]), Convert.ToByte(array[1]), array[2]);
                }
    
                catch (Exception e)
                {
                    MessageBox.Show("\"" + e.Message + "\"", "Erro", MessageBoxButton.OK, MessageBoxImage.Error);
                }
    
                return new CoordString(Convert.ToByte(10), Convert.ToByte(10), " ");
            }
        }

    Jogo.cs:

        public class Jogo
        {
            Jogo jogo1 = new Jogo();
            Jogo jogo2 = new Jogo();
            Jogo jogo3 = new Jogo();
            Jogo jogo4 = new Jogo();
            Jogo jogo5 = new Jogo();
            Jogo jogo6 = new Jogo();
    
            private Jogo()
            {
    
            }
        }

    Jogador.cs:

        public class Jogador
        {
            protected Jogador()
            {
                Local = new TextBlock();
                Local.VerticalAlignment = VerticalAlignment.Bottom;
                Local.HorizontalAlignment = HorizontalAlignment.Left;
                Local.Margin = new Thickness(10, 0, 0, 10);
                Local.Text = "@";
                // Posicao = Local.Margin;
            }
            public Jogador(ref TextBlock local)
            {
                local.Text = "@";
                /*
                Local = new TextBlock();
                Local.VerticalAlignment = VerticalAlignment.Bottom;
                Local.HorizontalAlignment = HorizontalAlignment.Left;
                Local.Margin = new Thickness(local.Margin.Left, 0, 0, local.Margin.Bottom);
                Local.Text = "@";
                local.VerticalAlignment = VerticalAlignment.Bottom;
                local.HorizontalAlignment = HorizontalAlignment.Left;
                local.Text = "@";*/
                // Posicao = local.Margin;
            }
            public Jogador(ref TextBlock local, Color cor)
            {
                Local = new TextBlock();
                Local.VerticalAlignment = VerticalAlignment.Bottom;
                Local.HorizontalAlignment = HorizontalAlignment.Left;
                Local.Margin = new Thickness(local.Margin.Left, 0, 0, local.Margin.Bottom);
                Local.Text = "@";
                Local.Foreground = new SolidColorBrush(cor);
                local.VerticalAlignment = VerticalAlignment.Bottom;
                local.HorizontalAlignment = HorizontalAlignment.Left;
                local.Text = "@";
                local.Foreground = new SolidColorBrush(cor);            
            }
    
            public Thickness Posicao
            {
                get
                {
                    return Local.Margin;
                }
    
                set
                {
                    Local.Name = "textblock" + value.Left + value.Top;
                }
            }
            public Thickness PosicaoAnterior
            {
                get
                {
                    return Local.Margin;
                }
    
                set
                {
                    Local.Name = "textblock" + value.Left + value.Top;
                }
            }
            public TextBlock Local
            {
                get;
                private set;
            }
        }
    
        public static partial class Util
        {
            public static bool IsParede(this TextBlock l)
            {
                switch (l.Text.ToString())
                {
                    case "@":
                    case " ":
                        return true;
    
                    case "#":
                    default:
                        return false;
                }
            }
            private static bool IsParede(this TextBlock l, Brush jCor)
            {
                return !((l.Text.ToString() == " " || l.Text.ToString() == "@") && jCor != l.Foreground);
            }
            public static TextBlock[,] PosTesouro(this TextBlock[,] mapa)
            {
                return null;
            }
        }

    Error:

    Error 1 A field initializer cannot reference the non-static field, method, or property 'Tesouro_Escondido.MainWindow.mapa0tb' C:\Users\jmcomputador\documents\visual studio 2010\Projects\Tesouro Escondido\Tesouro Escondido\MainWindow.xaml.cs 28 48 Tesouro Escondido

    Thank you for your pacience to read all this (if you've read it to the bottom here) and to help me,


    João Miguel


    • Modificato JMCF125 lunedì 7 maggio 2012 19:53 missing word
    •  
  • lunedì 7 maggio 2012 20:24
     
      Contiene codice

    Taking a better look,

    CoordString s = new CoordString();
    KeyValuePair<byte[,], string> k = new KeyValuePair<byte[,], string>();

    the examples above are very similar. I could have used "KeyValuePair<TKey, TValue>", I just didn't remember. However, it was a good thing to forget it. Because I searched to see if it was worth it, and "KeyValuePair<TKey, TValue>" takes a lot of memory.


    João Miguel


    • Modificato JMCF125 lunedì 7 maggio 2012 20:24 error
    •  
  • lunedì 7 maggio 2012 20:25
    Moderatore
     
      Contiene codice

    What the error says, the initializer for mapaIntro uses mapa0tb and the compiler doesn't like that. You should put the initializers in the constructor, before InitializeComponent:

            public MainWindow() {
                mapa0tb = new TextBlock[20, 20];
                mapa1tb = new TextBlock[20, 20];
                mapaIntro = new Mapa(mapa0tb, "(2,3, #)");
                InitializeComponent();
            }
            internal TextBlock[,] mapa0tb, mapa1tb;
            internal Mapa mapaIntro;

    Now that should make it compile but there's a few things to note:

    • there's no reason to use ref for the first parameter of Mapa constructor, the constructor does not and should not modify this parameter.
    • Mapa.Carrega has an out parameter and void return type. That's odd, there's no reason to use out here, just return the grid.
    • Dispose - if you want to write a Dispose method you should first figure out what do you want to dispose. As is not there's nothing you can dispose in that class. You're trying to dispose some arrays by casting to IDisposable but this won't work, arrays don't implement IDisposable. Neither the elements in the array (string, CoordString and TextBlock) implement IDisposable. So... there's nothing to dispose.
  • domenica 13 maggio 2012 13:07
     
     

    I'm sorry for the delay, I had time to come here once or twice and read your reply, but not enough time to try it and reply back to you.

    The error was indeed solved, but at run-time, the "#" symbol does not appear. I put a breakpoint in Mapa.cs and everything seemed to be working fine, as shown below:

    

    Of course I wasn't going to stay watching a null character turned into a white space 399 times. So, I put a breakpoint in the end of the method and it the value was the same. But when the program ran, the "#" character wasn't there.

    How can I solve this?


    João Miguel

  • lunedì 14 maggio 2012 06:05
    Moderatore
     
     
    Can you show how you call Carrega in MainWindow?
  • lunedì 14 maggio 2012 19:20
     
     

    Once again, my apolgies for the delay.

    I call it as gridPrincipal = mapaIntro.Carrega(); in the MainWindow.xaml.cs file.

    Thanks,


    João Miguel

  • lunedì 14 maggio 2012 21:10
    Moderatore
     
     Con risposta

    I suspect that won't work properly, you're assigning the new grid to the variable gridPrincipal, this doesn't replace the grid that you already declared in XAML. Try replacing that line with one of the following:

    gridPrincipal.Children.Add(mapaIntro.Carrega());

    or

    gridPrincipal = mapaIntro.Carrega();

    Content = gridPrincipal;

    • Contrassegnato come risposta JMCF125 giovedì 17 maggio 2012 19:13
    •  
  • mercoledì 16 maggio 2012 21:07
     
     

    Hi,

    Thanks, I dit that, and it went well. But then I changed some more stuff (no time to describe it now) and I get this weird TargetInvocationException error.

    I'll mark your previous reply as answer (because it solved this problem, although more problems like this may come up) when I (or someone else) find out the way to eliminate this exception.

    Thank you one more time,


    João Miguel

  • giovedì 17 maggio 2012 09:56
    Moderatore
     
     

    TargetInvocationException error may have something to do with reflection but without a stack trace it's impossible to tell what's going on.

    When you have a different problem you should make a new thread in the appropriate forum (one of the VC# forums if it's not WPF related).

  • giovedì 17 maggio 2012 19:12
     
     
    Thanks, I have posted the error in here.

    João Miguel