Compare commits

...

23 Commits

Author SHA1 Message Date
33bc3d76c6 Tris MiniMax 2025-12-04 09:36:41 +01:00
89421ac1c4 Labirinti 2025-12-01 10:50:34 +01:00
241fe7271f Ancora alberi 2025-11-20 09:41:46 +01:00
c6a896f0e2 Alberi 2025-11-20 09:35:03 +01:00
80c5ea412e Livelli 2025-11-20 09:34:50 +01:00
16f1d7af9e Alberi 2025-11-20 09:29:02 +01:00
ce29e454cc Verifica 2025-11-14 09:35:30 +01:00
70e46cc65c Caccia alla Talpa 2025-11-13 17:08:32 +01:00
cc9f2f7ebf Prova 2025-11-13 09:26:45 +01:00
theitaliandeveloper
3054032532 Nuovi progetti 2025-11-13 09:24:57 +01:00
4ca42b835c Commit 2025-11-06 09:36:30 +01:00
72a5882f3f Commit 2025-11-06 09:36:23 +01:00
7e839c8069 Dino Game 2025-10-27 10:50:33 +01:00
ac2a283da4 Dino Game 2025-10-24 09:46:41 +02:00
cc2fd0202b Dino Game 2025-10-24 09:46:33 +02:00
40c9df42d4 Verifica 2025-10-17 09:47:08 +02:00
c1f2c32bd7 Simulazione Verifica 2025-10-16 08:43:10 +02:00
9099666b07 Prova 2025-10-10 08:02:07 +02:00
37f913480f Rubrica 2025-10-02 08:32:20 +02:00
e1d1afa26f roba 2025-09-23 10:45:07 +02:00
b82e9cc2e9 Prova 2025-09-22 10:34:29 +02:00
265f15cbec Terzo Progetto e gitignore 2025-09-22 10:32:52 +02:00
4e6d08632f README 2025-09-22 10:28:49 +02:00
137 changed files with 4111 additions and 8 deletions

7
.gitignore vendored
View File

@@ -21,4 +21,9 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
replay_pid* replay_pid*
# Visual Studio Code settings.json
settings.json
# IntelliJ Idea
.idea/*

30
Alberi1/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
Alberi1/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
Alberi1/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
Alberi1/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Alberi1.iml" filepath="$PROJECT_DIR$/Alberi1.iml" />
</modules>
</component>
</project>

6
Alberi1/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

11
Alberi1/Alberi1.iml Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

123
Alberi1/src/Main.java Normal file
View File

@@ -0,0 +1,123 @@
import static java.lang.Math.max;
class Nodo{
static java.util.Random rnd = new java.util.Random();
int dato;
Nodo left, right;
public Nodo(int dato, Nodo left, Nodo right) {
this.dato = dato;
this.left = left;
this.right = right;
}
static void stampa(Nodo n, int livello, String lr) {
if(n==null) return;
for(int i=0;i<livello-1;i++)
System.out.print("\t");
if(livello!=0) System.out.print("+------->");
System.out.println(n.dato+lr);
stampa(n.left, livello+1,"L");
stampa(n.right, livello+1,"R");
}
/*
0) fissate l'intestazione della funzione e
pensate che esista già e che funzioni
1) caso base, trovare un caso in cui la risposta
è ovvia e non serve computazione
2) cosa fare col dato attuale e cosa fare con i rimanenti
*/
static int somma(Nodo albero) {
if(albero==null) return 0;
return albero.dato+somma(albero.left)+somma(albero.right);
}
static int conta(Nodo albero) {//conta quanti sono i nodi
if(albero==null) return 0;
return 1+conta(albero.left)+conta(albero.right);
}
static int contaFoglie(Nodo albero) {//conta quanti sono le foglie (nodi senza figli)
if(albero==null) return 0;
if (albero.left == null && albero.right == null) {
return 1;
} else {
return contaFoglie(albero.left) + contaFoglie(albero.right);
}
}
static Nodo insOrd(int val, Nodo albero) { //Inserimento ordinato
if(albero==null) return new Nodo(val, null, null);
if(val>albero.dato) return
new Nodo(albero.dato, albero.left, insOrd(val, albero.right));
return new Nodo(albero.dato, insOrd(val, albero.left), albero.right);
}
static boolean trova(Nodo albero, int valore) { //Trova un valore
if(albero==null) return false;
else if(albero.dato==valore) return true;
else return trova(albero.left, valore) || trova(albero.right, valore);
}
static String valoriNelLivello(Nodo albero, int livello){ //Trova un valore in un livello
if(albero==null) return "";
else if(livello==0) return albero.dato + " ";
else return valoriNelLivello(albero.left, livello-1) + valoriNelLivello(albero.right, livello-1);
}
static int altezza(Nodo albero){ //Trova l'altezza dell'albero
if(albero==null) return 0;
else if (albero.left == null && albero.right == null) return 1;
return 1 + max(altezza(albero.left), altezza(albero.right));
}
static boolean uguali(Nodo a, Nodo b) { //Controlla che i due alberi siano uguali
if (a == null && b == null) return true;
if (a == null || b == null) return false;
if (a.dato != b.dato) return false;
return uguali(a.left, b.left) && uguali(a.right, b.right);
}
static int profondita(Nodo albero, int val) { //Restituisce la profondità massima
if(albero==null) return -1;
else if(albero.left == null && albero.right == null && albero.dato != val) return -1;
else if(albero.dato == val) return 1;
int pl = profondita(albero.left,val);
int pr = profondita(albero.right,val);
int m = max(pl, pr);
if (m == -1) return -1;
return 1 + m;
}
static int contaFiglio(Nodo albero) { //Conta i nodi che hanno un solo figlio
int count = 0;
if(albero==null) return count;
else if ((albero.left == null && albero.right != null) || (albero.left != null && albero.right == null)) count = 1;
return count + contaFiglio(albero.left) + contaFiglio(albero.right);
}
static int contaNelLivello(Nodo albero, int livello) { //Conta i nodi nel livello
if(albero==null) return 0;
else if (livello == 0) return 1;
return contaNelLivello(albero.left, livello-1) + contaNelLivello(albero.right, livello-1);
}
static Nodo crea(int altezza) { //Crea un albero con altezza determinata
if (altezza == 0) return null;
else if (altezza == 1) return new Nodo(rnd.nextInt(41) + 10,null,null);
Nodo left = crea(altezza - 1);
Nodo right = crea(altezza - 1);
return new Nodo(rnd.nextInt(41) + 10, left, right);
}
}
public class Main {
public static void main(String[] args) {
Nodo n1 = new Nodo(10, null, null);
Nodo n2 = new Nodo(5, null, null);
Nodo n3 = new Nodo(30, null, null);
n1.left = n2;
n1.right = n3;
// Nodo.stampa(n1,0);
Nodo n4 = Nodo.insOrd(23, n1);
n4 = Nodo.insOrd(1, n4);
Nodo.stampa(n4,0,"");
System.out.println("Nodi: " + Nodo.conta(n4));
System.out.println("Foglie: " + Nodo.contaFoglie(n4));
System.out.println("Somma: " + Nodo.somma(n4));
System.out.println("Trovato 24? " + Nodo.trova(n4,24));
}
}

30
CacciaLaTalpa/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
CacciaLaTalpa/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
CacciaLaTalpa/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
CacciaLaTalpa/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/CacciaLaTalpa.iml" filepath="$PROJECT_DIR$/CacciaLaTalpa.iml" />
</modules>
</component>
</project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,287 @@
import javax.swing.*; // Importa componenti GUI (JFrame, JButton, JLabel, ecc.)
import java.awt.*; // Importa layout e colori (BorderLayout, GridLayout, Color)
import java.awt.event.*; // Importa gestione eventi (ActionListener, ActionEvent)
import java.util.Random; // Importa classe per numeri casuali
// Classe principale che estende JFrame (la finestra dell'applicazione)
public class CacciaAllaTalpa extends JFrame {
// === COSTANTI ===
private static final int NUM_BUCHI = 6; // Numero totale di buchi
private static int TEMPO_TALPA = 2000; // Millisecondi che la talpa rimane visibile
// === COMPONENTI GUI ===
private JButton[] buchi; // Array di 6 bottoni che rappresentano i buchi
private JLabel lblPunteggio; // Etichetta per mostrare il punteggio
private JLabel lblVite; // Etichetta per mostrare le vite rimaste
// === VARIABILI DI GIOCO ===
private int punteggio = 0; // Punteggio corrente del giocatore
private int vite = 5; // Vite rimanenti (inizi con 5)
private int posizioneCorrente = -1; // Indice del buco dove si trova la talpa (-1 = nessuna talpa)
private Timer timerTalpa; // Timer per spostare la talpa ogni 2 secondi
private Random random; // Generatore di numeri casuali
private boolean giocoAttivo = true; // Flag per sapere se il gioco è in corso
// === COSTRUTTORE ===
// Qui viene inizializzata tutta l'interfaccia grafica
public CacciaAllaTalpa() {
// Imposta il titolo della finestra
setTitle("Caccia alla Talpa");
// Chiudi l'applicazione quando chiudi la finestra
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// BorderLayout: divide la finestra in 5 zone (NORTH, SOUTH, EAST, WEST, CENTER)
// I numeri (10, 10) sono gli spazi orizzontali e verticali tra le zone
setLayout(new BorderLayout(10, 10));
// Impedisci il ridimensionamento della finestra
setResizable(false);
// Inizializza il generatore di numeri casuali
random = new Random();
// === PANNELLO SUPERIORE (Punteggio e Vite) ===
// GridLayout(1, 2): 1 riga, 2 colonne
// 20 = spazio orizzontale tra le colonne, 0 = nessuno spazio verticale
JPanel panelInfo = new JPanel(new GridLayout(1, 2, 20, 0));
// BorderFactory.createEmptyBorder(top, left, bottom, right)
// Crea un margine interno di 15 pixel su tutti i lati
panelInfo.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
// Colore verde per il pannello superiore
panelInfo.setBackground(new Color(34, 139, 34));
// === LABEL PUNTEGGIO ===
lblPunteggio = new JLabel("Punteggio: 0", SwingConstants.CENTER);
lblPunteggio.setFont(new Font("Arial", Font.BOLD, 20)); // Font grande e grassetto
lblPunteggio.setForeground(Color.WHITE); // Testo bianco
// === LABEL VITE ===
lblVite = new JLabel("Vite: 5", SwingConstants.CENTER);
lblVite.setFont(new Font("Arial", Font.BOLD, 20));
lblVite.setForeground(Color.WHITE);
// Aggiungi le due label al pannello
panelInfo.add(lblPunteggio);
panelInfo.add(lblVite);
// === PANNELLO CENTRALE (I 6 buchi) ===
// GridLayout(2, 3): 2 righe, 3 colonne = 6 celle totali
// 15, 15 = spazi tra le celle (orizzontale, verticale)
JPanel panelBuchi = new JPanel(new GridLayout(2, 3, 15, 15));
panelBuchi.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panelBuchi.setBackground(new Color(139, 69, 19)); // Colore marrone (terra)
// Crea l'array di 6 bottoni
buchi = new JButton[NUM_BUCHI];
// Ciclo per creare tutti i 6 buchi
for (int i = 0; i < NUM_BUCHI; i++) {
// IMPORTANTE: final per usare 'i' dentro la lambda
final int index = i;
// Crea un nuovo bottone
buchi[i] = new JButton();
// Imposta dimensione fissa del bottone (120x120 pixel)
buchi[i].setPreferredSize(new Dimension(120, 120));
// Font grande per l'emoji della talpa
buchi[i].setFont(new Font("Arial", Font.BOLD, 40));
// Colore di sfondo marrone scuro
buchi[i].setBackground(new Color(101, 67, 33));
// Rimuovi il bordo tratteggiato quando il bottone ha il focus
buchi[i].setFocusPainted(false);
// Bordo nero spesso 3 pixel attorno al bottone
buchi[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
// === EVENT LISTENER ===
// Quando clicchi il bottone, chiama clickBuco(index)
// 'e' è l'evento (ActionEvent) che contiene info sul click
buchi[i].addActionListener(e -> clickBuco(index));
// Aggiungi il bottone al pannello
panelBuchi.add(buchi[i]);
}
// === AGGIUNGI I PANNELLI ALLA FINESTRA ===
// BorderLayout.NORTH = zona superiore
add(panelInfo, BorderLayout.NORTH);
// BorderLayout.CENTER = zona centrale (prende tutto lo spazio rimanente)
add(panelBuchi, BorderLayout.CENTER);
// pack() ridimensiona la finestra per contenere tutti i componenti
pack();
// Centra la finestra sullo schermo (null = centro dello schermo)
setLocationRelativeTo(null);
// === TIMER PRINCIPALE ===
// Timer che ogni 2 secondi (TEMPO_TALPA) chiama spostaOPerdiVita()
// 'e' è l'ActionEvent generato dal timer
timerTalpa = new Timer(TEMPO_TALPA, e -> spostaOPerdiVita());
// === AVVIO DEL GIOCO ===
// Timer che aspetta 1 secondo prima di iniziare il gioco
Timer startTimer = new Timer(1000, e -> {
mostraTalpa(); // Mostra la prima talpa
timerTalpa.start(); // Avvia il timer principale
});
startTimer.setRepeats(false); // Esegui solo una volta
startTimer.start(); // Avvia questo timer
}
// === METODO: MOSTRA LA TALPA ===
// Questo metodo nasconde la talpa precedente e la mostra in una nuova posizione casuale
private void mostraTalpa() {
// Se il gioco non è attivo, esci subito dal metodo
if (!giocoAttivo) return;
// Nascondi la talpa dalla posizione precedente
if (posizioneCorrente >= 0) {
buchi[posizioneCorrente].setText(""); // Rimuovi l'emoji
// Ripristina il colore originale del buco
buchi[posizioneCorrente].setBackground(new Color(101, 67, 33));
}
// Genera una nuova posizione casuale (da 0 a 5)
posizioneCorrente = random.nextInt(NUM_BUCHI);
// Mostra la talpa nella nuova posizione
buchi[posizioneCorrente].setText("🐭"); // Emoji della talpa
// Schiarisci leggermente il colore per evidenziare la talpa
buchi[posizioneCorrente].setBackground(new Color(139, 90, 43));
}
// === METODO: GESTIONE CLICK SU UN BUCO ===
// Parametro: index = quale buco è stato cliccato (da 0 a 5)
private void clickBuco(int index) {
// Se il gioco non è attivo, non fare nulla
if (!giocoAttivo) return;
// Controlla se hai cliccato sul buco giusto (dove c'è la talpa)
if (index == posizioneCorrente) {
// === HAI COLPITO LA TALPA! ===
punteggio++; // Incrementa il punteggio
// Aggiorna la label del punteggio
lblPunteggio.setText("Punteggio: " + punteggio);
// Feedback visivo: colora di verde il buco
buchi[index].setBackground(Color.GREEN);
// Resetta il timer principale (ricomincia il conto di 2 secondi)
timerTalpa.restart();
// Timer per mostrare subito una nuova talpa dopo 200ms
// Questo da il tempo di vedere il verde prima che la talpa si sposti
Timer feedbackTimer = new Timer(200, e -> mostraTalpa());
feedbackTimer.setRepeats(false); // Esegui una sola volta
feedbackTimer.start();
} else {
// === HAI MANCATO! ===
// Feedback visivo: colora di rosso il buco sbagliato
buchi[index].setBackground(Color.RED);
// Timer per ripristinare il colore originale dopo 300ms
Timer resetColor = new Timer(300, e ->
buchi[index].setBackground(new Color(101, 67, 33)));
resetColor.setRepeats(false);
resetColor.start();
}
}
// === METODO: SPOSTA LA TALPA O PERDI UNA VITA ===
// Questo metodo viene chiamato dal timer ogni 2 secondi
private void spostaOPerdiVita() {
if (!giocoAttivo) return;
// Se arrivi qui, significa che i 2 secondi sono passati
// e il giocatore NON ha cliccato sulla talpa
vite--; // Perdi una vita
// Aggiorna la label delle vite
lblVite.setText("Vite: " + vite);
// Controlla se hai finito le vite
if (vite <= 0) {
fineGioco(); // Game Over
} else {
mostraTalpa(); // Mostra la talpa in una nuova posizione
}
}
// === METODO: FINE DEL GIOCO ===
private void fineGioco() {
giocoAttivo = false; // Ferma il gioco
timerTalpa.stop(); // Ferma il timer principale
// Nascondi l'ultima talpa
if (posizioneCorrente >= 0) {
buchi[posizioneCorrente].setText("");
buchi[posizioneCorrente].setBackground(new Color(101, 67, 33));
}
// Mostra un dialog con il punteggio finale
// JOptionPane.showConfirmDialog mostra una finestra con bottoni SI/NO
int scelta = JOptionPane.showConfirmDialog(
this, // Finestra padre
"Game Over!\nPunteggio finale: " + punteggio + "\n\nVuoi giocare ancora?",
"Fine Gioco", // Titolo del dialog
JOptionPane.YES_NO_OPTION // Tipo di bottoni
);
// Controlla quale bottone ha cliccato l'utente
if (scelta == JOptionPane.YES_OPTION) {
resetGioco(); // Ricomincia il gioco
} else {
System.exit(0); // Chiudi l'applicazione
}
}
// === METODO: RESET DEL GIOCO ===
// Ripristina tutte le variabili e ricomincia una nuova partita
private void resetGioco() {
// Azzera le variabili di gioco
punteggio = 0;
vite = 5;
posizioneCorrente = -1;
giocoAttivo = true;
// Aggiorna le label
lblPunteggio.setText("Punteggio: 0");
lblVite.setText("Vite: 5");
// Ripulisci tutti i buchi
for (JButton buco : buchi) {
buco.setText(""); // Rimuovi eventuali talpe
buco.setBackground(new Color(101, 67, 33)); // Colore originale
}
// Aspetta 1 secondo e poi riavvia il gioco
Timer startTimer = new Timer(500, e -> {
mostraTalpa(); // Mostra la prima talpa
timerTalpa.restart(); // Riavvia il timer principale
});
startTimer.setRepeats(false);
startTimer.start();
}
// === METODO MAIN ===
// Punto di ingresso del programma
public static void main(String[] args) {
// SwingUtilities.invokeLater() esegue il codice nel thread della GUI
// È la best practice per creare interfacce Swing
SwingUtilities.invokeLater(() -> {
// Crea una nuova istanza del gioco
CacciaAllaTalpa gioco = new CacciaAllaTalpa();
// Rendi visibile la finestra
gioco.setVisible(true);
});
}
}

30
Calculator/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
Calculator/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
Calculator/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
Calculator/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Calculator.iml" filepath="$PROJECT_DIR$/Calculator.iml" />
</modules>
</component>
</project>

6
Calculator/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

11
Calculator/Calculator.iml Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,79 @@
package calc;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
class ButtonHandler implements ActionListener {
JTextField tf;
int a,b;
String op;
public ButtonHandler(JTextField tf) {
this.tf = tf;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("+") || e.getActionCommand().equals("-")) {
op = e.getActionCommand();
a = Integer.parseInt(tf.getText());
tf.setText("");
return;
}
if (e.getActionCommand().equals("=")) {
b = Integer.parseInt(tf.getText());
if(op.equals("+")) tf.setText(""+(a+b));
if(op.equals("-")) tf.setText(""+(a-b));
return;
}
tf.setText(tf.getText()+e.getActionCommand());
}
}
// Classe principale con il metodo main
public class CalcolatriceMain {
public static void main(String[] args) {
JFrame f = new JFrame("titolo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(100, 100, 300, 500);
f.setLayout(null);
JTextField tf = new JTextField("0");
tf.setBounds(10, 10, 240, 80);
f.add(tf);
ButtonHandler bh = new ButtonHandler(tf);
int x = 10;
int y = 100;
int cont = 1;
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 3; i++) {
JButton bn = new JButton("" + cont);
bn.setActionCommand("" + cont);
bn.setBounds(x, y, 80, 80);
f.add(bn);
x += 80;
bn.addActionListener(bh);
cont++;
}
y += 80;
x = 10;
}
String[] etichette = {"+","-","="};
for (int i = 0; i < 3; i++) {
JButton bn = new JButton(etichette[i]);
bn.setActionCommand(etichette[i]);
bn.setBounds(x, y, 80, 80);
f.add(bn);
x += 80;
bn.addActionListener(bh);
}
f.setVisible(true);
}
}

10
DinoGame/.classpath Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

8
DinoGame/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -0,0 +1,9 @@
<component name="ArtifactManager">
<artifact type="jar" name="DinoGame:jar">
<output-path>$PROJECT_DIR$/bin/artifacts/DinoGame_jar</output-path>
<root id="archive" name="DinoGame.jar">
<element id="module-output" name="DinoGame" />
<element id="dir-copy" path="$PROJECT_DIR$/resources" />
</root>
</artifact>
</component>

6
DinoGame/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
DinoGame/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/DinoGame.iml" filepath="$PROJECT_DIR$/DinoGame.iml" />
</modules>
</component>
</project>

6
DinoGame/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

28
DinoGame/.project Normal file
View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>DinoGame</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1758261738047</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

14
DinoGame/DinoGame.iml Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager">
<output url="file://$MODULE_DIR$/bin/Release/DinoGame" />
<output-test url="file://$MODULE_DIR$/bin/Debug/DinoGame" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: DinoGame

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

View File

@@ -0,0 +1,6 @@
result=21,date=20200420_144048,player=Dino
result=58,date=20200420_144054,player=Dino
result=328,date=20200420_144126,player=Dino
result=367,date=20200422_130458,player=Dino
result=408,date=20200425_162524,player=Dino
result=537,date=20200425_164524,player=Dino

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
DinoGame/resources/dead.wav Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
DinoGame/resources/hi.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
DinoGame/resources/jump.wav Normal file

Binary file not shown.

BIN
DinoGame/resources/land.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

550
DinoGame/src/DinoGame.java Normal file
View File

@@ -0,0 +1,550 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import javax.sound.sampled.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DinoGame extends JPanel implements ActionListener, KeyListener {
// Game constants
private static final int WIDTH = 800;
private static final int HEIGHT = 400;
private static final int GROUND_Y = 320;
private static final int FPS = 60;
private static final int GRAVITY = 1;
private static final int JUMP_STRENGTH = -18;
private static final int INITIAL_SPEED = 10;
private static final int MAX_SPEED = 20;
private static final int SPEED_INCREMENT = 1;
private static final int HITBOX_INSET = 8;
private boolean gameStarted = false;
private boolean gameOver = false;
private boolean paused = false;
private int score = 0;
private int highScore = 0;
private int gameSpeed = INITIAL_SPEED;
private int frameCount = 0;
private final int dinoX = 50;
private int dinoY;
private int dinoWidth;
private int dinoHeight;
private int dinoDuckWidth;
private int dinoDuckHeight;
private int velocityY = 0;
private boolean isJumping = false;
private boolean isDucking = false;
private int animFrame = 0;
private int groundY;
private BufferedImage dinoRun1, dinoRun2, dinoJump, dinoDead;
private BufferedImage dinoDownRun1, dinoDownRun2;
private BufferedImage cactus1, cactus2, cactus3, cactus4, cactus5, cactus6;
private BufferedImage birdFly1, birdFly2;
private BufferedImage cloud, land, gameOverImg, replayImg, hiImg;
private final ArrayList<Obstacle> obstacles = new ArrayList<>();
private final ArrayList<Cloud> clouds = new ArrayList<>();
private int landX = 0;
private final Random rand = new Random();
private int obstacleTimer = 0;
private int minObstacleDistance = 60;
private int maxObstacleDistance = 120;
private Clip jumpSound, deadSound, scoreSound;
private long lastScoreTime = 0;
public DinoGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.WHITE);
setFocusable(true);
addKeyListener(this);
setDoubleBuffered(true);
loadAssets();
for (int i = 0; i < 5; i++) {
clouds.add(new Cloud(i * 250 + rand.nextInt(100), 50 + rand.nextInt(100)));
}
resetGameData();
Timer timer = new Timer(1000 / FPS, this);
timer.start();
}
private void loadAssets() {
try {
loadImages();
} catch (IOException e) {
String errorMsg = "Error: cannot load image resources.\n" + e.getMessage();
System.err.println(errorMsg);
JOptionPane.showMessageDialog(this, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
dinoWidth = dinoRun1.getWidth();
dinoHeight = dinoRun1.getHeight();
dinoDuckWidth = dinoDownRun1.getWidth();
dinoDuckHeight = dinoDownRun1.getHeight();
groundY = GROUND_Y - dinoHeight;
dinoY = groundY;
loadSoundsAndHighScore();
}
private void loadImages() throws IOException {
dinoRun1 = loadImage("/dino-run-1.png");
dinoRun2 = loadImage("/dino-run-2.png");
dinoJump = loadImage("/dino-jump.png");
dinoDead = loadImage("/dino-dead.png");
dinoDownRun1 = loadImage("/dino-down-run-1.png");
dinoDownRun2 = loadImage("/dino-down-run-2.png");
cactus1 = loadImage("/cactus-1.png");
cactus2 = loadImage("/cactus-2.png");
cactus3 = loadImage("/cactus-3.png");
cactus4 = loadImage("/cactus-4.png");
cactus5 = loadImage("/cactus-5.png");
cactus6 = loadImage("/cactus-6.png");
birdFly1 = loadImage("/bird-fly-1.png");
birdFly2 = loadImage("/bird-fly-2.png");
cloud = loadImage("/cloud.png");
land = loadImage("/land.png");
gameOverImg = loadImage("/game-over.png");
replayImg = loadImage("/replay.png");
hiImg = loadImage("/hi.png");
}
private BufferedImage loadImage(String path) throws IOException {
InputStream is = getClass().getResourceAsStream(path);
if (is == null) {
throw new IOException("Resource not found: " + path);
}
try {
return ImageIO.read(is);
} catch (IOException e) {
throw new IOException("Cannot read image: " + path, e);
}
}
private void loadSoundsAndHighScore() {
new Thread(() -> {
try {
jumpSound = loadSound("/jump.wav");
deadSound = loadSound("/dead.wav");
scoreSound = loadSound("/score.wav");
loadHighScore();
} catch (Exception e) {
System.err.println("Error loading sounds and high score: " + e.getMessage());
}
}).start();
}
private Clip loadSound(String path) {
try {
InputStream is = getClass().getResourceAsStream(path);
if (is != null) {
InputStream bufferedIs = new BufferedInputStream(is);
AudioInputStream ais = AudioSystem.getAudioInputStream(bufferedIs);
Clip clip = AudioSystem.getClip();
clip.open(ais);
return clip;
}
} catch (Exception e) {
System.err.println("Cannot load sound: " + path + " - " + e.getMessage());
}
return null;
}
private void loadHighScore() {
try {
Path scoreFile = Paths.get(System.getProperty("user.home"), "dino-best-scores.txt");
if (Files.exists(scoreFile)) {
String content = new String(Files.readAllBytes(scoreFile));
highScore = Integer.parseInt(content.trim());
}
} catch (Exception e) {
highScore = 0;
System.err.println("Cannot load high score: " + e.getMessage());
}
}
private void saveHighScore() {
new Thread(() -> {
try {
Path scoreFile = Paths.get(System.getProperty("user.home"), "dino-best-scores.txt");
Files.write(scoreFile, String.valueOf(highScore).getBytes());
} catch (IOException e) {
System.err.println("Error saving high score: " + e.getMessage());
}
}).start();
}
private void playSound(Clip clip) {
if (clip != null) {
new Thread(() -> {
try {
if (clip.isRunning()) {
clip.stop();
}
clip.setFramePosition(0);
clip.start();
} catch (Exception e) {
// Silently fail
}
}).start();
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (!gameStarted || paused) {
repaint();
return;
}
if (!gameOver) {
updateGameLogic();
}
repaint();
}
private void updateGameLogic() {
frameCount++;
updateScoreAndSpeed();
updatePlayer();
updateEnvironment();
spawnAndMoveObstacles();
}
private void updateScoreAndSpeed() {
if (frameCount % 6 == 0) {
score++;
if (score % 100 == 0) {
long currentTime = System.currentTimeMillis();
if (currentTime - lastScoreTime > 100) {
playSound(scoreSound);
lastScoreTime = currentTime;
}
}
}
if (frameCount % 900 == 0 && gameSpeed < MAX_SPEED) {
gameSpeed += SPEED_INCREMENT;
minObstacleDistance = Math.max(40, 60 - ((gameSpeed - INITIAL_SPEED) * 2));
maxObstacleDistance = Math.max(80, 120 - ((gameSpeed - INITIAL_SPEED) * 3));
}
}
private void updatePlayer() {
if (isJumping) {
velocityY += GRAVITY;
dinoY += velocityY;
if (dinoY >= groundY) {
dinoY = groundY;
isJumping = false;
velocityY = 0;
}
}
int animSpeed = Math.max(3, 6 - ((gameSpeed - INITIAL_SPEED) / 2));
if (frameCount % animSpeed == 0) {
animFrame = (animFrame + 1) % 2;
}
}
private void updateEnvironment() {
landX -= gameSpeed;
if (land != null && landX <= -land.getWidth()) {
landX = 0;
}
for (Cloud c : clouds) {
c.x -= 1;
if (cloud != null && c.x < -cloud.getWidth()) {
c.x = WIDTH + rand.nextInt(200);
c.y = 50 + rand.nextInt(100);
}
}
}
private void spawnAndMoveObstacles() {
obstacleTimer++;
int spawnDelay = minObstacleDistance + rand.nextInt(maxObstacleDistance - minObstacleDistance);
if (obstacleTimer > spawnDelay) {
spawnObstacle();
obstacleTimer = 0;
}
for (int i = obstacles.size() - 1; i >= 0; i--) {
Obstacle obs = obstacles.get(i);
obs.x -= gameSpeed;
if (obs.x < -obs.width) {
obstacles.remove(i);
} else if (checkCollision(obs)) {
gameOver = true;
playSound(deadSound);
if (score > highScore) {
highScore = score;
saveHighScore();
}
}
}
}
private void spawnObstacle() {
if (!obstacles.isEmpty()) {
Obstacle last = obstacles.get(obstacles.size() - 1);
if (last.x > WIDTH - 200) {
return;
}
}
int birdChance = Math.min(4, ((gameSpeed - INITIAL_SPEED) / 2) + 2);
int type = rand.nextInt(10);
if (type < (10 - birdChance)) {
BufferedImage[] cacti = {cactus1, cactus2, cactus3, cactus4, cactus5, cactus6};
BufferedImage cactusImg = cacti[rand.nextInt(cacti.length)];
if (cactusImg != null) {
obstacles.add(new Obstacle(WIDTH, GROUND_Y - cactusImg.getHeight(),
cactusImg.getWidth(), cactusImg.getHeight(),
cactusImg, false));
}
} else {
if (birdFly1 != null) {
int birdHeight = birdFly1.getHeight();
int[] heights = {
GROUND_Y - birdHeight, // Basso
GROUND_Y - birdHeight - 100, // Alto
GROUND_Y - birdHeight - 60 // Medio
};
int birdY = heights[rand.nextInt(heights.length)];
obstacles.add(new Obstacle(WIDTH, birdY,
birdFly1.getWidth(), birdFly1.getHeight(),
birdFly1, true));
}
}
}
private Rectangle getDinoHitbox() {
if (isDucking) {
return new Rectangle(
dinoX + HITBOX_INSET,
GROUND_Y - dinoDuckHeight + HITBOX_INSET,
dinoDuckWidth - 2 * HITBOX_INSET,
dinoDuckHeight - 2 * HITBOX_INSET
);
} else {
return new Rectangle(
dinoX + HITBOX_INSET,
dinoY + HITBOX_INSET,
dinoWidth - 2 * HITBOX_INSET,
dinoHeight - 2 * HITBOX_INSET
);
}
}
private boolean checkCollision(Obstacle obs) {
Rectangle dinoRect = getDinoHitbox();
Rectangle obsRect = new Rectangle(
obs.x + HITBOX_INSET,
obs.y + HITBOX_INSET,
obs.width - 2 * HITBOX_INSET,
obs.height - 2 * HITBOX_INSET
);
return dinoRect.intersects(obsRect);
}
private void resetGameData() {
score = 0;
gameSpeed = INITIAL_SPEED;
frameCount = 0;
dinoY = groundY;
velocityY = 0;
isJumping = false;
isDucking = false;
obstacles.clear();
obstacleTimer = 0;
minObstacleDistance = 60;
maxObstacleDistance = 120;
}
private void reset() {
gameOver = false;
gameStarted = true;
resetGameData();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
drawClouds(g2d);
drawGround(g2d);
drawDino(g2d);
drawObstacles(g2d);
drawUI(g2d);
drawOverlays(g2d);
}
private void drawClouds(Graphics2D g2d) {
for (Cloud c : clouds) {
if (cloud != null) {
g2d.drawImage(cloud, c.x, c.y, null);
}
}
}
private void drawGround(Graphics2D g2d) {
if (land != null) {
g2d.drawImage(land, landX, GROUND_Y, null);
g2d.drawImage(land, landX + land.getWidth(), GROUND_Y, null);
}
g2d.setColor(new Color(83, 83, 83));
g2d.fillRect(0, GROUND_Y - 2, WIDTH, 2);
}
private void drawDino(Graphics2D g2d) {
BufferedImage dinoImg = getDinoImage();
if (dinoImg != null) {
if (isDucking) {
g2d.drawImage(dinoImg, dinoX, GROUND_Y - dinoDuckHeight, null);
} else {
g2d.drawImage(dinoImg, dinoX, dinoY, null);
}
}
}
private void drawObstacles(Graphics2D g2d) {
for (Obstacle obs : obstacles) {
if (obs.isBird) {
BufferedImage birdImg = (frameCount % 10 < 5) ? birdFly1 : birdFly2;
if (birdImg != null) {
g2d.drawImage(birdImg, obs.x, obs.y, null);
}
} else {
if (obs.img != null) {
g2d.drawImage(obs.img, obs.x, obs.y, null);
}
}
}
}
private void drawUI(Graphics2D g2d) {
g2d.setColor(new Color(83, 83, 83));
g2d.setFont(new Font("Courier New", Font.BOLD, 16));
if (hiImg != null && highScore > 0) {
g2d.drawImage(hiImg, WIDTH - 200, 20, null);
g2d.drawString(String.format("%05d", highScore), WIDTH - 150, 35);
}
g2d.drawString(String.format("%05d", score), WIDTH - 80, 35);
}
private void drawOverlays(Graphics2D g2d) {
if (gameOver) {
if (gameOverImg != null) {
g2d.drawImage(gameOverImg, WIDTH / 2 - gameOverImg.getWidth() / 2, 100, null);
}
if (replayImg != null) {
g2d.drawImage(replayImg, WIDTH / 2 - replayImg.getWidth() / 2, 150, null);
}
g2d.setFont(new Font("Arial", Font.BOLD, 18));
g2d.drawString("Press SPACE to restart", WIDTH / 2 - 110, 200);
} else if (!gameStarted) {
g2d.setColor(new Color(83, 83, 83));
g2d.setFont(new Font("Arial", Font.BOLD, 24));
String msg = "Press SPACE to Start";
FontMetrics fm = g2d.getFontMetrics();
int msgWidth = fm.stringWidth(msg);
g2d.drawString(msg, (WIDTH - msgWidth) / 2, HEIGHT / 2);
g2d.setFont(new Font("Arial", Font.PLAIN, 14));
String controls = "↓ to duck • P to pause";
msgWidth = g2d.getFontMetrics().stringWidth(controls);
g2d.drawString(controls, (WIDTH - msgWidth) / 2, HEIGHT / 2 + 30);
} else if (paused) {
g2d.setColor(new Color(83, 83, 83));
g2d.setFont(new Font("Arial", Font.BOLD, 36));
String msg = "PAUSED";
FontMetrics fm = g2d.getFontMetrics();
int msgWidth = fm.stringWidth(msg);
g2d.drawString(msg, (WIDTH - msgWidth) / 2, HEIGHT / 2);
}
}
private BufferedImage getDinoImage() {
if (gameOver) {
return dinoDead;
} else if (isJumping) {
return dinoJump;
} else if (isDucking) {
return (animFrame == 0) ? dinoDownRun1 : dinoDownRun2;
} else {
return (animFrame == 0) ? dinoRun1 : dinoRun2;
}
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
if (!gameStarted) {
gameStarted = true;
} else if (gameOver) {
reset();
} else if (!isJumping && !isDucking) {
isJumping = true;
velocityY = JUMP_STRENGTH;
playSound(jumpSound);
}
}
if (key == KeyEvent.VK_DOWN && !isJumping && gameStarted && !gameOver) {
isDucking = true;
}
if (key == KeyEvent.VK_UP && !gameStarted) {
gameStarted = true;
}
if ((key == KeyEvent.VK_P || key == KeyEvent.VK_ESCAPE) && gameStarted && !gameOver) {
paused = !paused;
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
isDucking = false;
}
}
@Override
public void keyTyped(KeyEvent e) {}
private static class Obstacle {
int x;
int y, width, height;
BufferedImage img;
boolean isBird;
Obstacle(int x, int y, int width, int height, BufferedImage img, boolean isBird) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.img = img;
this.isBird = isBird;
}
}
private static class Cloud {
int x;
int y;
Cloud(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Java Dino Game");
try {
InputStream iconStream = DinoGame.class.getResourceAsStream("/dino-jump.png");
if (iconStream != null) {
BufferedImage icon = ImageIO.read(iconStream);
frame.setIconImage(icon);
}
} catch (Exception e) {
System.err.println("Could not load icon: " + e.getMessage());
}
DinoGame game = new DinoGame();
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
game.requestFocusInWindow();
});
}
}

30
DisegnoPazzo/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
DisegnoPazzo/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
DisegnoPazzo/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
DisegnoPazzo/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/DisegnoPazzo.iml" filepath="$PROJECT_DIR$/DisegnoPazzo.iml" />
</modules>
</component>
</project>

6
DisegnoPazzo/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,111 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
public class CerchioTrascinabile extends JFrame {
public CerchioTrascinabile() {
setTitle("Cerchio Trascinabile");
setSize(600, 500);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
PannelloCerchio pannello = new PannelloCerchio();
JButton btnCancella = new JButton("Cancella");
btnCancella.addActionListener(e -> pannello.cancellaCerchio());
JPanel bottomPanel = new JPanel();
bottomPanel.add(btnCancella);
setLayout(new BorderLayout());
add(pannello, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new CerchioTrascinabile().setVisible(true);
});
}
}
class PannelloCerchio extends JPanel {
private Cerchio cerchio;
private boolean dragging = false;
public PannelloCerchio() {
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (cerchio == null) {
cerchio = new Cerchio(e.getX(), e.getY());
repaint();
} else if (cerchio.contiene(e.getX(), e.getY())) {
dragging = true;
}
}
@Override
public void mouseReleased(MouseEvent e) {
dragging = false;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (dragging && cerchio != null) {
cerchio.muovi(e.getX(), e.getY());
repaint();
}
}
});
}
public void cancellaCerchio() {
cerchio = null;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (cerchio != null) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
cerchio.disegna(g2d);
}
}
}
class Cerchio {
private int x, y;
private static final int RAGGIO = 40;
public Cerchio(int x, int y) {
this.x = x;
this.y = y;
}
public void muovi(int nuovoX, int nuovoY) {
this.x = nuovoX;
this.y = nuovoY;
}
public boolean contiene(int px, int py) {
int dx = px - x;
int dy = py - y;
return dx * dx + dy * dy <= RAGGIO * RAGGIO;
}
public void disegna(Graphics2D g2d) {
g2d.setColor(new Color(70, 130, 180));
g2d.fillOval(x - RAGGIO, y - RAGGIO, RAGGIO * 2, RAGGIO * 2);
g2d.setColor(new Color(30, 90, 140));
g2d.setStroke(new BasicStroke(2));
g2d.drawOval(x - RAGGIO, y - RAGGIO, RAGGIO * 2, RAGGIO * 2);
}
}

10
Figure/.classpath Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

28
Figure/.project Normal file
View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Figure</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1758261738047</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

112
Figure/src/FiguraMain.java Normal file
View File

@@ -0,0 +1,112 @@
/*
Progettare un sistema per gestire una griglia bidimensionale di figure geometriche.
Ogni cella della griglia può contenere una figura (come un cerchio o un quadrato),
oppure essere vuota.
-
Ogni figura deve implementare uninterfaccia Figura
che definisce un metodo per calcolare larea double calcolaArea();
e String descrizione(); che scrive il nome della figura
Le figure devono estendere una classe astratta FiguraAstratta
che implementa linterfaccia Figura e fornisce un metodo descrizione() da sovrascrivere.
Nel main, dovrai:
--
1) Creare un array bidimensionale di Figura (Figura[][] griglia = new Figura[3][3];)
2) Inserire alcune figure nella griglia.
3) Calcolare larea totale delle figure nella griglia.
4) Gestire eventuali eccezioni con try-catch (es. inserimento in posizione fuori dallarray).
*/
interface Figura {
double calcolaArea();
String descrizione();
}
abstract class FiguraAstratta implements Figura {
protected String nome;
public FiguraAstratta(String nome) {
this.nome = nome;
}
public abstract double calcolaArea();
public String descrizione() {
return "Figura: " + nome;
}
}
class Cerchio extends FiguraAstratta {
private double raggio;
public Cerchio(double raggio) {
super("Cerchio");
this.raggio = raggio;
}
@Override
public double calcolaArea() {
return Math.PI * raggio * raggio;
}
@Override
public String descrizione() {
return super.descrizione() + " con raggio " + raggio;
}
}
class Quadrato extends FiguraAstratta {
private double lato;
public Quadrato(double lato) {
super("Quadrato");
this.lato = lato;
}
@Override
public double calcolaArea() {
return lato * lato;
}
@Override
public String descrizione() {
return super.descrizione() + " con lato " + lato;
}
}
public class FiguraMain {
public static void main(String[] args) {
Figura[][] griglia = new Figura[3][3];
try {
griglia[0][0] = new Cerchio(2.0);
griglia[1][1] = new Quadrato(3.0);
griglia[2][2] = new Cerchio(1.5);
// Prova inserimento fuori dai limiti per scatenare un'eccezione
griglia[3][3] = new Quadrato(4.0); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Errore: tentativo di accesso fuori dai limiti dell'array.");
} catch (Exception e) {
System.out.println("Errore generico: " + e.getMessage());
}
double areaTotale = 0.0;
for (int i = 0; i < griglia.length; i++) {
for (int j = 0; j < griglia[i].length; j++) {
if (griglia[i][j] != null) {
System.out.println("Figura in posizione [" + i + "][" + j + "]: "
+ griglia[i][j].descrizione() + " - Area: " + griglia[i][j].calcolaArea());
areaTotale += griglia[i][j].calcolaArea();
}
}
}
System.out.println("Area totale delle figure nella griglia: " + areaTotale);
}
}

30
LabirintoGUI/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
LabirintoGUI/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
LabirintoGUI/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
LabirintoGUI/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/LabirintoGUI.iml" filepath="$PROJECT_DIR$/LabirintoGUI.iml" />
</modules>
</component>
</project>

6
LabirintoGUI/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,276 @@
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class MazeGame extends JFrame {
private static final int ROWS = 21;
private static final int COLS = 31;
private static final int CELL_SIZE = 25;
private static final int WALL = 0;
private static final int PATH = 1;
private static final int END = 3;
private static final int PLAYER = 4;
private final int[][] maze;
private int playerRow, playerCol;
private int endRow, endCol;
private MazePanel mazePanel;
private JLabel statusLabel;
private JLabel movesLabel;
private int moveCount = 0;
public MazeGame() {
setTitle("Gioco del Labirinto");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
maze = new int[ROWS][COLS];
generateMaze();
setupUI();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void setupUI() {
setLayout(new BorderLayout());
// Panel superiore con informazioni
JPanel topPanel = new JPanel(new GridLayout(2, 1));
topPanel.setBackground(new Color(44, 62, 80));
topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
statusLabel = new JLabel("Raggiungi la bandiera! Usa le frecce per muoverti", SwingConstants.CENTER);
statusLabel.setFont(new Font("Arial", Font.BOLD, 16));
statusLabel.setForeground(Color.WHITE);
movesLabel = new JLabel("Mosse: 0", SwingConstants.CENTER);
movesLabel.setFont(new Font("Arial", Font.PLAIN, 14));
movesLabel.setForeground(new Color(52, 152, 219));
topPanel.add(statusLabel);
topPanel.add(movesLabel);
// Panel del labirinto
mazePanel = new MazePanel();
mazePanel.setFocusable(true);
mazePanel.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
handleKeyPress(e.getKeyCode());
}
});
// Panel inferiore con pulsanti
JPanel bottomPanel = new JPanel();
bottomPanel.setBackground(new Color(44, 62, 80));
bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JButton newGameButton = new JButton("Nuovo Gioco");
newGameButton.setFont(new Font("Arial", Font.BOLD, 14));
newGameButton.setBackground(new Color(46, 204, 113));
newGameButton.setForeground(Color.WHITE);
newGameButton.setFocusPainted(false);
newGameButton.addActionListener(e -> newGame());
bottomPanel.add(newGameButton);
add(topPanel, BorderLayout.NORTH);
add(mazePanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
}
private void generateMaze() {
// Inizializza con muri
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
maze[i][j] = WALL;
}
}
// Genera percorsi usando DFS
Random rand = new Random();
Stack<int[]> stack = new Stack<>();
int startRow = 1;
int startCol = 1;
maze[startRow][startCol] = PATH;
stack.push(new int[]{startRow, startCol});
int[][] directions = {{-2, 0}, {2, 0}, {0, -2}, {0, 2}};
while (!stack.isEmpty()) {
int[] current = stack.peek();
int row = current[0];
int col = current[1];
java.util.List<int[]> neighbors = new ArrayList<>();
for (int[] dir : directions) {
int newRow = row + dir[0];
int newCol = col + dir[1];
if (newRow > 0 && newRow < ROWS - 1 &&
newCol > 0 && newCol < COLS - 1 &&
maze[newRow][newCol] == WALL) {
neighbors.add(new int[]{newRow, newCol, row + dir[0]/2, col + dir[1]/2});
}
}
if (!neighbors.isEmpty()) {
int[] next = neighbors.get(rand.nextInt(neighbors.size()));
maze[next[2]][next[3]] = PATH;
maze[next[0]][next[1]] = PATH;
stack.push(new int[]{next[0], next[1]});
} else {
stack.pop();
}
}
// Posiziona giocatore e fine
playerRow = 1;
playerCol = 1;
endRow = ROWS - 2;
endCol = COLS - 2;
maze[playerRow][playerCol] = PLAYER;
maze[endRow][endCol] = END;
}
private void handleKeyPress(int keyCode) {
int newRow = playerRow;
int newCol = playerCol;
switch (keyCode) {
case KeyEvent.VK_UP:
newRow--;
break;
case KeyEvent.VK_DOWN:
newRow++;
break;
case KeyEvent.VK_LEFT:
newCol--;
break;
case KeyEvent.VK_RIGHT:
newCol++;
break;
default:
return;
}
// Verifica se la mossa è valida
if (newRow >= 0 && newRow < ROWS && newCol >= 0 && newCol < COLS) {
if (maze[newRow][newCol] != WALL) {
// Muovi il giocatore
maze[playerRow][playerCol] = PATH;
playerRow = newRow;
playerCol = newCol;
// Verifica se ha raggiunto la fine
if (playerRow == endRow && playerCol == endCol) {
maze[playerRow][playerCol] = PLAYER;
mazePanel.repaint();
showVictory();
} else {
maze[playerRow][playerCol] = PLAYER;
moveCount++;
movesLabel.setText("Mosse: " + moveCount);
mazePanel.repaint();
}
}
}
}
private void showVictory() {
statusLabel.setText("🎉 Complimenti! Hai vinto in " + moveCount + " mosse! 🎉");
statusLabel.setForeground(new Color(46, 204, 113));
Timer timer = new Timer(3000, e -> {
int choice = JOptionPane.showConfirmDialog(
this,
"Hai completato il labirinto in " + moveCount + " mosse!\nVuoi giocare di nuovo?",
"Vittoria!",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE
);
if (choice == JOptionPane.YES_OPTION) {
newGame();
}
});
timer.setRepeats(false);
timer.start();
}
private void newGame() {
moveCount = 0;
movesLabel.setText("Mosse: 0");
statusLabel.setText("Raggiungi la bandiera! Usa le frecce per muoverti");
statusLabel.setForeground(Color.WHITE);
generateMaze();
mazePanel.repaint();
mazePanel.requestFocusInWindow();
}
class MazePanel extends JPanel {
public MazePanel() {
setPreferredSize(new Dimension(COLS * CELL_SIZE, ROWS * CELL_SIZE));
setBackground(Color.BLACK);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
int x = j * CELL_SIZE;
int y = i * CELL_SIZE;
switch (maze[i][j]) {
case WALL:
g2d.setColor(new Color(52, 73, 94));
g2d.fillRect(x, y, CELL_SIZE, CELL_SIZE);
g2d.setColor(new Color(44, 62, 80));
g2d.drawRect(x, y, CELL_SIZE, CELL_SIZE);
break;
case PATH:
g2d.setColor(new Color(236, 240, 241));
g2d.fillRect(x, y, CELL_SIZE, CELL_SIZE);
break;
case END:
g2d.setColor(new Color(236, 240, 241));
g2d.fillRect(x, y, CELL_SIZE, CELL_SIZE);
// Bandiera
g2d.setColor(new Color(231, 76, 60));
g2d.fillRect(x + 10, y + 5, 10, 8);
g2d.setColor(new Color(52, 73, 94));
g2d.fillRect(x + 9, y + 5, 2, 15);
break;
case PLAYER:
g2d.setColor(new Color(236, 240, 241));
g2d.fillRect(x, y, CELL_SIZE, CELL_SIZE);
// Giocatore (cerchio)
g2d.setColor(new Color(52, 152, 219));
g2d.fillOval(x + 5, y + 5, CELL_SIZE - 10, CELL_SIZE - 10);
g2d.setColor(Color.WHITE);
g2d.fillOval(x + 10, y + 8, 4, 4);
g2d.fillOval(x + CELL_SIZE - 14, y + 8, 4, 4);
break;
}
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(MazeGame::new);
}
}

30
LabirintoTest/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
LabirintoTest/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
LabirintoTest/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
LabirintoTest/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/LabirintoTest.iml" filepath="$PROJECT_DIR$/LabirintoTest.iml" />
</modules>
</component>
</project>

6
LabirintoTest/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,127 @@
import java.util.*;
public class MazeSolver {
private static final int ROWS = 15;
private static final int COLS = 25;
private static final char WALL = '█';
private static final char PATH = ' ';
private static final char START = 'S';
private static final char END = 'E';
private static final char SOLUTION = '·';
private char[][] maze;
private boolean[][] visited;
private int startRow, startCol, endRow, endCol;
public MazeSolver() {
maze = new char[ROWS][COLS];
visited = new boolean[ROWS][COLS];
generateMaze();
}
private void generateMaze() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
maze[i][j] = WALL;
}
}
Random rand = new Random();
Stack<int[]> stack = new Stack<>();
startRow = 1;
startCol = 1;
maze[startRow][startCol] = PATH;
stack.push(new int[]{startRow, startCol});
int[][] directions = {{-2, 0}, {2, 0}, {0, -2}, {0, 2}};
while (!stack.isEmpty()) {
int[] current = stack.peek();
int row = current[0];
int col = current[1];
List<int[]> neighbors = new ArrayList<>();
for (int[] dir : directions) {
int newRow = row + dir[0];
int newCol = col + dir[1];
if (newRow > 0 && newRow < ROWS - 1 &&
newCol > 0 && newCol < COLS - 1 &&
maze[newRow][newCol] == WALL) {
neighbors.add(new int[]{newRow, newCol, row + dir[0]/2, col + dir[1]/2});
}
}
if (!neighbors.isEmpty()) {
int[] next = neighbors.get(rand.nextInt(neighbors.size()));
maze[next[2]][next[3]] = PATH; // Rompi il muro
maze[next[0]][next[1]] = PATH;
stack.push(new int[]{next[0], next[1]});
} else {
stack.pop();
}
}
endRow = ROWS - 2;
endCol = COLS - 2;
maze[startRow][startCol] = START;
maze[endRow][endCol] = END;
}
private void printMaze() {
System.out.println("\n╔" + "".repeat(COLS) + "");
for (int i = 0; i < ROWS; i++) {
System.out.print("");
for (int j = 0; j < COLS; j++) {
System.out.print(maze[i][j]);
}
System.out.println("");
}
System.out.println("" + "".repeat(COLS) + "");
}
private boolean solveMaze(int row, int col, List<int[]> path) {
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
return false;
}
if (maze[row][col] == WALL || visited[row][col]) {
return false;
}
visited[row][col] = true;
path.add(new int[]{row, col});
if (row == endRow && col == endCol) {
return true;
}
if (solveMaze(row - 1, col, path) ||
solveMaze(row + 1, col, path) ||
solveMaze(row, col - 1, path) ||
solveMaze(row, col + 1, path)) {
return true;
}
path.remove(path.size() - 1);
return false;
}
private void markSolution(List<int[]> path) {
for (int[] pos : path) {
int row = pos[0];
int col = pos[1];
if (maze[row][col] != START && maze[row][col] != END) {
maze[row][col] = SOLUTION;
}
}
}
public void solve() {
System.out.println("LABIRINTO ORIGINALE:");
printMaze();
List<int[]> path = new ArrayList<>();
visited = new boolean[ROWS][COLS];
System.out.println("\nRisoluzione in corso...");
if (solveMaze(startRow, startCol, path)) {
markSolution(path);
System.out.println("\nLABIRINTO RISOLTO:");
printMaze();
System.out.println("\nPercorso trovato! Lunghezza: " + path.size() + " passi");
} else {
System.out.println("\nNessuna soluzione trovata!");
}
}
public static void main(String[] args) {
System.out.println("=== GENERATORE E RISOLUTORE DI LABIRINTI ===");
System.out.println("Legenda: " + START + " = Inizio, " + END + " = Fine, " +
SOLUTION + " = Soluzione");
MazeSolver solver = new MazeSolver();
solver.solve();
}
}

30
LePallineMeravigliose/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
LePallineMeravigliose/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
LePallineMeravigliose/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
LePallineMeravigliose/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/LePallineMeravigliose.iml" filepath="$PROJECT_DIR$/LePallineMeravigliose.iml" />
</modules>
</component>
</project>

6
LePallineMeravigliose/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,153 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
public class FallingBallsGUI extends JFrame {
private ArrayList<Ball> balls;
private boolean isPlaying = false;
private Timer timer;
private BallPanel ballPanel;
private Random random = new Random();
public FallingBallsGUI() {
setTitle("Palline che Cadono");
setSize(450, 750);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setLocationRelativeTo(null);
// Inizializza le palline
balls = new ArrayList<>();
Color[] colors = {
new Color(255, 107, 107),
new Color(78, 205, 196),
new Color(69, 183, 209),
new Color(255, 160, 122),
new Color(152, 216, 200),
new Color(247, 220, 111)
};
for (int i = 0; i < 6; i++) {
Ball ball = new Ball(
random.nextInt(360) + 20,
random.nextInt(200) * -1 - 20,
20,
random.nextDouble() * 2 + 1,
colors[i]
);
balls.add(ball);
}
// Pannello per disegnare le palline
ballPanel = new BallPanel();
add(ballPanel, BorderLayout.CENTER);
// Pannello per il bottone
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(new Color(245, 245, 245));
JButton playPauseButton = new JButton("Play");
playPauseButton.setFont(new Font("Arial", Font.BOLD, 18));
playPauseButton.setPreferredSize(new Dimension(150, 50));
playPauseButton.setBackground(new Color(76, 175, 80));
playPauseButton.setForeground(Color.WHITE);
playPauseButton.setFocusPainted(false);
playPauseButton.addActionListener(e -> {
isPlaying = !isPlaying;
if (isPlaying) {
playPauseButton.setText("Pause");
playPauseButton.setBackground(new Color(244, 67, 54));
} else {
playPauseButton.setText("Play");
playPauseButton.setBackground(new Color(76, 175, 80));
}
});
buttonPanel.add(playPauseButton);
add(buttonPanel, BorderLayout.SOUTH);
// Timer per l'animazione
timer = new Timer(16, e -> {
if (isPlaying) {
for (Ball ball : balls) {
ball.move();
// Se la pallina esce dal fondo, riposiziona in alto
if (ball.y - ball.radius > ballPanel.getHeight()) {
ball.y = random.nextInt(200) * -1 - 20;
ball.x = random.nextInt(ballPanel.getWidth() - 40) + 20;
ball.speed = random.nextDouble() * 2 + 1;
}
}
}
ballPanel.repaint();
});
timer.start();
}
// Classe per rappresentare una pallina
class Ball {
double x, y;
int radius;
double speed;
Color color;
Ball(double x, double y, int radius, double speed, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.speed = speed;
this.color = color;
}
void move() {
y += speed;
}
}
// Pannello personalizzato per disegnare le palline
class BallPanel extends JPanel {
BallPanel() {
setBackground(new Color(230, 240, 255));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ball ball : balls) {
// Disegna la pallina
g2d.setColor(ball.color);
g2d.fillOval((int)(ball.x - ball.radius),
(int)(ball.y - ball.radius),
ball.radius * 2,
ball.radius * 2);
// Bordo
g2d.setColor(new Color(0, 0, 0, 50));
g2d.setStroke(new BasicStroke(2));
g2d.drawOval((int)(ball.x - ball.radius),
(int)(ball.y - ball.radius),
ball.radius * 2,
ball.radius * 2);
// Effetto lucido
g2d.setColor(new Color(255, 255, 255, 150));
g2d.fillOval((int)(ball.x - 7),
(int)(ball.y - 7),
12, 12);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
FallingBallsGUI gui = new FallingBallsGUI();
gui.setVisible(true);
});
}
}

18
PrimaGUI/README.md Normal file
View File

@@ -0,0 +1,18 @@
## Getting Started
Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code.
## Folder Structure
The workspace contains two folders by default, where:
- `src`: the folder to maintain sources
- `lib`: the folder to maintain dependencies
Meanwhile, the compiled output files will be generated in the `bin` folder by default.
> If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there.
## Dependency Management
The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies).

14
PrimaGUI/src/App.java Normal file
View File

@@ -0,0 +1,14 @@
import javax.swing.JButton;
import javax.swing.JFrame;
public class App {
public static void main(String[] args) throws Exception {
JFrame f = new JFrame("Una finestra meravigliosa");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(100,100,800,600);
f.setLayout(null);
JButton b = new JButton("ok");
b.setBounds(100, 20, 100, 30);
f.add(b);
f.setVisible(true);
}
}

30
Prova1/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
.kotlin
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
Prova1/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
Prova1/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
Prova1/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Prova1.iml" filepath="$PROJECT_DIR$/Prova1.iml" />
</modules>
</component>
</project>

11
Prova1/Prova1.iml Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,152 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CirclePanelDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CirclePanelDemo().createAndShowGUI());
}
/* ----------------------------- */
/* 1. Finestra principale */
/* ----------------------------- */
private void createAndShowGUI() {
JFrame frame = new JFrame("Circle click, drag & delete");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
CirclePanel circlePanel = new CirclePanel();
frame.add(circlePanel, BorderLayout.CENTER);
JButton clearBtn = new JButton("Cancella cerchio");
clearBtn.addActionListener(e -> circlePanel.clearCircle());
JPanel btnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
btnPanel.add(clearBtn);
frame.add(btnPanel, BorderLayout.SOUTH);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null); // centra la finestra
frame.setVisible(true);
}
/* ----------------------------- */
/* 2. JPanel che disegna il cerchio */
/* ----------------------------- */
private static class CirclePanel extends JPanel {
private final int RADIUS = 30; // raggio fisso
private int circleX = -1; // centro X (-1 → nessun cerchio)
private int circleY = -1; // centro Y
/* variabili per il drag */
private boolean dragging = false;
private int offsetX, offsetY;
CirclePanel() {
setBackground(Color.WHITE);
MouseAdapter ma = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int mx = e.getX();
int my = e.getY();
/* Se il cerchio esiste */
if (circleX != -1 && circleY != -1) {
/* Se il click è dentro il cerchio → inizia drag */
if (isInsideCircle(mx, my)) {
dragging = true;
offsetX = mx - circleX;
offsetY = my - circleY;
} else {
// Click fuori dal cerchio: non fare nulla
dragging = false;
}
} else {
/* Nessun cerchio → creiamo un nuovo */
setCircle(mx, my);
}
}
@Override
public void mouseReleased(MouseEvent e) {
dragging = false;
}
@Override
public void mouseDragged(MouseEvent e) {
if (dragging && circleX != -1) {
int mx = e.getX();
int my = e.getY();
setCircle(mx - offsetX, my - offsetY);
}
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
/* ---------------------------------- */
/* 3. Utilità */
/* ---------------------------------- */
/** Verifica se il punto (x,y) è dentro il cerchio */
private boolean isInsideCircle(int x, int y) {
if (circleX == -1 || circleY == -1) return false;
int dx = x - circleX;
int dy = y - circleY;
return dx * dx + dy * dy <= RADIUS * RADIUS;
}
/** Imposta il centro del cerchio e ridisegna */
private void setCircle(int x, int y) {
circleX = x;
circleY = y;
repaint();
}
/** Cancella il cerchio (se presente) */
public void clearCircle() {
circleX = -1;
circleY = -1;
repaint();
}
/* ---------------------------------- */
/* 4. Disegno del pannello */
/* ---------------------------------- */
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (circleX == -1 || circleY == -1)
return; // nessun cerchio da disegnare
Graphics2D g2 = (Graphics2D) g.create();
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int topLeftX = circleX - RADIUS;
int topLeftY = circleY - RADIUS;
g2.setColor(Color.RED);
g2.fillOval(topLeftX, topLeftY, 2 * RADIUS, 2 * RADIUS);
// bordo bianco
g2.setStroke(new BasicStroke(2f));
g2.setColor(Color.WHITE);
g2.drawOval(topLeftX, topLeftY, 2 * RADIUS, 2 * RADIUS);
} finally {
g2.dispose();
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More