OurGamesForCourse

Форк
0
/
MainWindow.xaml.cs 
206 строк · 7.3 Кб
1
using System.Text;
2
using System.Windows;
3
using System.Windows.Controls;
4
using System.Windows.Data;
5
using System.Windows.Documents;
6
using System.Windows.Input;
7
using System.Windows.Media;
8
using System.Windows.Media.Imaging;
9
using System.Windows.Navigation;
10
using System.Windows.Shapes;
11

12
namespace PauchiaUkladka;
13

14
/// <summary>
15
/// Interaction logic for MainWindow.xaml
16
/// </summary>
17
public partial class MainWindow : Window
18
{
19
    private readonly ImageSource[] tileImages = new ImageSource[]
20
    {
21
        new BitmapImage(new Uri("Assets/TileEmpty.png", UriKind.Relative)),
22
        new BitmapImage(new Uri("Assets/TileCyan.png", UriKind.Relative)),
23
        new BitmapImage(new Uri("Assets/TileBlue.png", UriKind.Relative)),
24
        new BitmapImage(new Uri("Assets/TileOrange.png", UriKind.Relative)),
25
        new BitmapImage(new Uri("Assets/TileYellow.png", UriKind.Relative)),
26
        new BitmapImage(new Uri("Assets/TileGreen.png", UriKind.Relative)),
27
        new BitmapImage(new Uri("Assets/TilePurple.png", UriKind.Relative)),
28
        new BitmapImage(new Uri("Assets/TileRed.png", UriKind.Relative))
29
    };
30

31
    private readonly ImageSource[] blockImages = new ImageSource[]
32
    {
33
        new BitmapImage(new Uri("Assets/Block-Empty.png", UriKind.Relative)),
34
        new BitmapImage(new Uri("Assets/Block-I.png", UriKind.Relative)),
35
        new BitmapImage(new Uri("Assets/Block-J.png", UriKind.Relative)),
36
        new BitmapImage(new Uri("Assets/Block-L.png", UriKind.Relative)),
37
        new BitmapImage(new Uri("Assets/Block-O.png", UriKind.Relative)),
38
        new BitmapImage(new Uri("Assets/Block-S.png", UriKind.Relative)),
39
        new BitmapImage(new Uri("Assets/Block-T.png", UriKind.Relative)),
40
        new BitmapImage(new Uri("Assets/Block-Z.png", UriKind.Relative))
41
    };
42

43
    private readonly Image[,] imageControls;
44

45
    private readonly int maxDelay = 1000;
46
    private readonly int minDelay = 100;
47
    private readonly int delayDecrease = 25;
48

49
    private GameState gameState = new GameState();
50
    
51
    public MainWindow()
52
    {
53
        InitializeComponent();
54
        imageControls = SetupGameCanvas(gameState.GameGrid);
55
    }
56

57
    private Image[,] SetupGameCanvas(GameGrid grid) //Двумерный массив для отрисовки поля
58
    {
59
        Image[,] imageControls = new Image[grid.Rows, grid.Colums]; //Создаём поле
60
        int cellSize = 25; //Размер каждого блока (размер поля 250 на 500). Если разделить на 25 — 10 на 20.
61

62
        for (int r = 0; r < grid.Rows; r++) //Перебираем строки
63
        {
64
            for (int c = 0; c < grid.Colums; c++) //Перебираем колонки (вместе со строками — перебираем каждый блок)
65
            {
66
                Image imageControl = new Image //Создаём новую картинку с заданными размерами
67
                {
68
                    Width = cellSize, //Размеры указываем по 25 пикселей в ширину
69
                    Height = cellSize //и высоту
70
                };
71
                
72
                Canvas.SetTop(imageControl, (r - 2) * cellSize + 10); //Отрисовываем поле начиная сверзху и скрываем 2 строки в самом верху
73
                Canvas.SetLeft(imageControl, c * cellSize); //Отрисовываем поле начиная слева (обычно, указывается 2 направления отрисовки в 2D и три в 3D) и по размерам — равно количеству колонок
74
                GameCanvas.Children.Add(imageControl); //Отрисовка по заданным параметрам...
75
                imageControls[r, c] = imageControl; //... размером r на c (то есть числом наших строк и столбцов)
76
            }
77
        }
78

79
        return imageControls; //Возврат отрисованного изображения
80
    }
81

82
    private void DrawGrid(GameGrid grid)
83
    {
84
        for (int r = 0; r < grid.Rows; r++)
85
        {
86
            for (int c = 0; c < grid.Colums; c++)
87
            {
88
                int id = grid[r, c];
89
                imageControls[r, c].Opacity = 1;
90
                imageControls[r, c].Source = tileImages[id];
91
            }            
92
        }
93
    }
94

95
    private void DrawBlock(Block block)
96
    {
97
        foreach (Position p in block.TilePositions())
98
        {
99
            imageControls[p.Row, p.Column].Opacity = 1;
100
            imageControls[p.Row, p.Column].Source = tileImages[block.Id];
101
        }
102
    }
103
    
104
    private void DrawNextBlock(BlockQueue blockQueue)
105
    {
106
        Block next = blockQueue.NextBlock;
107
        NextImage.Source = blockImages[next.Id];
108
    }
109

110
    private void DrawHeldBlock(Block heldBlock)
111
    {
112
        if (heldBlock == null)
113
        {
114
            HoldImage.Source = blockImages[0];
115
        }
116
        else
117
        {
118
            HoldImage.Source = blockImages[heldBlock.Id];
119
        }
120
    }
121

122
    private void Draw(GameState gameState)
123
    {
124
        DrawGrid(gameState.GameGrid);
125
        DrawGhostBlock(gameState.CurrentBlock);
126
        DrawBlock(gameState.CurrentBlock);
127
        DrawNextBlock(gameState.BlockQueue);
128
        DrawHeldBlock(gameState.HeldBlock);
129
        ScoreText.Text = $"Очки: {gameState.Score}";
130
    }
131

132
    private void DrawGhostBlock(Block block)
133
    {
134
        int dropDistance = gameState.BlockDropDistance();
135

136
        foreach (Position p in block.TilePositions())
137
        {
138
            imageControls[p.Row + dropDistance, p.Column].Opacity = 0.25;
139
            imageControls[p.Row + dropDistance, p.Column].Source = tileImages[block.Id];
140
        }
141
    }
142

143
    private async Task GameLoop()
144
    {
145
        Draw(gameState);
146

147
        while (gameState.GameOver == false)
148
        {
149
            int delay = Math.Max(minDelay, maxDelay - (gameState.Score * delayDecrease));
150
            await Task.Delay(delay);
151
            gameState.MoveBlockDown();
152
            Draw(gameState);
153
        }
154

155
        GameOverMenu.Visibility = Visibility.Visible;
156
        FinalScoreText.Text = $"Очки: {gameState.Score}";
157
    }
158
    
159
    private void Window_KeyDown(object sender, KeyEventArgs e)
160
    {
161
        if (gameState.GameOver)
162
        {
163
            return;
164
        }
165

166
        switch (e.Key)
167
        {
168
            case Key.Left:
169
                gameState.MoveBlockLeft();
170
                break;
171
            case Key.Right:
172
                gameState.MoveBlockRight();
173
                break;
174
            case Key.Down:
175
                gameState.MoveBlockDown();
176
                break;
177
            case Key.Up:
178
                gameState.RotateBlockCW();
179
                break;
180
            case Key.Z:
181
                gameState.RotateBlockCCW();
182
                break;
183
            case Key.C:
184
                gameState.HoldBlock();
185
                break;
186
            case Key.Space:
187
                gameState.DropBlock();
188
                break;
189
            default:
190
                return;
191
        }
192
        Draw(gameState);
193
    }
194

195
    private async void GameCanvas_Loaded(object sender, RoutedEventArgs e)
196
    {
197
        await GameLoop();
198
    }
199

200
    private async void PlayAgain_Click(object sender, RoutedEventArgs e)
201
    {
202
        gameState = new GameState();
203
        GameOverMenu.Visibility = Visibility.Hidden;
204
        await GameLoop();
205
    }
206
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.