Крестики-нолики (часть 1)

3
  • 1 favourites

Index

Tagged

Attached Files

The following files have been attached to this tutorial:

.zip
.capx

tictactoe-part1-a.capx

Download now 880.66 KB
.capx

tictactoe-part1-b.capx

Download now 881.78 KB

Stats

3,540 visits, 5,795 views

Tools

License

This tutorial is licensed under CC BY 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Часть 1 - Создание игры с двумя игроками "Крестики-нолики".

Я собираюсь описать шаги и логику здесь, а не детализировать каждый отдельный шаг процесса. В массивы много индексирования, поэтому я попытаюсь изо всех сил объяснить это.

Готовая Игра

Часть 2 добавит ИИ для игры против компьютера.

Необходимые условия

rexrainbow's Board - Board

rexrainbow's SquareTx - SquareTx

Файлы

4frame-32x32.gif, background-blue.png, GameOver1.wav, OooScary1.wav, WinnerMarks.gif

Основная игра

Я поместил 4 кадра в первый файл, но мы выборочно выбираем соответствующие кадры для спрайта. Было удобно строить их вместе. Фон, который я получил от векторного сайта, который часто предлагает бесплатные векторные файлы (www.vectorstock.com). The marks file I created myself, again compiling all of the various "lines" that mark a win as frames.

Прежде чем мы начнем, немного пояснений по логике. Крестики-нолики представляет собой сетку 3x3. Мы можем указать эту сетку либо как x столбцов по y строк, либо пронумеровать по отдельности. Большинство алгоритмов Крестики-нолики фактически используют схему с номером 1-9. Я намеренно использую оба, чтобы сделать несколько очков. Преобразовать массивы Construct2 через(X,Y,Z). Переведя системы координат, получим (используя только (X,Y)):

1 является (0,0)

2 является (1,0)

3 является (2,0)

4 является (0,1)

5 является (1,1)

6 iявляется (2,1)

7 является (0,2)

8 является (1,2)

9 является (2,2)

Победители Крестики-нолики легко идентифицируются со следующими наборами (опять же используя схему 1-9):

{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8}, {3,6,9}, {1,5,9}, {3,5,7}. Побеждают восемь комбинаций.

Каждый из них идентифицирует три квадрата, необходимых для победы, одним игроком, по горизонтали, вертикали или по диагонали. Зная это, нетрудно обнаружить победителя - вы просто заполняете массив / сетку текущей игры, так как каждый игрок выбирает квадрат, а затем проверяет сетку текущей игры для каждой из этих комбинаций, а если обнаруживается, игра заканчивается , и объявлен победитель.

Давайте начнем

Create a new project. Name it.

Create 3 more layers. Name them: Background (0), Board (1), Mark (2), DEBUG (3).

Select the Background layer.

Insert a Tiled Background from background-blue.png. Set the Position to: 0,0. Set the size to: 640,480.

Insert a Sprite from file 4frame-32x32.gif. We need the next step of loading the animations by importing the frames from the animation window. Delete the first frame, as it is now a duplicate, and delete the last two frames. We keep the gray and the white images. Name this spite: Tile.

Insert a second Sprite and load the animations the same as above. Delete everything but the X frame. Name it ChessX. Insert a third Sprite for O.

Insert another sprite, choosing WinnerMarks.gif, and import all of the frames as before. Name: WinnerMarks.

Insert the Board object and the SquareTx object.

Select Board from the Object Types folder in the Projects panel. Set Width=3, Height=3. We need an instance variable, so add: CurrentTurnIsX, Type=Boolean, Initial value=true.

Select SquareTx and set Width = 36, Height=36

Insert: Button – Name: RestartButton, Position: 285, 412, Text: Restart

Insert: Text, Name=WinnerText, Position=220,62, Size: 200,52. Font: Arial, Regular, 20, Color: Choose Other, then Custom, then for Red,Green,Blue: type 255,0,0, and set Horizontal alignment: Center. Set Text: <winnertext>

Insert: Data & Storage: Array, Insert. Rename it to Winners. (Don’t worry about the dimensions. We load this in from a JSON string).

Insert: Data & Storage: Array, Insert. Rename it to CurrentPlay. Width=3, Height=3 (leave Depth=1).

Insert new object: Input: Mouse.

I’ve also got a LogText object, used for debugging the game. This can always be made invisible when you are ready to release the game. Just place it on the right and size as you like. We use this to show the values in the CurrentPlay array to watch the data change. Set Text: <log>.

At this point we have all of our elements. Let’s shift them to the correct layers now by changing the Layer property of each object.

Click on each item in the Objects panel and set it’s Layer property, bottom to top. WinnerText: Mark, WinnerMarks: Mark. TiledBackground: Background, Tile: Board, (skip SquareTx, it isn’t on a layer), RestartButton on Mark, LogText: DEBUG, (skip CurrentPlay), ChessX and ChessO: Board, (and skip Board).

If you press Run at this point you just see a pretty background and a Restart button (and the two text fields). We’re getting to the board layout.

  • 0 Comments

  • Order by
Want to leave a comment? Login or Register an account!