简体   繁体   中英

2d array TicTacToe logic and syntax issues in Java

I'm having trouble creating a TicTacToe program for my class. It's a 4 x 4 board. My variables for my win condition method victoire () are giving me an error. The code has to be written in french for my variables, methods, etc. by convention because of where I live, so sorry in advance.

The errors are :

Multiple markers at this line - colonne2 cannot be resolved to a variable - ligne2 cannot be resolved to a variable

Lines 156 and 162 respectively

and the warnings are :

The value of the local variable colonne2 is not used

The value of the local variable ligne2 is not used

Lines 194 and 195 respectively

Here is my code :

package td;

import java.util.Random;
import java.util.Scanner;

public class Main {


    // Initialisation des variables
    public static String ligne, colonne;
    public static Scanner scan;
    public static char[][] tableau = new char[4][4];
    public static char tourJoueur = 'O';
    public static Random rand;
    public static int scoreJ1;
    public static int scoreJ2;
    public static String nomJoueur1;
    public static String nomJoueur2;

    public static void main(String[] args) {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                tableau[i][j] = ' ';
                // Introduction avant les jeux
                menuIntroduction();

                // Toutes les parties
                plusieursParties();

                // Message final
                menuFin();
            }
        }
    }

    private static void menuIntroduction() {
        printIntro();

        scoreJ1 = 0;
        scoreJ2 = 0;

        // Initialisation du Scanner
        scan = new Scanner(System.in);

        // Recuperation des noms des joueurs
        System.out.println("Joueur 1 rentrez votre nom");
        nomJoueur1 = scan.nextLine();

        System.out.println("Joueur 2 rentrez votre nom");
        nomJoueur2 = scan.nextLine();

        // Choix du premier joueur au hasard
        Random rand = new Random();
        if (rand.nextInt() % 2 == 0) {
            tourJoueur = 'O';
        } else {
            tourJoueur = 'X';

        }
    }

    private static void printIntro() {
        System.out.println("BIENVENU AU TIC TAC TOE!\n");
        System.out.println("Chaque joueur se fera assigner 'X' ou 'O'\n");
        System.out.println("Chaque joueur selectionnera une case dans le Tic Tac Toe.\n");
        System.out.println(
                "Il faudra selectionner une ligne (de 0-3) et peser sur ENTER. Il faudra ensuite selectionner une colonne et peser sur ENTER\n");
        System.out.println("Chaque joueur se fera assigner 'X' ou 'O', débutant par le joueur 1\n");
        System.out.println(
                "Pour gagner, il faudra compléter une ligne du tableau avec 'X' ou 'O', soit verticalement, soit horizontalement, soit diagonalement\n");
        System.out.println("Si le tableau est plein et qu'aucun joueur n'a fait de ligne, la partie sera nulle\n");
        System.out.println("Chaque partie gagnée donnera un point au joueur vainqueur\n");
        System.out.println("Bonne partie!");
        System.out.println();
        System.out.println("========================================================\n\n\n");

    }

    private static void menuFin() {
        System.out.println("=========================FIN DU JEU=========================\n\n\n");
        System.out.println("merci à " + nomJoueur1 + " et " + nomJoueur2 + " d'avoir joué ! ");

        // message de fin different selon le joueur gagnant ou s'il y a égalité
        if (scoreJ1 > scoreJ2) {
            System.out.println(nomJoueur1 + " l'emporte à " + scoreJ1 + " contre " + scoreJ2);
        } else if (scoreJ2 > scoreJ1) {
            System.out.println(nomJoueur2 + " l'emporte à " + scoreJ2 + " contre " + scoreJ1);

        } else {
            System.out.println("Égalité! " + scoreJ1 + " point(s) au total!");
        }
        System.out.println("\n\n\n\nÀ bientôt!");

    }

    private static void plusieursParties() {
        do {

            jouerUnePartie(tourJoueur);

        } while (onContinue());
    }

    private static boolean onContinue() {
        boolean inputContinue = false;
        boolean entreeIncorrecte = true;

        // tant que l'utilisateur ecrit n'importe quoi on lui redemande de faire un
        // choix
        do {
            System.out.println("les scores sont : ");
            System.out.println(nomJoueur1 + " : " + scoreJ1 + "  |||  " + nomJoueur2 + " : " + scoreJ2);
            System.out.println("voulez - vous continuer ? [Oui/Non]");

            String reponseUser = scan.nextLine();

            // cas un et deux reponse valide et transmise, cas trois le user dit n'importe
            // quoi
            if (reponseUser.equals("Oui")) {
                inputContinue = true;
                entreeIncorrecte = false;
            } else if (reponseUser.equals("Non")) {
                inputContinue = false;
                entreeIncorrecte = false;
            } else {
                System.out.println("Erreur, entrez 'Oui' ou 'Non'");
                entreeIncorrecte = true;
            }

        } while (entreeIncorrecte);

        // on renvoie la reponse de l'utilisateur lorsqu'elle est valide
        return inputContinue;
    }

    private static void jouerUnePartie(char tourJoueur1) {
        System.out.println("C'est au tour de " + nomJoueur1 + "!" + "Tu joues " + tourJoueur + "!\n");
        System.out.println("Entre une ligne et pèse sur ENTER");
        System.out.println("Entre une colonne et pèse sur ENTER");

        afficherTableau();

        // Verifie si l'utilisateur utilise un chiffre et non quelque chose d'autre pour
        // ligne et pour colonne
        boolean jouant = true;
        do {
            afficherTableau();
            verifierEntree();

        }while (jouant); {
            //Je ne comprends pas pourquoi il rale ici
                tableau[ligne2][colonne2] = tourJoueur;
                if (victoire(scoreJ1, scoreJ1) && !tableauPlein()) {
                    System.out.println("Felicitations! Le joueur " + tourJoueur + " gagne!");
                    jouant = false;
                }
            //Meme chose ici
                if (!victoire(ligne2, colonne2) && tableauPlein()) {
                    System.out.println("Partie nulle!");
                    jouant = false;
                } else {
                    jouant = true;
                }
                if (tourJoueur == 'O') {
                    tourJoueur = 'X';
                } else {
                    tourJoueur = 'O';
                }

        }
    }

    private static void verifierEntree() {
        boolean entreeIncorrecte = true;
        while (entreeIncorrecte) {

            ligne = scan.nextLine();
            colonne = scan.nextLine();

            if (ligne.equals("0") || ligne.equals("1") || ligne.equals("2") || ligne.equals("3")) {
                entreeIncorrecte = false;
            } else if (colonne.equals("0") || colonne.equals("1") || colonne.equals("2") || colonne.equals("3")) {
                entreeIncorrecte = false;
            } else {
                System.out.println("Mauvaise entree! Recommence! ");
                entreeIncorrecte = true;
            }
            if (!entreeIncorrecte) {
                //Comment colonne2 et ligne 2 ne sont pas utilisés?
                int colonne2 = Integer.parseInt(colonne);
                int ligne2 = Integer.parseInt(ligne);
            }
        }
    }

    private static boolean victoire(int ligne2, int colonne2) {

        // Verifie horizontalement la victoire

        if (tableau[0][colonne2] == tableau[1][colonne2] && tableau[0][colonne2] == tableau[2][colonne2]
                && tableau[0][colonne2] == tableau[3][colonne2])
            return true;

        // Verifie verticalement la victoire

        if (tableau[ligne2][0] == tableau[ligne2][1] && tableau[ligne2][0] == tableau[ligne2][2]
                && tableau[ligne2][0] == tableau[ligne2][3])
            return true;

        // Verifie diagonalement vers la droite la victoire

        if (tableau[0][0] == tableau[1][1] && tableau[0][0] == tableau[2][2] && tableau[0][0] == tableau[3][3]
                && tableau[1][1] != ' ')
            return true;

        // Verifie diagonalement vers la gauche la victoire

        if (tableau[0][3] == tableau[1][2] && tableau[0][3] == tableau[2][1] && tableau[0][3] == tableau[3][0]
                && tableau[1][2] != ' ')
            return true;
        if (tableauPlein())
            return true;
        return false;
    }

    private static boolean tableauPlein() {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (tableau[i][j] == ' ') {
                    // Un tour peut etre fait, tableau non vide
                    return false;
                }
            }
        }
        return true;

    }

    private static void afficherTableau() {
        for (int i = 0; i < 4; i++) {
            System.out.println();
            for (int j = 0; j < 4; j++) {
                if (j == 0) {
                    System.out.print(" |");
                }
                System.out.print(tableau[i][j] + " |");
            }
        }
        System.out.println();
    }
}

Warnings:

For this chunk of code

if (!entreeIncorrecte) {
    //Comment colonne2 et ligne 2 ne sont pas utilisés?
    int colonne2 = Integer.parseInt(colonne);
    int ligne2 = Integer.parseInt(ligne);
}

You are declaring two new variables here, but you aren't using them. This means the declarations are effectively useless. When you declare a variable and assign it a value, it lasts until the end of the block. At the end of the block, it is destroyed. You can't refer to it anymore.

This is why you are getting a warning, because the code doesn't use those variables.

Compiler errors:

Looking at the code you pasted, we have:

//Je ne comprends pas pourquoi il rale ici
tableau[ligne2][colonne2] = tourJoueur;

The code here calls on ligne2 and colonne2 as variables, however you never declare them anywhere inside the method jouerUnePartie , so the compiler cannot find them and errors out. To fix these errors, you need to declare the variable (and assign it in the case of primitives like int ) before you use them.

The fix for this is to create the variables and give them values before you refer to them. Whether you do this in the method itself, or make them a static global variable inside of Main is up to you, but you probably do not want to do the static global variable thing unless you have a very good reason (and if you're asking yourself right now "do I have a good reason?" then you very likely don't). The best way is to either calculate them in the function, or to pass them into the method as arguments. This of course depends on what you are trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM