Tick Tack Toe

Recommended levellevel
5+
Tic-tac-toe [1] is a logical game between two opponents on a square field of 3 by 3 cells or larger (up to an “endless field”). One of the players plays with "crosses", the second - with "toes". The traditional Chinese game Gomoku uses black and white stones. Players take turns placing signs on the free cells of the 3x3 field (one is always crosses, the other is always zeros). The first one to line up 3 of his pieces vertically, horizontally or large diagonally wins. If the players have filled in all 9 cells and it turns out that there are no three identical symbols in any vertical, horizontal or large diagonal, the game is considered to be a draw. The first move is made by the player placing crosses. Usually, at the end of the game, the winning side crosses out its three signs (a zero or a cross), which make up a continuous row. Exchange icons It is possible to override the rule that tells players to only place their own type of icon. For example, a game option could be: players put a cross or a zero (whatever they want); the first one wins if he builds a line of the required length from identical icons, the second one wins if this does not happen before filling the field. Another option: “your” icon changes with each move. Super tic-tac-toe The game consists of nine tic-tac-toe boards arranged in a 3×3 grid. Players take turns playing on the smaller tic-tac-toe boards until one of them wins on the larger tic-tac-toe board. Compared to traditional tic-tac-toe, the strategy in this game is conceptually more complex and has proven to be more challenging for computers.
Comments (38)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
21 April, 17:28
Метод викликається, але перевірка не проходить
Jandar
Level 1
21 April, 14:59
Зробив, як написано, а видає цю помилку: Метод повинен містити код, що виконується, або його слід оголосити абстрактним. файл ua/javarush/games/ticktacktoe/TicTacToeGame.java, рядок 7, позиція 147
Денис
Level 22
20 April, 15:22
Помогите с этим методом, если ячейка равна нулю то пишу в ней "X" или "O" , когда нажимаю на ячейку не во всех ячейках появляется "X" или "O"
// отображение только одной ячейки
    public void updateCellView(int x, int y, int value) {
        // установка текста в ячейке метод setCellValue(x, y, text)
// когда без этого условия, то все отлично расставляет знаки
        if (x != 0 && y != 0) { // если ячейка не равна нулю
            return;
        }
        if (value  == 0) {
              setCellValueEx(x, y, Color.WHITE, " ", Color.WHITE);
        } else if (value == 1) {
            setCellValueEx(x, y, Color.WHITE, "X", Color.RED);
        } else if (value == 2) {
            setCellValueEx(x, y, Color.WHITE, "O", Color.BLUE);
        } else {
            setCellValueEx(x, y, Color.WHITE, "", Color.WHITE);
        }
    }
Денис
Level 22
20 April, 16:35
Вообщем проверку надо вставлять в метод onMouseLeftClick
24 April, 13:43
а для чего вообще эта проверка у вас?
Денис
Level 22
24 April, 15:41
// если ячейка не ноль, то ретурн
        if (model[x][y] != 0) {
            return;
        }
Nozim
Level 11
30 March, 06:00
public void onKeyPress(Key key) {
        if (key == Key.ESCAPE) {
            startGame();
            updateView();
        }
        if (key == Key.SPACE) {
            startGame();
            updateView();
        }
    }
Почему не проходит?
Михаил
Level 31
3 April, 22:25
У проверки нажатия пробела нахватает проверки что игра остановлена
Irina бухгалтер at Тандер АО
28 March, 08:07
В своей реализации игры я добавила сообщение в начале игры и изменила надпись "Ничья".
Alexey
Level 3
26 March, 16:54
public boolean checkWin(int x, int y, int n) {
    boolean winX = true;
    boolean winY = true;
    boolean winD1 = true;
    boolean winD2 = true;
    int l = model.length - 1;

    for(int i = 0; i < model.length; i++) {
        winX = model[x][i] == n && winX;
        winY = model[i][y] == n && winY;
        winD1 = model[i][i] == n && winD1;
        winD2 = model[i][l-i] == n && winD2;
    };

    return winX || winY || winD1 || winD2;
}
26 March, 12:48
есть ли способы сократить код или другие методы?(хотелось бы узнать)
public boolean checkWin(int x, int y, int n){
        if (model[x][0] == n && model[x][1] == n && model[x][2] == n)
        return true;
        if (model[0][y] == n && model[1][y] == n && model[2][y] == n)
        return true;
        if (model[0][0] == n && model[1][1] == n && model[2][2] == n)
        return true;
        if (model[2][2] == n && model[1][1] == n && model[0][0] == n)
        return true;
         if (model[0][2] == n && model[1][1] == n && model[2][0] == n)
        return true;
        if (model[2][0] == n && model[1][1] == n && model[0][2] == n)
        return true;

        return false;
Лёля
Level 26
Expert
26 March, 16:06
Думаю можно объединить арифметику поиграв с count, но сходу не придумалось. Ещё короче, без кучи циклов, это вместо count завести четыре переменных, например countX, countY, countD, countD2 и все их прогнать в одном цикле, а после все значения прогнать через if и ||, но тогда работать будет дольше за счёт возможных лишних прогонов, зато код будет визуально короче. Ну и если закинуть размер в переменную, то можно такой код масштабировать на любое количество клеток, поправив всего пару мест, в отличие от готового решения.
public boolean checkWin(int x, int y, int n) {
    int count = 0;

    for (int i = 0; i < 3; i++) {
        count = model[x][i] == n ? ++count : 0;
    }
    if (count == 3) return true;

    count = 0;

    for (int i = 0; i < 3; i++) {
        count = model[i][y] == n ? ++count : 0;
    }
    if (count == 3) return true;

    count = 0;
    for (int i = 0; i < 3; i++) {
        count = model[i][i] == n ? ++count : 0;
    }
    if (count == 3) return true;

    count = 0;
    for (int i = 0; i < 3; i++) {
        count = model[2-i][i] == n ? ++count : 0;
    }
    if (count == 3) return true;
    return false;
}
26 March, 19:40
Нужно ли дублировать проверку одной и той же диагонали? if (model[0][0] == n && model[1][1] == n && model[2][2] == n) return true; if (model[2][2] == n && model[1][1] == n && model[0][0] == n) return true; в коде третий и четвертый if проверяют одно и то же, пятый и шестой if также проверяют одну и ту же диагональ . дублирование проверки можно убрать
Александр Крылов Full Stack Developer at MKB
10 April, 18:05
public boolean checkWin(int x, int y, int n) {
        boolean resX = true, resY = true, resD = true, resD2 = true;
        for (int i = 0; i < SIZE; i++) {
            resX = resX && model[i][y] == n;
            resY = resY && model[x][i] == n;
            resD = resD && model[i][i] == n;
            resD2 = resD2 && model[i][SIZE - 1 - i] == n;
        }
        return resX || resY || resD || resD2;
    }
Примечание: если одна из переменных res будет false, то на следующем витке цикла в присваивании этой переменной java не будет выполнять условие model[][] == n, так как false && ??? = false
Alex
Level 41
23 April, 10:43
1) Duplicate Checks: Some checks are duplicated. For example, you check for the same diagonal twice (model[0][0] == n && model[1][1] == n && model[2][2] == n and model[2][2] == n && model[1][1] == n && model[0][0] == n). Similarly, you check for both diagonals separately. 2) Logic for Diagonal Check: The diagonal checks (model[0][0] == n && model[1][1] == n && model[2][2] == n and model[0][2] == n && model[1][1] == n && model[2][0] == n) are incorrect. You have (2,2) and (0,0) twice, which should be replaced with (0,2) and (2,0) respectively.
25 March, 16:11
https://javarush.com/projects/apps/497871
Satenik
Level 1
25 March, 13:12
24 March, 17:17
public void initialize(){
        setScreenSize(3,3);
        startGame();
        updateView();
    }
почему не засчитывает?
24 March, 18:52
1. public void initialize() { 2. setScreenSize(3, 3); Остальное всё правильно