-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatalhaNavalGUI.java
More file actions
143 lines (116 loc) · 5.24 KB
/
BatalhaNavalGUI.java
File metadata and controls
143 lines (116 loc) · 5.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
// BatalhaNavalGUI.java
import java.awt.*;
import javax.swing.*;
public class BatalhaNavalGUI extends JFrame {
private static final int TAMANHO_TABULEIRO = 5;
private static final int MAX_TENTATIVAS = 4;
private Tabuleiro tabuleiro;
private int tentativasRestantes;
private JButton[][] botoesDoTabuleiro;
private JLabel labelStatus;
private JButton botaoNovoJogo;
public BatalhaNavalGUI() {
// Configurações da janela principal
super("Batalha Naval"); // Título da janela
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 600);
setLayout(new BorderLayout());
setLocationRelativeTo(null); // Centraliza a janela
tabuleiro = new Tabuleiro(TAMANHO_TABULEIRO);
inicializarComponentes();
iniciarNovoJogo();
}
private void inicializarComponentes() {
// Painel para o grid de botões
JPanel painelTabuleiro = new JPanel();
painelTabuleiro.setLayout(new GridLayout(TAMANHO_TABULEIRO, TAMANHO_TABULEIRO));
botoesDoTabuleiro = new JButton[TAMANHO_TABULEIRO][TAMANHO_TABULEIRO];
for (int i = 0; i < TAMANHO_TABULEIRO; i++) {
for (int j = 0; j < TAMANHO_TABULEIRO; j++) {
JButton botao = new JButton();
botao.setFont(new Font("Arial", Font.BOLD, 36));
final int linha = i;
final int coluna = j;
// Ação a ser executada quando um botão for clicado
botao.addActionListener(e -> botaoPressionado(linha, coluna));
botoesDoTabuleiro[i][j] = botao;
painelTabuleiro.add(botao);
}
}
add(painelTabuleiro, BorderLayout.CENTER);
// Painel inferior para status e botão de novo jogo
JPanel painelInferior = new JPanel();
painelInferior.setLayout(new BorderLayout());
labelStatus = new JLabel("Bem-vindo! Clique em uma posição para atacar.", SwingConstants.CENTER);
labelStatus.setFont(new Font("Arial", Font.PLAIN, 16));
painelInferior.add(labelStatus, BorderLayout.CENTER);
botaoNovoJogo = new JButton("Novo Jogo");
botaoNovoJogo.addActionListener(e -> iniciarNovoJogo());
painelInferior.add(botaoNovoJogo, BorderLayout.SOUTH);
add(painelInferior, BorderLayout.SOUTH);
}
private void iniciarNovoJogo() {
tabuleiro.reset();
tentativasRestantes = MAX_TENTATIVAS;
// Reseta a aparência de todos os botões
for (int i = 0; i < TAMANHO_TABULEIRO; i++) {
for (int j = 0; j < TAMANHO_TABULEIRO; j++) {
botoesDoTabuleiro[i][j].setEnabled(true);
botoesDoTabuleiro[i][j].setText("");
botoesDoTabuleiro[i][j].setBackground(null);
}
}
// Embora as coordenadas internas sejam de 0-4, a mensagem para o usuário é de 1-5
labelStatus.setText(String.format("Acerte o navio (1x1) em %d tentativas! Linhas/Colunas de 1 a 5.", MAX_TENTATIVAS));
}
private void botaoPressionado(int linha, int coluna) {
if (tentativasRestantes <= 0) {
return; // Jogo já acabou
}
JButton botaoClicado = botoesDoTabuleiro[linha][coluna];
// Impede que o mesmo botão seja clicado duas vezes
if (!botaoClicado.isEnabled()) {
return;
}
char resultado = tabuleiro.verificarAtaque(linha, coluna);
botaoClicado.setEnabled(false); // Desabilita o botão após o clique
if (resultado == Tabuleiro.ACERTO) {
botaoClicado.setText("X");
botaoClicado.setBackground(Color.GREEN);
labelStatus.setText("PARABÉNS! Você afundou o navio inimigo!");
fimDeJogo(true); // Venceu
} else { // resultado == Tabuleiro.ERRO
botaoClicado.setText("O");
botaoClicado.setBackground(Color.CYAN);
tentativasRestantes--;
if (tentativasRestantes > 0) {
labelStatus.setText(String.format("Você acertou a água! Tentativas restantes: %d", tentativasRestantes));
} else {
labelStatus.setText("FIM DE JOGO! Suas tentativas acabaram.");
fimDeJogo(false); // Perdeu
}
}
}
private void fimDeJogo(boolean vitoria) {
// Desabilita todos os botões que ainda não foram clicados
for (int i = 0; i < TAMANHO_TABULEIRO; i++) {
for (int j = 0; j < TAMANHO_TABULEIRO; j++) {
botoesDoTabuleiro[i][j].setEnabled(false);
}
}
// Se o jogador perdeu, revela onde o navio estava
if (!vitoria) {
int linhaNavio = tabuleiro.getNavioLinha();
int colunaNavio = tabuleiro.getNavioColuna();
botoesDoTabuleiro[linhaNavio][colunaNavio].setBackground(Color.RED);
botoesDoTabuleiro[linhaNavio][colunaNavio].setText("N");
}
}
public static void main(String[] args) {
// Garante que a GUI seja criada na thread de eventos do Swing
SwingUtilities.invokeLater(() -> {
BatalhaNavalGUI jogo = new BatalhaNavalGUI();
jogo.setVisible(true);
});
}
}