Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. public static void jogoDaVelha2Players(char matriz[][]) {
  2. System.out.print("JOGO DA VELHA 2 PLAYERS\n");
  3. int jogador = 1;
  4. int linha;
  5. int coluna;
  6. int contador = 0;
  7.  
  8. while(!acabou(matriz)) {
  9. if(contador == 9) {
  10. System.out.println("\nVelha!");
  11. break;
  12. }
  13.  
  14. System.out.print("\nDigite a linha (jogador " + jogador + "): ");
  15. linha = in.nextInt();
  16.  
  17. System.out.print("Digite a coluna (jogador " + jogador + "): ");
  18. coluna = in.nextInt();
  19.  
  20. if(matriz[linha][coluna] == 'x' || matriz[linha][coluna] == 'o') {
  21. System.out.println("Esta posição já possui valor! Por favor, digite outra.");
  22. continue;
  23. }
  24.  
  25. if(!(linha > 2 || coluna > 2 || linha < 0 || coluna < 0)) {
  26. if(jogador == 1) {
  27. matriz[linha][coluna] = 'x';
  28. jogador = 2;
  29. } else {
  30. matriz[linha][coluna] = 'o';
  31. jogador = 1;
  32. }
  33. listaMatrizJogoDaVelha(matriz);
  34. contador++;
  35. } else {
  36. System.out.print("Erro! Por favor, digite valores de 0 a 2.");
  37. }
  38. }
  39. }
  40.  
  41. public static boolean acabou(char matriz[][]) {
  42. ArrayList<Character> linha = new ArrayList<>();
  43. ArrayList<Character> coluna = new ArrayList<>();
  44. ArrayList<Character> diagonalPrincipal = new ArrayList<>();
  45. ArrayList<Character> diagonalSecundaria = new ArrayList<>();
  46.  
  47. for(int i=0; i<matriz.length; i++) {
  48. linha.clear();
  49. coluna.clear();
  50. for(int j=0; j<matriz.length; j++) {
  51. linha.add(matriz[i][j]);
  52. coluna.add(matriz[j][i]);
  53. if(i == j) {
  54. diagonalPrincipal.add(matriz[i][j]);
  55. }
  56. if(i + j == 2) {
  57. diagonalSecundaria.add(matriz[i][j]);
  58. }
  59. }
  60. if(verificaVitoria(linha) || verificaVitoria(diagonalPrincipal) || verificaVitoria(diagonalSecundaria) || verificaVitoria(coluna)) {
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66.  
  67. public static boolean verificaVitoria(ArrayList<Character> sequencia) {
  68. int ocorrenciasX = Collections.frequency(sequencia, 'x');
  69. int ocorrenciasO = Collections.frequency(sequencia, 'o');
  70. if(ocorrenciasX == 3) {
  71. System.out.println("Jogador 1 venceu!");
  72. return true;
  73. } else if(ocorrenciasO == 3) {
  74. System.out.println("Jogador 2 venceu!");
  75. return true;
  76. } else {
  77. return false;
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement