Messagebox input text - name of players wpf c#

A A 61 Reputation points
2021-04-27T16:08:07.363+00:00

Hey,

I have a task to do a game tictactoe. I found code and possible ways to create it. So it is working. Se code below.

  1. Next what I should do - to get MessageBox at the beginning of the game and ask two players to type their name. Then two persons can play and I need to save who win more: cross or noughts e.g it was 10 games, 3 times cross win and 7 times noughts win so this info should be showed somewhere.
    I do not know how to do it.
  2. In xalm I have a square shape for the game and I use "*" so rows and columns have ideal proportions. Don't know who to add there something more and still have everything right-sized.

I consider to do Messagebox with text input (players' name). How to do it? And should it be in the beginning, before public partial class MainWindow : Window ?

Would be glad to get help! Thanks in advance!

Here is code:
XALM:

<Window x:Class="tictactoe.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:tictactoe"
        mc:Ignorable="d"
        ResizeMode="NoResize"
        Title="Tic Tac Toe" Height="500" Width="500">

    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Background" Value="White" />
            <Setter Property="BorderThickness" Value="0.5" />
            <Setter Property="FontSize" Value="70" />
        </Style>
    </Window.Resources>

    <Grid x:Name="Container">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Button Click="Button_Click" x:Name="Button0_0" Grid.Column="0" Grid.Row="0" Content="X" />
        <Button Click="Button_Click" x:Name="Button1_0" Grid.Column="1" Grid.Row="0" Content="O" />
        <Button Click="Button_Click" x:Name="Button2_0" Grid.Column="2" Grid.Row="0" />

        <Button Click="Button_Click" x:Name="Button0_1" Grid.Column="0" Grid.Row="1" />
        <Button Click="Button_Click" x:Name="Button1_1" Grid.Column="1" Grid.Row="1" />
        <Button Click="Button_Click" x:Name="Button2_1" Grid.Column="2" Grid.Row="1" />

        <Button Click="Button_Click" x:Name="Button0_2" Grid.Column="0" Grid.Row="2" />
        <Button Click="Button_Click" x:Name="Button1_2" Grid.Column="1" Grid.Row="2" />
        <Button Click="Button_Click" x:Name="Button2_2" Grid.Column="2" Grid.Row="2" />

    </Grid>
</Window>

c#:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace tictactoe
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Private Members

    /// <summary>
    /// Holds the current results of cells in the active game
    /// </summary>
    private MarkType[] mResults;

    /// <summary>
    /// True if it is player 1's turn (X) or player 2's turn (O)
    /// </summary>
    private bool mPlayer1Turn;

    /// <summary>
    /// True if the game has ended
    /// </summary>
    private bool mGameEnded;

    #endregion

    #region Constructor

    /// <summary>
    /// Default constructor
    /// </summary>
    public MainWindow()
    {
        InitializeComponent();

        NewGame();
    }
    #endregion

    /// <summary>
    /// Starts a new game and clears all values back to the start
    /// </summary>
    private void NewGame()
    {
        // Create a new blank array of free cells
        mResults = new MarkType[9];

        for (var i = 0; i < mResults.Length; i++)
            mResults[i] = MarkType.Free;

        // Make sure Player 1 starts the game
        mPlayer1Turn = true;

        // Interate every button on the grid...
        Container.Children.Cast<Button>().ToList().ForEach(button =>
        {
            // Change background, foreground and content to default values
            button.Content = string.Empty;
            button.Background = Brushes.White;
            button.Foreground = Brushes.Blue;
        });

        // Make sure the game hasn't finished
        mGameEnded = false;
    }

    /// <summary>
    /// Handles a button click event
    /// </summary>
    /// <param name="sender">The button that was clicked</param>
    /// <param name="e">The events of the click</param>

private void Button_Click(object sender, RoutedEventArgs e)
    {
        // Start a new game on the click after it finished
        if (mGameEnded)
        {
            NewGame();
            return;
        }

        // Cast the sender to a button
        var button = (Button)sender;

        // Find the buttons position in the array
        var column = Grid.GetColumn(button);
        var row = Grid.GetRow(button);

        var index = column + (row * 3);

        // Don't do anything if the cell already has a value in it
        if (mResults[index] != MarkType.Free)
            return;

        // Set the cell value based on which players turn it is
        mResults[index] = mPlayer1Turn ? MarkType.Cross : MarkType.Nought;

        // Set button text to the result
        button.Content = mPlayer1Turn ? "X" : "O";

        //Change noughts to green
        if (!mPlayer1Turn)
            button.Foreground = Brushes.Red;

        // Toggle the players turns
        mPlayer1Turn ^= true;

        // Check for a winner
        CheckForWinner();
    }

    /// <summary>
    /// Check if there is a winner of a 3 line straight
    /// </summary>
    private void CheckForWinner()
    {
        #region Horizontal Wins
        // Check for horizontal wins
        //
        // - Row 0
        //
        if (mResults[0] != MarkType.Free && (mResults[0] & mResults[1] & mResults[2]) == mResults[0])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button0_0.Background = Button1_0.Background = Button2_0.Background = Brushes.Green;
        }
        //
        // - Row 1
        //
        if (mResults[3] != MarkType.Free && (mResults[3] & mResults[4] & mResults[5]) == mResults[3])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button0_1.Background = Button1_1.Background = Button2_1.Background = Brushes.Green;
        }
        //
        // - Row 2
        //
        if (mResults[6] != MarkType.Free && (mResults[6] & mResults[7] & mResults[8]) == mResults[6])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button0_2.Background = Button1_2.Background = Button2_2.Background = Brushes.Green;
        }

        #endregion

        #region Vertical Wins

        // Check for vertical wins
        //
        // - Column 0
        //
        if (mResults[0] != MarkType.Free && (mResults[0] & mResults[3] & mResults[6]) == mResults[0])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button0_0.Background = Button0_1.Background = Button0_2.Background = Brushes.Green;
        }
        //
        // - Column 1
        //
        if (mResults[1] != MarkType.Free && (mResults[1] & mResults[4] & mResults[7]) == mResults[1])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button1_0.Background = Button1_1.Background = Button1_2.Background = Brushes.Green;
        }
        //
        // - Column 2
        //
        if (mResults[2] != MarkType.Free && (mResults[2] & mResults[5] & mResults[8]) == mResults[2])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button2_0.Background = Button2_1.Background = Button2_2.Background = Brushes.Green;
        }

        #endregion

        #region Diagonal Wins
        // Check for diagonal wins
        //
        // - Top Left Bottom Right
        //
        if (mResults[0] != MarkType.Free && (mResults[0] & mResults[4] & mResults[8]) == mResults[0])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button0_0.Background = Button1_1.Background = Button2_2.Background = Brushes.Green;
        }
        //
        // - Top Right Bottom Left
        //
        if (mResults[2] != MarkType.Free && (mResults[2] & mResults[4] & mResults[6]) == mResults[2])
        {
            // Game ends
            mGameEnded = true;

            // Highlight winning cwlls in green
            Button2_0.Background = Button1_1.Background = Button0_2.Background = Brushes.Green;
        }

        #endregion
        #region No wins
        if (!mResults.Any(result => result == MarkType.Free))
        {
            // Game ended
            mGameEnded = true;

            // Turn all cells orange
            Container.Children.Cast<Button>().ToList().ForEach(button =>
            {
                button.Background = Brushes.Orange;
            });
        }

        #endregion
    }
}

}

i have this one separately

MarkType.cs:

namespace tictactoe
{
    /// <summary>
    /// The type of value a cell in the game is currently at 
    /// </summary>
    public enum MarkType
    {
        /// <summary>
        /// The cell hasn't been clicked yet
        /// </summary>
        Free,
        /// <summary>
        /// The cell is a O
        /// </summary>
        Nought,
        /// <summary>
        /// The cell is an X
        /// </summary>
        Cross
    }
}
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,683 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,320 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
768 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2021-04-28T05:31:09.197+00:00

    How about using Popup for asking the player to input his name?Below is my sample code for you to refer. If it doesn't give you help, please let me know.
    MainWindow xaml code:

    <Window x:Class="Tictactoe.MainWindow"  
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
                xmlns:local="clr-namespace:Tictactoe"  
                mc:Ignorable="d"  
                Name="myWin"  
                Title="MainWindow" Height="450" Width="800">  
            <Window.Resources>  
                <Style TargetType="Button">  
                    <Setter Property="Background" Value="White" />  
                    <Setter Property="BorderThickness" Value="0.5" />  
                    <Setter Property="FontSize" Value="70" />  
                </Style>  
            </Window.Resources>  
            <Grid>  
                <Grid x:Name="Container">  
                   <!--Your Code-->  
                </Grid>  
                <Popup x:Name="pop1" Width="200" Height="200"  
                                   StaysOpen="True"   
                                   IsOpen="True"   
                                   AllowsTransparency="True"  
                                   PlacementTarget="{Binding ElementName=myWin}"  
                                   Placement="Center"  
                                   >  
                    <Grid Background="Green" Width="200" Height="200">  
                        <Grid.ColumnDefinitions>  
                            <ColumnDefinition Width="90" />  
                            <ColumnDefinition Width="90" />  
                        </Grid.ColumnDefinitions>  
          
                        <Grid.RowDefinitions>  
                            <RowDefinition Height="50" />  
                            <RowDefinition Height="50" />  
                            <RowDefinition Height="50" />  
                        </Grid.RowDefinitions>  
                          
                        <TextBlock Grid.Row="0" Grid.Column="0" Text="Name" Width="80" Height="38"></TextBlock>  
                        <TextBox Name="txtName" Grid.Row="0" Grid.Column="1" Text="" Width="120" Height="38"></TextBox>  
          
                        <TextBlock Grid.Row="1" Grid.Column="0" Text="Password" Width="80" Height="38"></TextBlock>  
                        <TextBox Name="txtPwd" Grid.Row="1" Grid.Column="1" Text="" Width="120" Height="38"></TextBox>  
          
                        <Button Style="{x:Null}" Grid.Row="2" Grid.Column="0" Name="btnCancel" Width="80" Height="38" Click="btnCancel_Click">Cancel</Button>  
                        <Button Style="{x:Null}" Grid.Row="2" Grid.Column="1" Name="btnOK" Width="80" Height="38" Click="btnOK_Click">Ok</Button>  
                          
                    </Grid>  
                </Popup>  
            </Grid>  
          
        </Window>  
    

    And add a class named Player for your project to host use info.

     public class Player  
                {  
                    public string Name { get; set; }  
                    public string PassWord { get; set; }  
                }  
    

    Then add below code to your MainWindow.xaml.cs
    91991-capture.png

    The result picture is:
    91936-capture2.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.