Aula Ricardo
This commit is contained in:
126
.idea/workspace.xml
generated
Normal file
126
.idea/workspace.xml
generated
Normal file
@@ -0,0 +1,126 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="AutoImportSettings">
|
||||
<option name="autoReloadType" value="SELECTIVE" />
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="fd78c1bd-12b2-46dc-8526-15a96b49acfe" name="Changes" comment="" />
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="MavenImportPreferences">
|
||||
<option name="generalSettings">
|
||||
<MavenGeneralSettings>
|
||||
<option name="mavenHomeTypeForPersistence" value="WRAPPER" />
|
||||
</MavenGeneralSettings>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectColorInfo"><![CDATA[{
|
||||
"associatedIndex": 0
|
||||
}]]></component>
|
||||
<component name="ProjectId" id="362e79rqjdk2ONrSDdv5exrxXfg" />
|
||||
<component name="ProjectViewState">
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent"><![CDATA[{
|
||||
"keyToString": {
|
||||
"Application.Launcher.executor": "Run",
|
||||
"Maven.blackjack-desktop [javafx:run].executor": "Run",
|
||||
"ModuleVcsDetector.initialDetectionPerformed": "true",
|
||||
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||
"kotlin-language-version-configured": "true",
|
||||
"last_opened_file_path": "C:/Users/smaker/Downloads/jogo_blackjack_21_fx/jogo_blackjack_21_fx",
|
||||
"settings.editor.selected.configurable": "preferences.updates"
|
||||
}
|
||||
}]]></component>
|
||||
<component name="RunManager">
|
||||
<configuration default="true" type="JetRunConfigurationType">
|
||||
<module name="jogo_blackjack_21_fx" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration default="true" type="KotlinStandaloneScriptRunConfigurationType">
|
||||
<module name="jogo_blackjack_21_fx" />
|
||||
<option name="filePath" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="blackjack-desktop [javafx:run]" type="MavenRunConfiguration" factoryName="Maven" nameIsGenerated="true">
|
||||
<MavenSettings>
|
||||
<option name="myGeneralSettings" />
|
||||
<option name="myRunnerSettings" />
|
||||
<option name="myRunnerParameters">
|
||||
<MavenRunnerParameters>
|
||||
<option name="cmdOptions" />
|
||||
<option name="profiles">
|
||||
<set />
|
||||
</option>
|
||||
<option name="goals">
|
||||
<list>
|
||||
<option value="javafx:run" />
|
||||
</list>
|
||||
</option>
|
||||
<option name="multimoduleDir" />
|
||||
<option name="pomFileName" />
|
||||
<option name="profilesMap">
|
||||
<map />
|
||||
</option>
|
||||
<option name="projectsCmdOptionValues">
|
||||
<list />
|
||||
</option>
|
||||
<option name="resolveToWorkspace" value="false" />
|
||||
<option name="workingDirPath" value="$PROJECT_DIR$" />
|
||||
</MavenRunnerParameters>
|
||||
</option>
|
||||
</MavenSettings>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration default="true" type="PythonConfigurationType" factoryName="Python">
|
||||
<module name="jogo_blackjack_21_fx" />
|
||||
<option name="ENV_FILES" value="" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="PARENT_ENVS" value="true" />
|
||||
<envs>
|
||||
<env name="PYTHONUNBUFFERED" value="1" />
|
||||
</envs>
|
||||
<option name="SDK_HOME" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="" />
|
||||
<option name="IS_MODULE_SDK" value="false" />
|
||||
<option name="ADD_CONTENT_ROOTS" value="true" />
|
||||
<option name="ADD_SOURCE_ROOTS" value="true" />
|
||||
<option name="SCRIPT_NAME" value="" />
|
||||
<option name="PARAMETERS" value="" />
|
||||
<option name="SHOW_COMMAND_LINE" value="false" />
|
||||
<option name="EMULATE_TERMINAL" value="false" />
|
||||
<option name="MODULE_MODE" value="false" />
|
||||
<option name="REDIRECT_INPUT" value="false" />
|
||||
<option name="INPUT_FILE" value="" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration default="true" type="Tox" factoryName="Tox">
|
||||
<module name="jogo_blackjack_21_fx" />
|
||||
<option name="ENV_FILES" value="" />
|
||||
<option name="INTERPRETER_OPTIONS" value="" />
|
||||
<option name="PARENT_ENVS" value="true" />
|
||||
<option name="SDK_HOME" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="" />
|
||||
<option name="IS_MODULE_SDK" value="false" />
|
||||
<option name="ADD_CONTENT_ROOTS" value="true" />
|
||||
<option name="ADD_SOURCE_ROOTS" value="true" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="fd78c1bd-12b2-46dc-8526-15a96b49acfe" name="Changes" comment="" />
|
||||
<created>1764208924060</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1764208924060</updated>
|
||||
</task>
|
||||
<servers />
|
||||
</component>
|
||||
</project>
|
||||
3
.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
3
.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
|
||||
690
README.md
Normal file
690
README.md
Normal file
@@ -0,0 +1,690 @@
|
||||
# Jogo **Blackjack (21)**
|
||||
|
||||
Vamos construir um **Blackjack (21)** profissional, com arquitetura MVC (Model-View-Controller).
|
||||
|
||||
---
|
||||
|
||||
### 🏗️ 1. Preparação do Ambiente e Estrutura
|
||||
|
||||
Você precisará do **JDK 21** instalado e de uma IDE (IntelliJ IDEA ou Eclipse). Vamos usar o **Maven** para gerenciar as dependências.
|
||||
|
||||
**Estrutura de Pastas Recomendada:**
|
||||
|
||||
```text
|
||||
blackjack21/
|
||||
├── src/
|
||||
│ ├── main/
|
||||
│ │ ├── java/
|
||||
│ │ │ └── com/
|
||||
│ │ │ └── blackjack/
|
||||
│ │ │ ├── Main.java (Entrada)
|
||||
│ │ │ ├── model/ (Lógica: Carta, Baralho, Mão)
|
||||
│ │ │ └── controller/ (Interface e Regras de Jogo)
|
||||
│ │ └── resources/
|
||||
│ │ └── styles.css (Estilo Moderno)
|
||||
└── pom.xml
|
||||
```
|
||||
|
||||
**Dependências no `pom.xml`:**
|
||||
Precisamos das bibliotecas do JavaFX.
|
||||
|
||||
```xml
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-controls</artifactId>
|
||||
<version>21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-fxml</artifactId>
|
||||
<version>21</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🚀 2. Configuração e Execução no Windows
|
||||
|
||||
#### Pré-requisitos
|
||||
|
||||
- **JDK 21** instalado
|
||||
- **Maven** instalado globalmente (ou use o Maven Wrapper incluído)
|
||||
|
||||
#### Problema Comum: Maven Wrapper
|
||||
|
||||
Se você encontrar o erro:
|
||||
|
||||
```
|
||||
Get-Content : Cannot find path '.mvn\wrapper\maven-wrapper.properties' because it does not exist.
|
||||
```
|
||||
|
||||
**Solução:**
|
||||
|
||||
1. Abra o PowerShell no diretório do projeto
|
||||
2. Execute o comando para regenerar o Maven Wrapper:
|
||||
```powershell
|
||||
mvn -N wrapper:wrapper
|
||||
```
|
||||
|
||||
#### Como Executar o Projeto
|
||||
|
||||
```powershell
|
||||
# Navegar para o diretório do projeto
|
||||
cd "caminho\para\jogo_blackjack_21_fx"
|
||||
|
||||
# Executar a aplicação JavaFX
|
||||
.\mvnw javafx:run
|
||||
|
||||
# Ou limpar e executar
|
||||
.\mvnw clean javafx:run
|
||||
```
|
||||
|
||||
#### Outros Comandos Úteis
|
||||
|
||||
```powershell
|
||||
# Apenas compilar
|
||||
.\mvnw compile
|
||||
|
||||
# Limpar arquivos compilados
|
||||
.\mvnw clean
|
||||
|
||||
# Executar testes (se houver)
|
||||
.\mvnw test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🃏 4. O Modelo (Model)
|
||||
|
||||
Aqui ficam as regras de negócio, independentes da interface visual.
|
||||
|
||||
**Classe `Carta.java` e Enums:**
|
||||
|
||||
```java
|
||||
package com.blackjack.model;
|
||||
|
||||
public record Carta(Nipe nipe, Rank rank) {
|
||||
public enum Nipe { COPAS, OUROS, PAUS, ESPADAS }
|
||||
public enum Rank {
|
||||
DOIS(2), TRES(3), QUATRO(4), CINCO(5), SEIS(6), SETE(7), OITO(8), NOVE(9), DEZ(10),
|
||||
VALETE(10), DAMA(10), REI(10), AS(11);
|
||||
|
||||
final int valor;
|
||||
Rank(int valor) { this.valor = valor; }
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return rank + " de " + nipe;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Classe `Baralho.java`:**
|
||||
|
||||
```java
|
||||
package com.blackjack.model;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class Baralho {
|
||||
private final Stack<Carta> cartas = new Stack<>();
|
||||
|
||||
public Baralho() {
|
||||
reiniciar();
|
||||
}
|
||||
|
||||
public void reiniciar() {
|
||||
cartas.clear();
|
||||
for (Carta.Nipe nipe : Carta.Nipe.values()) {
|
||||
for (Carta.Rank rank : Carta.Rank.values()) {
|
||||
cartas.push(new Carta(nipe, rank));
|
||||
}
|
||||
}
|
||||
Collections.shuffle(cartas);
|
||||
}
|
||||
|
||||
public Carta comprar() {
|
||||
return cartas.isEmpty() ? null : cartas.pop();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🧠 5. Lógica de Pontuação (Regra do Ás)
|
||||
|
||||
O Ás é "tricky". Ele vale 11, a menos que estoure 21, aí passa a valer 1.
|
||||
|
||||
**Classe `Mao.java`:**
|
||||
|
||||
```java
|
||||
package com.blackjack.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Mao {
|
||||
private final List<Carta> cartas = new ArrayList<>();
|
||||
|
||||
public void adicionarCarta(Carta carta) {
|
||||
cartas.add(carta);
|
||||
}
|
||||
|
||||
public void limpar() {
|
||||
cartas.clear();
|
||||
}
|
||||
|
||||
public List<Carta> getCartas() {
|
||||
return cartas;
|
||||
}
|
||||
|
||||
public int calcularPontuacao() {
|
||||
int pontos = 0;
|
||||
int ases = 0;
|
||||
|
||||
for (Carta c : cartas) {
|
||||
pontos += c.rank().valor;
|
||||
if (c.rank() == Carta.Rank.AS) ases++;
|
||||
}
|
||||
|
||||
while (pontos > 21 && ases > 0) {
|
||||
pontos -= 10; // Transforma Ás de 11 para 1
|
||||
ases--;
|
||||
}
|
||||
return pontos;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🎨 6. Interface Moderna e Controle (View & Controller)
|
||||
|
||||
Em vez de usar HTML/DOM (que é Web), usaremos o **Scenegraph** do JavaFX. Para ser didático, farei a interface via código para você ver a estrutura, mas em projetos grandes usamos arquivos FXML.
|
||||
|
||||
**Classe `BlackjackGame.java` (O Coração da UI):**
|
||||
|
||||
```java
|
||||
package com.blackjack.controller;
|
||||
|
||||
import com.blackjack.model.*;
|
||||
import javafx.application.Application;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
public class BlackjackGame extends Application {
|
||||
|
||||
private Baralho baralho;
|
||||
private Mao maoJogador;
|
||||
private Mao maoDealer;
|
||||
|
||||
private HBox mesaDealer;
|
||||
private HBox mesaJogador;
|
||||
private Label lblStatus;
|
||||
private Label lblPontosJogador;
|
||||
|
||||
private Button btnPedir;
|
||||
private Button btnParar;
|
||||
private Button btnReiniciar;
|
||||
|
||||
@Override
|
||||
public void start(Stage stage) {
|
||||
baralho = new Baralho();
|
||||
maoJogador = new Mao();
|
||||
maoDealer = new Mao();
|
||||
|
||||
// --- Layout da Interface (Responsiva) ---
|
||||
VBox root = new VBox(20);
|
||||
root.setAlignment(Pos.CENTER);
|
||||
root.setStyle("-fx-background-color: #2E8B57; -fx-padding: 30;"); // Verde Mesa de Jogo
|
||||
|
||||
// Área do Dealer
|
||||
Label lblDealer = new Label("Dealer");
|
||||
lblDealer.getStyleClass().add("titulo");
|
||||
mesaDealer = new HBox(10);
|
||||
mesaDealer.setAlignment(Pos.CENTER);
|
||||
|
||||
// Área do Jogador
|
||||
Label lblJogador = new Label("Você");
|
||||
lblJogador.getStyleClass().add("titulo");
|
||||
mesaJogador = new HBox(10);
|
||||
mesaJogador.setAlignment(Pos.CENTER);
|
||||
lblPontosJogador = new Label("Pontos: 0");
|
||||
lblPontosJogador.getStyleClass().add("texto-branco");
|
||||
|
||||
// Botões
|
||||
HBox painelBotoes = new HBox(15);
|
||||
painelBotoes.setAlignment(Pos.CENTER);
|
||||
btnPedir = criarBotao("Pedir Carta", "#3498db");
|
||||
btnParar = criarBotao("Parar", "#e74c3c");
|
||||
btnReiniciar = criarBotao("Novo Jogo", "#f1c40f");
|
||||
btnReiniciar.setVisible(false); // Só aparece no fim
|
||||
|
||||
painelBotoes.getChildren().addAll(btnPedir, btnParar, btnReiniciar);
|
||||
|
||||
lblStatus = new Label("Bem-vindo ao Blackjack!");
|
||||
lblStatus.getStyleClass().add("status");
|
||||
|
||||
root.getChildren().addAll(lblDealer, mesaDealer, lblStatus, mesaJogador, lblJogador, lblPontosJogador, painelBotoes);
|
||||
|
||||
// --- Eventos (Interatividade) ---
|
||||
btnPedir.setOnAction(e -> comprarCartaJogador());
|
||||
btnParar.setOnAction(e -> turnoDealer());
|
||||
btnReiniciar.setOnAction(e -> iniciarJogo());
|
||||
|
||||
Scene scene = new Scene(root, 800, 600);
|
||||
scene.getStylesheets().add(getClass().getResource("/styles.css").toExternalForm());
|
||||
|
||||
stage.setTitle("Blackjack Java 21");
|
||||
stage.setScene(scene);
|
||||
stage.show();
|
||||
|
||||
iniciarJogo();
|
||||
}
|
||||
|
||||
private void iniciarJogo() {
|
||||
baralho.reiniciar();
|
||||
maoJogador.limpar();
|
||||
maoDealer.limpar();
|
||||
|
||||
btnPedir.setDisable(false);
|
||||
btnParar.setDisable(false);
|
||||
btnReiniciar.setVisible(false);
|
||||
lblStatus.setText("Sua vez...");
|
||||
|
||||
// Distribuição inicial
|
||||
maoJogador.adicionarCarta(baralho.comprar());
|
||||
maoDealer.adicionarCarta(baralho.comprar());
|
||||
maoJogador.adicionarCarta(baralho.comprar());
|
||||
maoDealer.adicionarCarta(baralho.comprar());
|
||||
|
||||
atualizarMesa(false);
|
||||
}
|
||||
|
||||
private void comprarCartaJogador() {
|
||||
maoJogador.adicionarCarta(baralho.comprar());
|
||||
if (maoJogador.calcularPontuacao() > 21) {
|
||||
atualizarMesa(false);
|
||||
fimDeJogo("Você estourou! Dealer venceu.");
|
||||
} else {
|
||||
atualizarMesa(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void turnoDealer() {
|
||||
// Dealer compra até ter 17 ou mais
|
||||
while (maoDealer.calcularPontuacao() < 17) {
|
||||
maoDealer.adicionarCarta(baralho.comprar());
|
||||
}
|
||||
verificarVencedor();
|
||||
}
|
||||
|
||||
private void verificarVencedor() {
|
||||
int pJogador = maoJogador.calcularPontuacao();
|
||||
int pDealer = maoDealer.calcularPontuacao();
|
||||
|
||||
atualizarMesa(true); // Revela cartas do dealer
|
||||
|
||||
if (pDealer > 21) {
|
||||
fimDeJogo("Dealer estourou! Você venceu!");
|
||||
} else if (pJogador > pDealer) {
|
||||
fimDeJogo("Você venceu!");
|
||||
} else if (pJogador < pDealer) {
|
||||
fimDeJogo("Dealer venceu.");
|
||||
} else {
|
||||
fimDeJogo("Empate.");
|
||||
}
|
||||
}
|
||||
|
||||
private void fimDeJogo(String mensagem) {
|
||||
lblStatus.setText(mensagem);
|
||||
btnPedir.setDisable(true);
|
||||
btnParar.setDisable(true);
|
||||
btnReiniciar.setVisible(true);
|
||||
}
|
||||
|
||||
// Atualiza a "DOM" do JavaFX
|
||||
private void atualizarMesa(boolean mostrarTudoDealer) {
|
||||
mesaJogador.getChildren().clear();
|
||||
mesaDealer.getChildren().clear();
|
||||
|
||||
// Renderiza Jogador
|
||||
for (Carta c : maoJogador.getCartas()) {
|
||||
mesaJogador.getChildren().add(criarVisualCarta(c));
|
||||
}
|
||||
lblPontosJogador.setText("Pontos: " + maoJogador.calcularPontuacao());
|
||||
|
||||
// Renderiza Dealer
|
||||
List<Carta> cartasDealer = maoDealer.getCartas();
|
||||
for (int i = 0; i < cartasDealer.size(); i++) {
|
||||
if (i == 0 && !mostrarTudoDealer) {
|
||||
// Carta oculta
|
||||
mesaDealer.getChildren().add(criarVisualCartaOculta());
|
||||
} else {
|
||||
mesaDealer.getChildren().add(criarVisualCarta(cartasDealer.get(i)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helpers de UI
|
||||
private StackPane criarVisualCarta(Carta c) {
|
||||
StackPane card = new StackPane();
|
||||
card.setPrefSize(80, 120);
|
||||
card.getStyleClass().add("carta");
|
||||
Label lbl = new Label(c.toString());
|
||||
lbl.setWrapText(true);
|
||||
card.getChildren().add(lbl);
|
||||
return card;
|
||||
}
|
||||
|
||||
private StackPane criarVisualCartaOculta() {
|
||||
StackPane card = new StackPane();
|
||||
card.setPrefSize(80, 120);
|
||||
card.getStyleClass().add("carta-oculta");
|
||||
return card;
|
||||
}
|
||||
|
||||
private Button criarBotao(String texto, String cor) {
|
||||
Button btn = new Button(texto);
|
||||
btn.setStyle("-fx-background-color: " + cor + "; -fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: 14px;");
|
||||
btn.setPrefWidth(120);
|
||||
return btn;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
launch();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 💅 5. Estilização CSS (Moderno e Responsivo)
|
||||
|
||||
Salve como `src/main/resources/styles.css`. Isso substitui a necessidade de HTML.
|
||||
|
||||
```css
|
||||
.root {
|
||||
-fx-font-family: "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
.titulo {
|
||||
-fx-font-size: 24px;
|
||||
-fx-text-fill: white;
|
||||
-fx-font-weight: bold;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.6), 5, 0, 0, 1);
|
||||
}
|
||||
|
||||
.texto-branco {
|
||||
-fx-text-fill: white;
|
||||
-fx-font-size: 18px;
|
||||
}
|
||||
|
||||
.status {
|
||||
-fx-font-size: 28px;
|
||||
-fx-text-fill: #f1c40f;
|
||||
-fx-font-weight: bold;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.8), 10, 0, 0, 0);
|
||||
}
|
||||
|
||||
.carta {
|
||||
-fx-background-color: white;
|
||||
-fx-background-radius: 10;
|
||||
-fx-border-color: #333;
|
||||
-fx-border-radius: 10;
|
||||
-fx-border-width: 2;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.4), 10, 0, 5, 5);
|
||||
}
|
||||
|
||||
.carta-oculta {
|
||||
-fx-background-color: #a93226; /* Vermelho fundo carta */
|
||||
-fx-background-radius: 10;
|
||||
-fx-border-color: white;
|
||||
-fx-border-width: 3;
|
||||
-fx-border-style: dashed;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🚀 8. Gerar Versão Desktop (Java FX)
|
||||
|
||||
No Java moderno, não usamos Electron. Usamos **jpackage** (incluso no JDK 21) para criar um `.exe` ou `.msi` nativo.
|
||||
|
||||
1. **Compile o projeto** (via Maven):
|
||||
`mvn clean package`
|
||||
2. **Gere a imagem nativa** (Exemplo de comando simplificado):
|
||||
```bash
|
||||
jpackage --input target/ --name Blackjack21 --main-jar blackjack-1.0.jar --main-class com.blackjack.controller.BlackjackGame --type app-image
|
||||
```
|
||||
|
||||
Isso criará um executável que o usuário pode clicar e jogar sem precisar instalar o Java manualmente.
|
||||
|
||||
---
|
||||
|
||||
### Próximo Passo
|
||||
|
||||
### 🚀 9. Refatoração
|
||||
|
||||
Esse erro é um clássico no desenvolvimento moderno com JavaFX (pós-JDK 11).
|
||||
|
||||
O motivo: Desde o Java 11, o JavaFX foi removido do JDK padrão e agora vive como módulos separados. Quando você tenta rodar diretamente uma classe que estende `Application` (como a nossa `BlackjackApp`), a JVM tenta carregar os componentes gráficos nativos antes mesmo de olhar para o seu classpath, e falha.
|
||||
|
||||
Vou te ensinar o **padrão da indústria** para resolver isso sem precisar ficar configurando argumentos complexos de VM (`--module-path`, etc). Usaremos a técnica do **Launcher (Lançador)**.
|
||||
|
||||
Siga estes passos simples:
|
||||
|
||||
### ✅ A Solução: O "Truque" do Launcher
|
||||
|
||||
Precisamos criar uma classe simples que **não** estenda `Application`, apenas para chamar o `main` da classe principal. Isso engana a JVM e permite que as bibliotecas sejam carregadas corretamente do classpath.
|
||||
|
||||
#### 1\. Crie a classe `Launcher.java`
|
||||
|
||||
Crie este arquivo na mesma pasta do seu `BlackjackApp.java` (`src/main/java/com/blackjack/Launcher.java`):
|
||||
|
||||
```java
|
||||
package com.blackjack;
|
||||
|
||||
public class Launcher {
|
||||
public static void main(String[] args) {
|
||||
BlackjackApp.main(args);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2\. Execute pelo Launcher
|
||||
|
||||
Agora, em vez de tentar rodar o `BlackjackApp.java`, **execute o `Launcher.java`**.
|
||||
|
||||
- **Se estiver no VS Code/IntelliJ:** Clique com o botão direito em `Launcher.java` e selecione "Run".
|
||||
- **Se estiver via Linha de Comando:** Aponte para essa classe.
|
||||
|
||||
---
|
||||
|
||||
### 💡 Alternativa: Rodando via Maven (Recomendado)
|
||||
|
||||
Se você já configurou o `pom.xml` que te passei anteriormente, você nem precisa criar o Launcher se rodar direto pelo Maven. O plugin do JavaFX cuida disso para você.
|
||||
|
||||
Abra o terminal na pasta do projeto (onde está o `pom.xml`) e digite:
|
||||
|
||||
```bash
|
||||
mvn clean javafx:run
|
||||
```
|
||||
|
||||
Isso deve abrir a janela do jogo imediatamente.
|
||||
|
||||
### Resumo Técnico (Para seu aprendizado)
|
||||
|
||||
O erro acontece porque a classe `BlackjackApp` herda de `javafx.application.Application`. A JVM verifica isso na inicialização e exige que os módulos JavaFX estejam no _Module Path_. Ao usar a classe `Launcher` (que é uma classe Java comum), a aplicação inicia normalmente e, quando chama `BlackjackApp.main()`, as bibliotecas já estão carregadas no _Class Path_, contornando a verificação estrita da inicialização.
|
||||
|
||||
---
|
||||
|
||||
# Códigos Completos
|
||||
|
||||
**Dependências no `pom.xml`:**
|
||||
Precisamos das bibliotecas do JavaFX.
|
||||
|
||||
```xml
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.blackjack</groupId>
|
||||
<artifactId>blackjack-desktop</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>21</maven.compiler.source>
|
||||
<maven.compiler.target>21</maven.compiler.target>
|
||||
<javafx.version>21</javafx.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-controls</artifactId>
|
||||
<version>${javafx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-fxml</artifactId>
|
||||
<version>${javafx.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-maven-plugin</artifactId>
|
||||
<version>0.0.8</version>
|
||||
<configuration>
|
||||
<mainClass>com.blackjack.BlackjackApp</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 💅 5. Estilização CSS (Moderno e Responsivo)
|
||||
|
||||
Salve como `src/main/resources/styles.css`. Isso substitui a necessidade de HTML.
|
||||
|
||||
```css
|
||||
.root {
|
||||
-fx-background-color: #0a5c0a; /* Verde clássico */
|
||||
-fx-font-family: "Arial";
|
||||
}
|
||||
|
||||
/* Títulos */
|
||||
.titulo-principal {
|
||||
-fx-text-fill: white;
|
||||
-fx-font-size: 32px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-padding: 20;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.5), 5, 0, 0, 1);
|
||||
}
|
||||
|
||||
.titulo-area {
|
||||
-fx-text-fill: #ffc107; /* Dourado */
|
||||
-fx-font-size: 18px;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
/* Container das Mãos (Areas) */
|
||||
.area-jogo {
|
||||
-fx-background-color: rgba(0, 0, 0, 0.2);
|
||||
-fx-border-color: #ffc107;
|
||||
-fx-border-width: 2;
|
||||
-fx-border-radius: 10;
|
||||
-fx-background-radius: 10;
|
||||
-fx-padding: 20;
|
||||
-fx-spacing: 15;
|
||||
-fx-alignment: center;
|
||||
-fx-min-width: 600;
|
||||
}
|
||||
|
||||
/* A Carta Visual */
|
||||
.carta {
|
||||
-fx-background-color: white;
|
||||
-fx-background-radius: 8;
|
||||
-fx-border-color: #333;
|
||||
-fx-border-radius: 8;
|
||||
-fx-border-width: 1;
|
||||
-fx-pref-width: 80;
|
||||
-fx-pref-height: 120;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0, 0, 0, 0.4), 8, 0, 2, 2);
|
||||
}
|
||||
|
||||
.carta-texto {
|
||||
-fx-font-size: 18px;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
.carta-naipe-grande {
|
||||
-fx-font-size: 36px;
|
||||
}
|
||||
|
||||
.red {
|
||||
-fx-text-fill: #d90000;
|
||||
}
|
||||
.black {
|
||||
-fx-text-fill: black;
|
||||
}
|
||||
|
||||
/* Carta Oculta (Verso) */
|
||||
.carta-oculta {
|
||||
-fx-background-color: linear-gradient(to bottom right, #444, #666);
|
||||
-fx-background-radius: 8;
|
||||
-fx-border-color: white;
|
||||
-fx-border-width: 2;
|
||||
-fx-border-style: solid;
|
||||
}
|
||||
|
||||
/* Mensagem de Status */
|
||||
.status-msg {
|
||||
-fx-text-fill: white;
|
||||
-fx-font-size: 24px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-padding: 10;
|
||||
}
|
||||
|
||||
/* Botões */
|
||||
.button {
|
||||
-fx-background-color: #ffc107;
|
||||
-fx-text-fill: #333;
|
||||
-fx-font-size: 14px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-background-radius: 5;
|
||||
-fx-cursor: hand;
|
||||
-fx-padding: 10 20;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
-fx-background-color: #ffd54f;
|
||||
}
|
||||
|
||||
.button:disabled {
|
||||
-fx-background-color: #999;
|
||||
-fx-opacity: 0.7;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### [ricardotecpro.github.io](https://ricardotecpro.github.io/)
|
||||
295
mvnw
vendored
Normal file
295
mvnw
vendored
Normal file
@@ -0,0 +1,295 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
if [ -n "${JAVA_HOME-}" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
189
mvnw.cmd
vendored
Normal file
189
mvnw.cmd
vendored
Normal file
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
51
pom.xml
Normal file
51
pom.xml
Normal file
@@ -0,0 +1,51 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.blackjack</groupId>
|
||||
<artifactId>blackjack-desktop</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<javafx.version>21</javafx.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-controls</artifactId>
|
||||
<version>${javafx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-fxml</artifactId>
|
||||
<version>${javafx.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<source>17</source>
|
||||
<target>17</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-maven-plugin</artifactId>
|
||||
<version>0.0.8</version>
|
||||
<configuration>
|
||||
<mainClass>com.blackjack.BlackjackApp</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
255
src/main/java/com/blackjack/BlackjackApp.java
Normal file
255
src/main/java/com/blackjack/BlackjackApp.java
Normal file
@@ -0,0 +1,255 @@
|
||||
package com.blackjack;
|
||||
|
||||
import com.blackjack.model.*;
|
||||
import javafx.application.Application;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.geometry.Pos;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.scene.shape.Rectangle;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
public class BlackjackApp extends Application {
|
||||
|
||||
// --- Estado do Jogo ---
|
||||
private Baralho baralho;
|
||||
private Mao maoJogador;
|
||||
private Mao maoDealer;
|
||||
private boolean jogoEmAndamento;
|
||||
|
||||
// --- Elementos de UI ---
|
||||
private HBox containerCartasDealer;
|
||||
private HBox containerCartasJogador;
|
||||
private Label lblPontosDealer;
|
||||
private Label lblPontosJogador;
|
||||
private Label lblMensagem;
|
||||
|
||||
private Button btnPedir;
|
||||
private Button btnParar;
|
||||
private Button btnNovoJogo;
|
||||
|
||||
@Override
|
||||
public void start(Stage stage) {
|
||||
// Inicialização dos Modelos
|
||||
baralho = new Baralho();
|
||||
maoJogador = new Mao();
|
||||
maoDealer = new Mao();
|
||||
|
||||
// --- Construção da Interface ---
|
||||
|
||||
// 1. Cabeçalho
|
||||
Label titulo = new Label("BLACKJACK 21");
|
||||
titulo.getStyleClass().add("titulo-principal");
|
||||
|
||||
// 2. Área do Dealer
|
||||
lblPontosDealer = new Label("Dealer: 0");
|
||||
lblPontosDealer.getStyleClass().add("titulo-area");
|
||||
|
||||
containerCartasDealer = new HBox(10);
|
||||
containerCartasDealer.setAlignment(Pos.CENTER);
|
||||
|
||||
VBox areaDealer = new VBox(10, lblPontosDealer, containerCartasDealer);
|
||||
areaDealer.getStyleClass().add("area-jogo");
|
||||
|
||||
// 3. Status do Jogo
|
||||
lblMensagem = new Label("Bem-vindo!");
|
||||
lblMensagem.getStyleClass().add("status-msg");
|
||||
|
||||
// 4. Área do Jogador
|
||||
lblPontosJogador = new Label("Você: 0");
|
||||
lblPontosJogador.getStyleClass().add("titulo-area");
|
||||
|
||||
containerCartasJogador = new HBox(10);
|
||||
containerCartasJogador.setAlignment(Pos.CENTER);
|
||||
|
||||
VBox areaJogador = new VBox(10, lblPontosJogador, containerCartasJogador);
|
||||
areaJogador.getStyleClass().add("area-jogo");
|
||||
|
||||
// 5. Controles
|
||||
HBox controles = new HBox(20);
|
||||
controles.setAlignment(Pos.CENTER);
|
||||
controles.setPadding(new Insets(20));
|
||||
|
||||
btnPedir = new Button("PEDIR CARTA");
|
||||
btnParar = new Button("PARAR (STAND)");
|
||||
btnNovoJogo = new Button("NOVO JOGO");
|
||||
|
||||
// Ações dos Botões
|
||||
btnPedir.setOnAction(e -> acaoPedirCarta());
|
||||
btnParar.setOnAction(e -> acaoParar());
|
||||
btnNovoJogo.setOnAction(e -> iniciarJogo());
|
||||
|
||||
controles.getChildren().addAll(btnPedir, btnParar, btnNovoJogo);
|
||||
|
||||
// --- Layout Principal ---
|
||||
VBox root = new VBox(20);
|
||||
root.setAlignment(Pos.TOP_CENTER);
|
||||
root.setPadding(new Insets(20));
|
||||
root.getChildren().addAll(titulo, areaDealer, lblMensagem, areaJogador, controles);
|
||||
|
||||
// Configuração da Cena
|
||||
Scene scene = new Scene(root, 900, 700);
|
||||
|
||||
// Importante: Carregando o CSS
|
||||
String css = getClass().getResource("/styles.css").toExternalForm();
|
||||
scene.getStylesheets().add(css);
|
||||
|
||||
stage.setTitle("Blackjack Desktop - JavaFX");
|
||||
stage.setScene(scene);
|
||||
stage.show();
|
||||
|
||||
// Começar o primeiro jogo
|
||||
iniciarJogo();
|
||||
}
|
||||
|
||||
// --- Lógica do Jogo (Game Loop) ---
|
||||
|
||||
private void iniciarJogo() {
|
||||
jogoEmAndamento = true;
|
||||
baralho.reiniciar();
|
||||
maoJogador.limpar();
|
||||
maoDealer.limpar();
|
||||
|
||||
lblMensagem.setText("Sua vez. Pedir ou Parar?");
|
||||
atualizarBotoes(true);
|
||||
|
||||
// Distribuição inicial
|
||||
maoJogador.adicionar(baralho.comprar());
|
||||
maoDealer.adicionar(baralho.comprar());
|
||||
maoJogador.adicionar(baralho.comprar());
|
||||
maoDealer.adicionar(baralho.comprar());
|
||||
|
||||
// Verifica Blackjack instantâneo
|
||||
if (maoJogador.calcularPontuacao() == 21) {
|
||||
finalizarJogo("Blackjack! Você venceu!");
|
||||
}
|
||||
|
||||
atualizarMesa(false); // false = esconde a primeira carta do dealer
|
||||
}
|
||||
|
||||
private void acaoPedirCarta() {
|
||||
if (!jogoEmAndamento) return;
|
||||
|
||||
maoJogador.adicionar(baralho.comprar());
|
||||
atualizarMesa(false);
|
||||
|
||||
if (maoJogador.calcularPontuacao() > 21) {
|
||||
finalizarJogo("Você estourou! Dealer vence.");
|
||||
}
|
||||
}
|
||||
|
||||
private void acaoParar() {
|
||||
if (!jogoEmAndamento) return;
|
||||
|
||||
// Vez do Dealer
|
||||
while (maoDealer.calcularPontuacao() < 17) {
|
||||
maoDealer.adicionar(baralho.comprar());
|
||||
}
|
||||
|
||||
determinarVencedor();
|
||||
}
|
||||
|
||||
private void determinarVencedor() {
|
||||
int ptsJogador = maoJogador.calcularPontuacao();
|
||||
int ptsDealer = maoDealer.calcularPontuacao();
|
||||
|
||||
// Atualiza mostrando a carta oculta
|
||||
atualizarMesa(true);
|
||||
|
||||
if (ptsDealer > 21) {
|
||||
finalizarJogo("Dealer estourou! Você venceu!");
|
||||
} else if (ptsJogador > ptsDealer) {
|
||||
finalizarJogo("Você venceu!");
|
||||
} else if (ptsDealer > ptsJogador) {
|
||||
finalizarJogo("Dealer venceu.");
|
||||
} else {
|
||||
finalizarJogo("Empate!");
|
||||
}
|
||||
}
|
||||
|
||||
private void finalizarJogo(String msg) {
|
||||
jogoEmAndamento = false;
|
||||
lblMensagem.setText(msg);
|
||||
atualizarBotoes(false);
|
||||
atualizarMesa(true); // Revela tudo no final
|
||||
}
|
||||
|
||||
private void atualizarBotoes(boolean jogando) {
|
||||
btnPedir.setDisable(!jogando);
|
||||
btnParar.setDisable(!jogando);
|
||||
btnNovoJogo.setDisable(jogando);
|
||||
}
|
||||
|
||||
// --- Renderização Visual (O "DOM" do JavaFX) ---
|
||||
|
||||
private void atualizarMesa(boolean mostrarTudoDealer) {
|
||||
// 1. Renderizar Jogador
|
||||
containerCartasJogador.getChildren().clear();
|
||||
for (Carta c : maoJogador.getCartas()) {
|
||||
containerCartasJogador.getChildren().add(criarCartaVisual(c));
|
||||
}
|
||||
lblPontosJogador.setText("Você: " + maoJogador.calcularPontuacao());
|
||||
|
||||
// 2. Renderizar Dealer
|
||||
containerCartasDealer.getChildren().clear();
|
||||
var cartasD = maoDealer.getCartas();
|
||||
|
||||
for (int i = 0; i < cartasD.size(); i++) {
|
||||
if (i == 0 && !mostrarTudoDealer) {
|
||||
containerCartasDealer.getChildren().add(criarCartaVerso());
|
||||
} else {
|
||||
containerCartasDealer.getChildren().add(criarCartaVisual(cartasD.get(i)));
|
||||
}
|
||||
}
|
||||
|
||||
// Placar Dealer (esconde pontuação total se carta estiver oculta)
|
||||
if (mostrarTudoDealer) {
|
||||
lblPontosDealer.setText("Dealer: " + maoDealer.calcularPontuacao());
|
||||
} else {
|
||||
// Mostra pontuação apenas das cartas visíveis (a partir da segunda)
|
||||
// Simplificação: mostra "?" ou recalcula sem a primeira
|
||||
lblPontosDealer.setText("Dealer: ?");
|
||||
}
|
||||
}
|
||||
|
||||
// Cria o componente visual da carta (StackPane)
|
||||
private StackPane criarCartaVisual(Carta carta) {
|
||||
StackPane cardPane = new StackPane();
|
||||
cardPane.getStyleClass().add("carta");
|
||||
|
||||
// Rank Topo Esquerdo
|
||||
Label lblRankTop = new Label(carta.rank().display);
|
||||
lblRankTop.getStyleClass().addAll("carta-texto", carta.nipe().corCss);
|
||||
StackPane.setAlignment(lblRankTop, Pos.TOP_LEFT);
|
||||
StackPane.setMargin(lblRankTop, new Insets(5));
|
||||
|
||||
// Naipe Centro
|
||||
Label lblNaipe = new Label(carta.nipe().simbolo);
|
||||
lblNaipe.getStyleClass().addAll("carta-naipe-grande", carta.nipe().corCss);
|
||||
StackPane.setAlignment(lblNaipe, Pos.CENTER);
|
||||
|
||||
// Rank Base Direito (invertido opcionalmente, aqui normal)
|
||||
Label lblRankBot = new Label(carta.rank().display);
|
||||
lblRankBot.getStyleClass().addAll("carta-texto", carta.nipe().corCss);
|
||||
StackPane.setAlignment(lblRankBot, Pos.BOTTOM_RIGHT);
|
||||
StackPane.setMargin(lblRankBot, new Insets(5));
|
||||
|
||||
cardPane.getChildren().addAll(lblRankTop, lblNaipe, lblRankBot);
|
||||
return cardPane;
|
||||
}
|
||||
|
||||
private StackPane criarCartaVerso() {
|
||||
StackPane cardPane = new StackPane();
|
||||
cardPane.getStyleClass().addAll("carta", "carta-oculta");
|
||||
Label inter = new Label("?");
|
||||
inter.setStyle("-fx-text-fill: white; -fx-font-size: 30px;");
|
||||
cardPane.getChildren().add(inter);
|
||||
return cardPane;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
launch();
|
||||
}
|
||||
}
|
||||
7
src/main/java/com/blackjack/Launcher.java
Normal file
7
src/main/java/com/blackjack/Launcher.java
Normal file
@@ -0,0 +1,7 @@
|
||||
package com.blackjack;
|
||||
|
||||
public class Launcher {
|
||||
public static void main(String[] args) {
|
||||
BlackjackApp.main(args);
|
||||
}
|
||||
}
|
||||
22
src/main/java/com/blackjack/model/Baralho.java
Normal file
22
src/main/java/com/blackjack/model/Baralho.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.blackjack.model;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Stack;
|
||||
|
||||
public class Baralho {
|
||||
private final Stack<Carta> cartas = new Stack<>();
|
||||
|
||||
public void reiniciar() {
|
||||
cartas.clear();
|
||||
for (Nipe n : Nipe.values()) {
|
||||
for (Rank r : Rank.values()) {
|
||||
cartas.push(new Carta(n, r));
|
||||
}
|
||||
}
|
||||
Collections.shuffle(cartas); // O shuffle do Java é mais otimizado que o manual
|
||||
}
|
||||
|
||||
public Carta comprar() {
|
||||
return cartas.isEmpty() ? null : cartas.pop();
|
||||
}
|
||||
}
|
||||
8
src/main/java/com/blackjack/model/Carta.java
Normal file
8
src/main/java/com/blackjack/model/Carta.java
Normal file
@@ -0,0 +1,8 @@
|
||||
package com.blackjack.model;
|
||||
|
||||
public record Carta(Nipe nipe, Rank rank) {
|
||||
@Override
|
||||
public String toString() {
|
||||
return rank.display + nipe.simbolo;
|
||||
}
|
||||
}
|
||||
37
src/main/java/com/blackjack/model/Mao.java
Normal file
37
src/main/java/com/blackjack/model/Mao.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package com.blackjack.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Mao {
|
||||
private final List<Carta> cartas = new ArrayList<>();
|
||||
|
||||
public void adicionar(Carta c) {
|
||||
cartas.add(c);
|
||||
}
|
||||
|
||||
public void limpar() {
|
||||
cartas.clear();
|
||||
}
|
||||
|
||||
public List<Carta> getCartas() {
|
||||
return cartas;
|
||||
}
|
||||
|
||||
public int calcularPontuacao() {
|
||||
int pontos = 0;
|
||||
int ases = 0;
|
||||
|
||||
for (Carta c : cartas) {
|
||||
pontos += c.rank().valorBase;
|
||||
if (c.rank() == Rank.AS) ases++;
|
||||
}
|
||||
|
||||
// Lógica do Ás: se estourar 21, conta como 1 (subtrai 10)
|
||||
while (pontos > 21 && ases > 0) {
|
||||
pontos -= 10;
|
||||
ases--;
|
||||
}
|
||||
return pontos;
|
||||
}
|
||||
}
|
||||
16
src/main/java/com/blackjack/model/Nipe.java
Normal file
16
src/main/java/com/blackjack/model/Nipe.java
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.blackjack.model;
|
||||
|
||||
public enum Nipe {
|
||||
COPAS("♥", "red"),
|
||||
OUROS("♦", "red"),
|
||||
PAUS("♣", "black"),
|
||||
ESPADAS("♠", "black");
|
||||
|
||||
public final String simbolo;
|
||||
public final String corCss;
|
||||
|
||||
Nipe(String simbolo, String corCss) {
|
||||
this.simbolo = simbolo;
|
||||
this.corCss = corCss;
|
||||
}
|
||||
}
|
||||
16
src/main/java/com/blackjack/model/Rank.java
Normal file
16
src/main/java/com/blackjack/model/Rank.java
Normal file
@@ -0,0 +1,16 @@
|
||||
package com.blackjack.model;
|
||||
|
||||
public enum Rank {
|
||||
DOIS("2", 2), TRES("3", 3), QUATRO("4", 4), CINCO("5", 5),
|
||||
SEIS("6", 6), SETE("7", 7), OITO("8", 8), NOVE("9", 9),
|
||||
DEZ("10", 10), VALETE("J", 10), DAMA("Q", 10), REI("K", 10),
|
||||
AS("A", 11);
|
||||
|
||||
public final String display;
|
||||
public final int valorBase;
|
||||
|
||||
Rank(String display, int valorBase) {
|
||||
this.display = display;
|
||||
this.valorBase = valorBase;
|
||||
}
|
||||
}
|
||||
93
src/main/resources/styles.css
Normal file
93
src/main/resources/styles.css
Normal file
@@ -0,0 +1,93 @@
|
||||
.root {
|
||||
-fx-background-color: #0a5c0a; /* Verde clássico */
|
||||
-fx-font-family: 'Arial';
|
||||
}
|
||||
|
||||
/* Títulos */
|
||||
.titulo-principal {
|
||||
-fx-text-fill: white;
|
||||
-fx-font-size: 32px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-padding: 20;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.5), 5, 0, 0, 1);
|
||||
}
|
||||
|
||||
.titulo-area {
|
||||
-fx-text-fill: #ffc107; /* Dourado */
|
||||
-fx-font-size: 18px;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
/* Container das Mãos (Areas) */
|
||||
.area-jogo {
|
||||
-fx-background-color: rgba(0, 0, 0, 0.2);
|
||||
-fx-border-color: #ffc107;
|
||||
-fx-border-width: 2;
|
||||
-fx-border-radius: 10;
|
||||
-fx-background-radius: 10;
|
||||
-fx-padding: 20;
|
||||
-fx-spacing: 15;
|
||||
-fx-alignment: center;
|
||||
-fx-min-width: 600;
|
||||
}
|
||||
|
||||
/* A Carta Visual */
|
||||
.carta {
|
||||
-fx-background-color: white;
|
||||
-fx-background-radius: 8;
|
||||
-fx-border-color: #333;
|
||||
-fx-border-radius: 8;
|
||||
-fx-border-width: 1;
|
||||
-fx-pref-width: 80;
|
||||
-fx-pref-height: 120;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.4), 8, 0, 2, 2);
|
||||
}
|
||||
|
||||
.carta-texto {
|
||||
-fx-font-size: 18px;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
.carta-naipe-grande {
|
||||
-fx-font-size: 36px;
|
||||
}
|
||||
|
||||
.red { -fx-text-fill: #d90000; }
|
||||
.black { -fx-text-fill: black; }
|
||||
|
||||
/* Carta Oculta (Verso) */
|
||||
.carta-oculta {
|
||||
-fx-background-color: linear-gradient(to bottom right, #444, #666);
|
||||
-fx-background-radius: 8;
|
||||
-fx-border-color: white;
|
||||
-fx-border-width: 2;
|
||||
-fx-border-style: solid;
|
||||
}
|
||||
|
||||
/* Mensagem de Status */
|
||||
.status-msg {
|
||||
-fx-text-fill: white;
|
||||
-fx-font-size: 24px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-padding: 10;
|
||||
}
|
||||
|
||||
/* Botões */
|
||||
.button {
|
||||
-fx-background-color: #ffc107;
|
||||
-fx-text-fill: #333;
|
||||
-fx-font-size: 14px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-background-radius: 5;
|
||||
-fx-cursor: hand;
|
||||
-fx-padding: 10 20;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
-fx-background-color: #ffd54f;
|
||||
}
|
||||
|
||||
.button:disabled {
|
||||
-fx-background-color: #999;
|
||||
-fx-opacity: 0.7;
|
||||
}
|
||||
BIN
target/classes/com/blackjack/BlackjackApp.class
Normal file
BIN
target/classes/com/blackjack/BlackjackApp.class
Normal file
Binary file not shown.
BIN
target/classes/com/blackjack/Launcher.class
Normal file
BIN
target/classes/com/blackjack/Launcher.class
Normal file
Binary file not shown.
BIN
target/classes/com/blackjack/model/Baralho.class
Normal file
BIN
target/classes/com/blackjack/model/Baralho.class
Normal file
Binary file not shown.
BIN
target/classes/com/blackjack/model/Carta.class
Normal file
BIN
target/classes/com/blackjack/model/Carta.class
Normal file
Binary file not shown.
BIN
target/classes/com/blackjack/model/Mao.class
Normal file
BIN
target/classes/com/blackjack/model/Mao.class
Normal file
Binary file not shown.
BIN
target/classes/com/blackjack/model/Nipe.class
Normal file
BIN
target/classes/com/blackjack/model/Nipe.class
Normal file
Binary file not shown.
BIN
target/classes/com/blackjack/model/Rank.class
Normal file
BIN
target/classes/com/blackjack/model/Rank.class
Normal file
Binary file not shown.
93
target/classes/styles.css
Normal file
93
target/classes/styles.css
Normal file
@@ -0,0 +1,93 @@
|
||||
.root {
|
||||
-fx-background-color: #0a5c0a; /* Verde clássico */
|
||||
-fx-font-family: 'Arial';
|
||||
}
|
||||
|
||||
/* Títulos */
|
||||
.titulo-principal {
|
||||
-fx-text-fill: white;
|
||||
-fx-font-size: 32px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-padding: 20;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.5), 5, 0, 0, 1);
|
||||
}
|
||||
|
||||
.titulo-area {
|
||||
-fx-text-fill: #ffc107; /* Dourado */
|
||||
-fx-font-size: 18px;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
/* Container das Mãos (Areas) */
|
||||
.area-jogo {
|
||||
-fx-background-color: rgba(0, 0, 0, 0.2);
|
||||
-fx-border-color: #ffc107;
|
||||
-fx-border-width: 2;
|
||||
-fx-border-radius: 10;
|
||||
-fx-background-radius: 10;
|
||||
-fx-padding: 20;
|
||||
-fx-spacing: 15;
|
||||
-fx-alignment: center;
|
||||
-fx-min-width: 600;
|
||||
}
|
||||
|
||||
/* A Carta Visual */
|
||||
.carta {
|
||||
-fx-background-color: white;
|
||||
-fx-background-radius: 8;
|
||||
-fx-border-color: #333;
|
||||
-fx-border-radius: 8;
|
||||
-fx-border-width: 1;
|
||||
-fx-pref-width: 80;
|
||||
-fx-pref-height: 120;
|
||||
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.4), 8, 0, 2, 2);
|
||||
}
|
||||
|
||||
.carta-texto {
|
||||
-fx-font-size: 18px;
|
||||
-fx-font-weight: bold;
|
||||
}
|
||||
|
||||
.carta-naipe-grande {
|
||||
-fx-font-size: 36px;
|
||||
}
|
||||
|
||||
.red { -fx-text-fill: #d90000; }
|
||||
.black { -fx-text-fill: black; }
|
||||
|
||||
/* Carta Oculta (Verso) */
|
||||
.carta-oculta {
|
||||
-fx-background-color: linear-gradient(to bottom right, #444, #666);
|
||||
-fx-background-radius: 8;
|
||||
-fx-border-color: white;
|
||||
-fx-border-width: 2;
|
||||
-fx-border-style: solid;
|
||||
}
|
||||
|
||||
/* Mensagem de Status */
|
||||
.status-msg {
|
||||
-fx-text-fill: white;
|
||||
-fx-font-size: 24px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-padding: 10;
|
||||
}
|
||||
|
||||
/* Botões */
|
||||
.button {
|
||||
-fx-background-color: #ffc107;
|
||||
-fx-text-fill: #333;
|
||||
-fx-font-size: 14px;
|
||||
-fx-font-weight: bold;
|
||||
-fx-background-radius: 5;
|
||||
-fx-cursor: hand;
|
||||
-fx-padding: 10 20;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
-fx-background-color: #ffd54f;
|
||||
}
|
||||
|
||||
.button:disabled {
|
||||
-fx-background-color: #999;
|
||||
-fx-opacity: 0.7;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
com\blackjack\model\Baralho.class
|
||||
com\blackjack\model\Mao.class
|
||||
com\blackjack\model\Rank.class
|
||||
com\blackjack\BlackjackApp.class
|
||||
com\blackjack\model\Carta.class
|
||||
com\blackjack\model\Nipe.class
|
||||
com\blackjack\Launcher.class
|
||||
@@ -0,0 +1,7 @@
|
||||
C:\Users\smaker\Downloads\jogo_blackjack_21_fx\jogo_blackjack_21_fx\src\main\java\com\blackjack\Launcher.java
|
||||
C:\Users\smaker\Downloads\jogo_blackjack_21_fx\jogo_blackjack_21_fx\src\main\java\com\blackjack\BlackjackApp.java
|
||||
C:\Users\smaker\Downloads\jogo_blackjack_21_fx\jogo_blackjack_21_fx\src\main\java\com\blackjack\model\Rank.java
|
||||
C:\Users\smaker\Downloads\jogo_blackjack_21_fx\jogo_blackjack_21_fx\src\main\java\com\blackjack\model\Mao.java
|
||||
C:\Users\smaker\Downloads\jogo_blackjack_21_fx\jogo_blackjack_21_fx\src\main\java\com\blackjack\model\Carta.java
|
||||
C:\Users\smaker\Downloads\jogo_blackjack_21_fx\jogo_blackjack_21_fx\src\main\java\com\blackjack\model\Baralho.java
|
||||
C:\Users\smaker\Downloads\jogo_blackjack_21_fx\jogo_blackjack_21_fx\src\main\java\com\blackjack\model\Nipe.java
|
||||
Reference in New Issue
Block a user