C # WPF Game advice - PullRequest
       1

C # WPF Game advice

0 голосов
/ 25 июля 2011

Я хочу создать игру, в которой дано слово, но пропущена одна буква, и вам нужно выбрать одну из приведенных ниже букв.Будучи новичком в C #, мне очень трудно сделать эту работу.Прямо сейчас у меня есть класс слова, который имеет WordFull, LetterA, LetterB, LetterC, индекс (куда мне нужно поместить букву) и CorrectLetter.Затем я загружаю этот объект слова, где я помещаю букву одну за другой в текстовые поля, и если индекс буквы в слове (h [e] llo = 1) равен свойству индекса текущей буквы (index = 1), тогда он отображаетпустое подчеркнутое текстовое поле.Когда вы нажимаете на эту букву, она проверяет правильность этой буквы со свойством CorrectLetter, и это то место, где я застрял.Я хочу поместить это письмо вместо пустого текстового поля.Но как мне это выбрать?Я думаю, что я делаю что-то не так.TL; DR Я хочу сделать игру с буквами, и мне нужен совет, как это сделать.Моя сетка XAML:

<TabItem Name="zaisti" Header="Vykdyti" IsSelected="True">
    <Grid Name="Grid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="7*"/>
            <RowDefinition Height="2*"/>
        </Grid.RowDefinitions>

        <Viewbox Grid.Row="0"  Grid.Column="0">
            <StackPanel Name="letters" Orientation="Horizontal">

            </StackPanel>
        </Viewbox>

        <Image Grid.Row="0" Grid.Column="1" Name="img" Margin="10" Source="pack://siteoforigin:,,,/pic.jpg"/>

        <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Button.Click="Grid_Click">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Button Grid.Column="0" Margin="10">
                <Button.Content>
                    <Viewbox>
                        <Label Name="Option1" Content="{Binding LetterA}"></Label>
                    </Viewbox>
                </Button.Content>
            </Button>
            <Button Grid.Column="1" Margin="10">
                <Button.Content>
                    <Viewbox>
                        <Label Name="Option2" Content="{Binding LetterB}"></Label>
                    </Viewbox>
                </Button.Content>
            </Button>
            <Button Grid.Column="2" Margin="10">
                <Button.Content>
                    <Viewbox>
                        <Label Name="Option3" Content="{Binding LetterC}"></Label>
                    </Viewbox>
                </Button.Content>
            </Button>
        </Grid>

Код позади:

public partial class MainWindow : Window
{
    List<Word> Words = new List<Word>()
    {
        ... data ...
    };
    int index = 0;

    public MainWindow()
    {
        InitializeComponent();
        pradzia.IsSelected = true;
        zaisti.IsEnabled = false;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        zaisti.IsSelected = true;
        zaisti.IsEnabled = true;
        letters.Children.Clear();
        LoadWord(index);
        this.DataContext = Words[index];
    }

    private void Grid_Click(object sender, RoutedEventArgs e)
    {
        if (index == Words.Count() - 1) return;
        MessageBox.Show((((e.Source as Button).Content as Viewbox).Child as Label).Content.ToString());
        if ((((e.Source as Button).Content as Viewbox).Child as Label).Content.ToString() == Words[index].LetterCorrect)
        {
            letters.Children.Clear();
            LoadWord(++index);
            this.DataContext = Words[index];
        }
    }

    private void LoadWord(int i)
    {
        int a = 0;
        foreach (char l in Words[i].WordFull)
        {
            TextBlock letter = new TextBlock();
            letter.Foreground = new SolidColorBrush(Colors.Gray);
            letter.Text = l.ToString();
            letter.Margin = new Thickness(2);

            if (Words[i].index == a)
            {
                letter.Text = ((char)160).ToString() + ((char)160).ToString();

                // Create an underline text decoration. Default is underline.
                TextDecoration myUnderline = new TextDecoration();

                // Create a solid color brush pen for the text decoration.
                myUnderline.Pen = new Pen(Brushes.Red, 1);
                myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended;

                // Set the underline decoration to a TextDecorationCollection and add it to the text block.
                TextDecorationCollection myCollection = new TextDecorationCollection();
                myCollection.Add(myUnderline);
                letter.TextDecorations = myCollection;
            }
            a++;

            letters.Children.Add(letter);
        }
    }

}

Класс слова:

class Word
{
    public string WordFull { get; set; }
    public string LetterA { get; set; }
    public string LetterB { get; set; }
    public string LetterC { get; set; }
    public string LetterCorrect { get; set; }
    public int index { get; set; }
}

1 Ответ

0 голосов
/ 26 июля 2011

Исходя из того, что я вижу, я бы сделал следующее

  • переместить создание отдельных элементов письма (включая подчеркивание) в их собственные методы, которые возвращают компонент для отображения
  • Затем, когда игрок выбирает правильную букву,
    • найти элемент подчеркивания,
    • уберите из букв визуальный контроль,
    • и замените его правильным буквенным элементом.

редактировать - на основе комментария Есть несколько способов добраться до элементов в коллекции Children. Если вы знаете фактический элемент,

letters.Children.Remove(element);

позволит вам удалить указанный элемент или

letters.Children[index];

будет работать, если вы знаете индекс.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...