rendered paste bodyimport javax.swing.JOptionPane;
public class Puissance4
{
public static int pos = 0;
public static void initialisation(char tab[][])
{
//remplissage
//la premiere dimension du tableau est le nombre de rangees,
//en faisant tab.length, on obtient le nombre de rangees.
//on boucle sur chacune des rangees.
for( int i = 0 ; i< tab.length; i++)
{
//on boucle sur chacun des elements de la rangees i.
//en faisant tab[i].length, on obtient le nombre de colonnes
for(int j = 0; j< tab[i].length; j++)
{
//on met un caractere '.' a la ieme rangee,
//jieme colonne du tableau tab
tab[i][j] = '.';
}
}
}
public static void afficher(char tab[][])
{
System.out.println(" 1 2 3 4 5 6 7");
for(int i = 0; i< tab.length; i++)
{
System.out.print(i+1 + " ");
for(int j = 0; j< tab[i].length; j++)
System.out.print( tab[i][j]+ " " );
System.out.println();
}
System.out.println();
}
public static void jouer(char tab[][], char j1, char caractere, int joueurActif)
{
//System.out.print("Joueur 1 colonne? ");
//int pos = Keyboard.readInt();
if (joueurActif == 1) {
pos = Integer.parseInt(JOptionPane.showInputDialog(null, "Joueur 1 colonne?"));
}
else {
pos = Integer.parseInt(JOptionPane.showInputDialog(null, "Joueur 2 colonne?"));
}
while(!(pos == 1 || pos == 2 || pos == 3 || pos == 4
|| pos == 5 || pos == 6 || pos == 7))
{
System.out.println("Colonne hors du tableau. " +
"Choisissez une autre colonne.");
if (joueurActif == 1) {
pos = Integer.parseInt(JOptionPane.showInputDialog(null, "Joueur 1 colonne?"));
}
else {
pos = Integer.parseInt(JOptionPane.showInputDialog(null, "Joueur 2 colonne?"));
}
}
while(tab[0][pos-1] != '.')
{
System.out.println("Colonne pleine. " +
"Choisissez une autre colonne.");
if (joueurActif == 1) {
pos = Integer.parseInt(JOptionPane.showInputDialog(null, "Joueur 1 colonne?"));
}
else {
pos = Integer.parseInt(JOptionPane.showInputDialog(null, "Joueur 2 colonne?"));
}
}
for(int i = tab.length - 1; i >= 0; i--)
{
if(tab[i][pos-1] == '.')
{
tab[i][pos-1] = caractere;
System.out.println(">> " + caractere + " " + pos + " " + (i+1));
break;
}
}
}
public static boolean verifligne(char tab[][], int pos, char comparer)
{
int lig = 0;
for(int i = 0; i < tab.length; i++)
if(tab[i][pos-1] == comparer)
{
lig = i;
break;
}
if (lig < (tab.length -3)) {
if(tab[lig+1][pos-1] == comparer && tab[lig+2][pos-1] == comparer && tab[lig+3][pos-1] == comparer)
return true;
else return false;
}
else {
return false;
}
}
public static final int nombreDeLignes = 6;
public static final int nombreDeColonnes = 7;
public static void main(String [] args)
{
char j1 = 'h';
char j2 = 'h';
char[][] tab = new char[nombreDeLignes][nombreDeColonnes];
initialisation(tab);
afficher(tab);
while(true)
{
jouer(tab,j1, 'X', 1);
afficher(tab);
if(verifligne(tab,pos, 'X'))
break;
jouer(tab,j2, 'O', 2);
afficher(tab);
}
System.out.println("FINI");
}
}