commit 9d78ac4cc6de7ff8f6c80e4b0b148ee475316368 Author: morpheus Date: Wed Nov 26 23:15:53 2025 -0300 Aula Ricardo diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..058430b --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1764208924060 + + + + \ No newline at end of file diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c0bcafe --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..cd61d38 --- /dev/null +++ b/README.md @@ -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 + + + org.openjfx + javafx-controls + 21 + + + org.openjfx + javafx-fxml + 21 + + +``` + +--- + +### 🚀 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 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 cartas = new ArrayList<>(); + + public void adicionarCarta(Carta carta) { + cartas.add(carta); + } + + public void limpar() { + cartas.clear(); + } + + public List 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 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 + + 4.0.0 + + com.blackjack + blackjack-desktop + 1.0-SNAPSHOT + + + 21 + 21 + 21 + + + + + org.openjfx + javafx-controls + ${javafx.version} + + + org.openjfx + javafx-fxml + ${javafx.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + + org.openjfx + javafx-maven-plugin + 0.0.8 + + com.blackjack.BlackjackApp + + + + + +``` + +--- + +### 💅 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/) diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -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-,maven-mvnd--}/ +[ -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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -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-,maven-mvnd--}/ +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" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..383a49f --- /dev/null +++ b/pom.xml @@ -0,0 +1,51 @@ + + 4.0.0 + + com.blackjack + blackjack-desktop + 1.0-SNAPSHOT + + + 17 + 17 + 21 + UTF-8 + + + + + org.openjfx + javafx-controls + ${javafx.version} + + + org.openjfx + javafx-fxml + ${javafx.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 17 + 17 + + + + org.openjfx + javafx-maven-plugin + 0.0.8 + + com.blackjack.BlackjackApp + + + + + \ No newline at end of file diff --git a/src/main/java/com/blackjack/BlackjackApp.java b/src/main/java/com/blackjack/BlackjackApp.java new file mode 100644 index 0000000..fa78ce8 --- /dev/null +++ b/src/main/java/com/blackjack/BlackjackApp.java @@ -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(); + } +} \ No newline at end of file diff --git a/src/main/java/com/blackjack/Launcher.java b/src/main/java/com/blackjack/Launcher.java new file mode 100644 index 0000000..aee23ec --- /dev/null +++ b/src/main/java/com/blackjack/Launcher.java @@ -0,0 +1,7 @@ +package com.blackjack; + +public class Launcher { + public static void main(String[] args) { + BlackjackApp.main(args); + } +} \ No newline at end of file diff --git a/src/main/java/com/blackjack/model/Baralho.java b/src/main/java/com/blackjack/model/Baralho.java new file mode 100644 index 0000000..a9e7c3c --- /dev/null +++ b/src/main/java/com/blackjack/model/Baralho.java @@ -0,0 +1,22 @@ +package com.blackjack.model; + +import java.util.Collections; +import java.util.Stack; + +public class Baralho { + private final Stack 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(); + } +} \ No newline at end of file diff --git a/src/main/java/com/blackjack/model/Carta.java b/src/main/java/com/blackjack/model/Carta.java new file mode 100644 index 0000000..ff10dae --- /dev/null +++ b/src/main/java/com/blackjack/model/Carta.java @@ -0,0 +1,8 @@ +package com.blackjack.model; + +public record Carta(Nipe nipe, Rank rank) { + @Override + public String toString() { + return rank.display + nipe.simbolo; + } +} \ No newline at end of file diff --git a/src/main/java/com/blackjack/model/Mao.java b/src/main/java/com/blackjack/model/Mao.java new file mode 100644 index 0000000..c585d4d --- /dev/null +++ b/src/main/java/com/blackjack/model/Mao.java @@ -0,0 +1,37 @@ +package com.blackjack.model; + +import java.util.ArrayList; +import java.util.List; + +public class Mao { + private final List cartas = new ArrayList<>(); + + public void adicionar(Carta c) { + cartas.add(c); + } + + public void limpar() { + cartas.clear(); + } + + public List 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; + } +} \ No newline at end of file diff --git a/src/main/java/com/blackjack/model/Nipe.java b/src/main/java/com/blackjack/model/Nipe.java new file mode 100644 index 0000000..4ae9cbf --- /dev/null +++ b/src/main/java/com/blackjack/model/Nipe.java @@ -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; + } +} \ No newline at end of file diff --git a/src/main/java/com/blackjack/model/Rank.java b/src/main/java/com/blackjack/model/Rank.java new file mode 100644 index 0000000..17cdbf4 --- /dev/null +++ b/src/main/java/com/blackjack/model/Rank.java @@ -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; + } +} \ No newline at end of file diff --git a/src/main/resources/styles.css b/src/main/resources/styles.css new file mode 100644 index 0000000..4d8c6f3 --- /dev/null +++ b/src/main/resources/styles.css @@ -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; +} \ No newline at end of file diff --git a/target/classes/com/blackjack/BlackjackApp.class b/target/classes/com/blackjack/BlackjackApp.class new file mode 100644 index 0000000..4ef4805 Binary files /dev/null and b/target/classes/com/blackjack/BlackjackApp.class differ diff --git a/target/classes/com/blackjack/Launcher.class b/target/classes/com/blackjack/Launcher.class new file mode 100644 index 0000000..49a6f7f Binary files /dev/null and b/target/classes/com/blackjack/Launcher.class differ diff --git a/target/classes/com/blackjack/model/Baralho.class b/target/classes/com/blackjack/model/Baralho.class new file mode 100644 index 0000000..1b71d0c Binary files /dev/null and b/target/classes/com/blackjack/model/Baralho.class differ diff --git a/target/classes/com/blackjack/model/Carta.class b/target/classes/com/blackjack/model/Carta.class new file mode 100644 index 0000000..5d39ab9 Binary files /dev/null and b/target/classes/com/blackjack/model/Carta.class differ diff --git a/target/classes/com/blackjack/model/Mao.class b/target/classes/com/blackjack/model/Mao.class new file mode 100644 index 0000000..ebaadfb Binary files /dev/null and b/target/classes/com/blackjack/model/Mao.class differ diff --git a/target/classes/com/blackjack/model/Nipe.class b/target/classes/com/blackjack/model/Nipe.class new file mode 100644 index 0000000..2bcbb18 Binary files /dev/null and b/target/classes/com/blackjack/model/Nipe.class differ diff --git a/target/classes/com/blackjack/model/Rank.class b/target/classes/com/blackjack/model/Rank.class new file mode 100644 index 0000000..17d841d Binary files /dev/null and b/target/classes/com/blackjack/model/Rank.class differ diff --git a/target/classes/styles.css b/target/classes/styles.css new file mode 100644 index 0000000..4d8c6f3 --- /dev/null +++ b/target/classes/styles.css @@ -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; +} \ No newline at end of file diff --git a/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 0000000..d22f8a0 --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -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 diff --git a/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 0000000..163cc69 --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -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