add tp Java

master
antoine.perederii 1 year ago
parent 950d52d748
commit 372a2d2d91

@ -0,0 +1,4 @@
# TP1 - JavaFX
## Sujet

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

@ -3,6 +3,7 @@
<component name="NewModuleRootManager" inherit-compiler-output="true"> <component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output /> <exclude-output />
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/rsrc" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.AreaChart?>
<?import javafx.scene.chart.CategoryAxis?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.ProgressBar?>
<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.control.ToolBar?>
<?import javafx.scene.layout.AnchorPane?>
<TabPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" tabClosingPolicy="UNAVAILABLE" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/18">
<tabs>
<Tab text="Untitled Tab 1">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<ToolBar prefHeight="40.0" prefWidth="604.0">
<items>
<Button mnemonicParsing="false" text="Button" />
</items>
</ToolBar>
<CheckBox layoutX="14.0" layoutY="153.0" mnemonicParsing="false" text="CheckBox" />
<CheckBox layoutX="14.0" layoutY="66.0" mnemonicParsing="false" text="CheckBox" />
<CheckBox layoutX="14.0" layoutY="123.0" mnemonicParsing="false" text="CheckBox" />
<CheckBox layoutX="14.0" layoutY="92.0" mnemonicParsing="false" text="CheckBox" />
<ProgressBar layoutX="14.0" layoutY="322.0" prefHeight="20.0" prefWidth="426.0" progress="0.0" />
<Button fx:id="myButton" mnemonicParsing="false" text="Button" />
<CheckBox layoutX="14.0" layoutY="276.0" mnemonicParsing="false" text="CheckBox" />
<CheckBox layoutX="14.0" layoutY="247.0" mnemonicParsing="false" text="CheckBox" />
<CheckBox layoutX="14.0" layoutY="215.0" mnemonicParsing="false" text="CheckBox" />
<CheckBox layoutX="14.0" layoutY="185.0" mnemonicParsing="false" text="CheckBox" />
</children></AnchorPane>
</content>
</Tab>
<Tab text="Untitled Tab 2">
<content>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
<children>
<AreaChart prefHeight="328.0" prefWidth="600.0">
<xAxis>
<CategoryAxis side="BOTTOM" />
</xAxis>
<yAxis>
<NumberAxis side="LEFT" />
</yAxis>
</AreaChart>
<Button layoutX="269.0" layoutY="316.0" mnemonicParsing="false" text="Button" />
</children></AnchorPane>
</content>
</Tab>
</tabs>
</TabPane>

@ -1,12 +1,24 @@
package launch; package launch;
import javafx.application.Application; import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage; import javafx.stage.Stage;
import view.Fenetre;
import java.io.IOException;
import java.util.Objects;
public class Launch extends Application { public class Launch extends Application {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Fenetre.fxml"));
public Launch() throws IOException {
}
@Override @Override
public void start(Stage primaryStage) throws Exception { public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(root));
primaryStage.show(); primaryStage.show();
} }
} }

@ -0,0 +1,13 @@
package view;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import java.awt.*;
public class Fenetre {
@FXML
private Button myButton = new Button();
}

@ -0,0 +1,133 @@
# ---> JetBrains
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# ---> macOS
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# ---> Java
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

@ -0,0 +1,15 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="FieldCanBeLocal" enabled="true" level="WARNING" enabled_by_default="true">
<option name="EXCLUDE_ANNOS">
<value>
<list size="1">
<item index="0" class="java.lang.String" itemvalue="javafx.fxml.FXML" />
</list>
</value>
</option>
<option name="IGNORE_FIELDS_USED_IN_MULTIPLE_METHODS" value="true" />
</inspection_tool>
</profile>
</component>

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

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

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

@ -0,0 +1,85 @@
# La course de dé (version JavaFX)
L'objectif de ce TP est d'ajouter une interface graphique au jeu de dé que vous avez codé en C++ en première année. Pour rappel :
> La «course de dé» se joue en lançant un dé. Les joueurs jouent tour à tour (pour ce TP nous nous limiterons à deux joueurs). Lorsque c'est à son tour, le joueur lance un dé et, tant qu'il ne fait pas 1, accumule les points des lancers successifs. S'il fait 1, il perd les points qu'il avait accumulés pendant son tour de jeu et la main passe, c'est à l'autre joueur de jouer. Un joueur peut sciemment décider d'arrêter de lancer le dé et ainsi sécuriser le score de son tour de jeu. Le premier joueur qui atteint un score de victoire (par exemple 50) gagne.
Afin de vous concenter sur l'interface graphique, nous vous fournissons la version Java du jeu que vous avez codé en C++. La conception de ce dernier est rappelé ci-dessous.
```plantuml
@startuml
skinparam defaultFontName Tahoma
skinparam classAttributeIconSize 0
skinparam monochrome true
skinparam shadowing false
skinparam linetype ortho
skinparam class {
BackgroundColor transparent
}
skinparam package {
BackgroundColor transparent
}
hide circle
package launcher {
class ConsoleGame {
+{static} main(args : String[])
}
}
package model {
class Dice {
-{static}NB_FACES_DEFAULT : int = 6 {frozen}
-nbFaces : int
-value : int
+Dice(nbFaces : int)
+Dice()
+getValue() : int
+roll() : int
+clear()
}
class Player {
-{static}num : int = 0
-name : string
-totalScore : int
-currentScore : int
+Player(name : string)
+Player()
+getName() : string
+getCurrentScore() : int
+setCurrentScore(score : int)
+getTotalScore() : int
+setTotalScore(score : int)
}
class Game {
+{static}LOSE_DICE_VALUE : int = 1 {frozen}
+{static}SCORE_TO_WIN : int = 50 {frozen}
-gameOver : boolean
-currentPlayerIndex : int
+Game()
+addPlayer(player : Player)
+getCurrentPlayer() : Player
+rollDice()
+getDiceValue() : int
+isGameOver() : boolean
+passToNextPlayer()
+restart()
}
Game --> "-dice" Dice
Game --> "*\n-players" Player
ConsoleGame ..> Game
}
@enduml
```

@ -0,0 +1,13 @@
<?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$/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="jdk" jdkName="18" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="lib" level="application" />
</component>
</module>

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Text?>
<BorderPane xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1">
<right>
<Button fx:id="buttonHold" mnemonicParsing="false" text="H" BorderPane.alignment="CENTER" />
</right>
<left>
<Button fx:id="buttonRoll" mnemonicParsing="false" text="R" BorderPane.alignment="CENTER" />
</left>
<top>
<Text fx:id="topText" text="Fight de Cedric et Jerome" BorderPane.alignment="CENTER" />
</top>
<bottom>
<Text fx:id="bottomText" text="Jerome à fait 1, il pert ! Gros noob !" BorderPane.alignment="CENTER" />
</bottom>
<center>
<Text fx:id="centerText" text="Jérome lance le dé, il fait 1" BorderPane.alignment="CENTER" />
</center>
</BorderPane>

@ -0,0 +1,74 @@
package launcher;
import model.Game;
import model.Player;
import java.util.Scanner;
public class ConsoleGame {
private static final String PROMPT = ", enter R to roll the dice or H to hold your score: ";
private static final String ALLOWED_KEYS = "[rRhH]";
private static final Scanner SCANNER = new Scanner(System.in);
private enum Choice {ROLL, HOLD, QUIT}
static public Choice readChoice(String playerName) {
String line = null;
System.out.print(playerName + PROMPT);
while (SCANNER.hasNext()) {
line = SCANNER.nextLine().trim();
if (line.length() == 1 && line.matches(ALLOWED_KEYS))
break;
System.out.print(playerName + PROMPT);
}
if (line == null)
return Choice.QUIT;
else {
return switch (line.charAt(0)) {
case 'r', 'R' -> Choice.ROLL;
case 'h', 'H' -> Choice.HOLD;
default -> throw new IllegalStateException("impossible branch");
};
}
}
public static void main(String[] args) {
Game teacherFight = new Game();
teacherFight.addPlayer(new Player("Laurent"));
teacherFight.addPlayer(new Player("Cédric"));
System.out.println("Laurent and Cédric are about to start a dice fight !");
while (!teacherFight.isGameOver()) {
Player currentPlayer = teacherFight.getCurrentPlayer();
System.out.println(currentPlayer);
Choice choice = readChoice(currentPlayer.getName());
switch (choice) {
case ROLL -> {
teacherFight.rollDice();
int diceValue = 0;
try {
diceValue = teacherFight.getDiceValue();
} catch (IllegalAccessException e) {
teacherFight.rollDice();
}
System.out.println(currentPlayer.getName() + " is rolling the dice… and get a " + diceValue);
if (diceValue == Game.LOSE_DICE_VALUE)
System.out.println(currentPlayer.getName() + " loses his turn.");
}
case HOLD -> {
teacherFight.passToNextPlayer();
System.out.println(currentPlayer.getName() + " decides to hold his score and has now " + currentPlayer.getTotalScore());
}
case QUIT -> {
System.out.println(currentPlayer.getName() + " quits.");
return;
}
}
}
Player winner = teacherFight.getCurrentPlayer();
System.out.println(winner.getName() + " wins the game !");
}
}

@ -0,0 +1,24 @@
package launcher;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import view.Fenetre;
import java.io.IOException;
import java.util.Objects;
public class Launch extends Application {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/Fenetre.fxml"));
public Launch() throws IOException {
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}

@ -0,0 +1,33 @@
package model;
import java.util.Random;
public class Dice {
private static final Random RANDOM = new Random();
private static final int NB_FACES_DEFAULT = 6;
private final int nbFaces;
private int value;
public Dice(int nbFaces) {
this.nbFaces = nbFaces;
}
public Dice() {
this(NB_FACES_DEFAULT);
}
public int getValue() throws IllegalAccessException {
if (value == 0)
throw new IllegalAccessException("The dice must be rolled first.");
return value;
}
public int roll() {
return value = RANDOM.nextInt(nbFaces) + 1;
}
public void clear() {
value = 0;
}
}

@ -0,0 +1,67 @@
package model;
import java.util.ArrayList;
import java.util.List;
public class Game {
public static final int LOSE_DICE_VALUE = 1;
public static final int SCORE_TO_WIN = 50;
private final Dice dice = new Dice();
private final List<Player> players = new ArrayList<>();
private int currentPlayerIndex = 0;
private boolean gameOver;
public boolean isGameOver() {
return gameOver;
}
public void addPlayer(Player player) {
players.add(player);
}
public Player getCurrentPlayer() {
return players.get(currentPlayerIndex);
}
public void rollDice() {
int rollValue = dice.roll();
Player currentPlayer = players.get(currentPlayerIndex);
if (rollValue != LOSE_DICE_VALUE) {
currentPlayer.setCurrentScore(currentPlayer.getCurrentScore() + rollValue);
} else {
currentPlayer.setCurrentScore(0);
passToNextPlayer();
}
}
public void passToNextPlayer() {
if (!isGameOver()) {
Player currentPlayer = players.get(currentPlayerIndex);
int newTotalScore = currentPlayer.getTotalScore() + currentPlayer.getCurrentScore();
currentPlayer.setTotalScore(newTotalScore);
currentPlayer.setCurrentScore(0);
if (newTotalScore >= SCORE_TO_WIN) {
gameOver = true;
} else {
currentPlayerIndex = ++currentPlayerIndex % players.size();
}
}
}
public void restart() {
dice.clear();
players.forEach(player -> {
player.setCurrentScore(0);
player.setTotalScore(0);
});
gameOver = false;
passToNextPlayer();
}
public int getDiceValue() throws IllegalAccessException {
return dice.getValue();
}
}

@ -0,0 +1,47 @@
package model;
public class Player {
private static final String BASE_PLAYER_NAME_DEFAULT = "Player ";
private static int num = 0;
private String name;
private int totalScore;
private int currentScore;
public Player(String name) {
setName(name);
}
public Player() {
this(BASE_PLAYER_NAME_DEFAULT + ++num);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotalScore() {
return totalScore;
}
public void setTotalScore(int score) {
totalScore = score;
}
public int getCurrentScore() {
return currentScore;
}
public void setCurrentScore(int score) {
currentScore = score;
}
@Override
public String toString() {
return name + " (" + totalScore + ") has currently " + currentScore;
}
}

@ -0,0 +1,77 @@
package view;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.text.Text;
import launcher.ConsoleGame;
import model.Game;
import model.Player;
import java.util.Scanner;
public class Fenetre {
@FXML
private Button buttonHold;
@FXML
private Button buttonRoll;
@FXML
private Text topText;
@FXML
private Text bottomText;
@FXML
private Text centerText;
// private static final String PROMPT = ", enter R to roll the dice or H to hold your score: ";
// private static final String ALLOWED_KEYS = "[rRhH]";
//
// private enum Choice {ROLL, HOLD, QUIT}
////
// public Choice readChoice(String playerName) {
// if(this.buttonHold.getOnMouseClicked()) {
// return Choice.HOLD;
// } else if(this.buttonRoll.getOnMouseClicked()) {
// return Choice.ROLL;
// }
// return null;
// }
// public static void main(String[] args) {
// Game teacherFight = new Game();
// teacherFight.addPlayer(new Player("Laurent"));
// teacherFight.addPlayer(new Player("Cédric"));
//
// System.out.println("Laurent and Cédric are about to start a dice fight !");
//
// while (!teacherFight.isGameOver()) {
// Player currentPlayer = teacherFight.getCurrentPlayer();
// System.out.println(currentPlayer);
// ConsoleGame.Choice choice = readChoice(currentPlayer.getName());
// switch (choice) {
// case ROLL -> {
// teacherFight.rollDice();
// int diceValue = 0;
// try {
// diceValue = teacherFight.getDiceValue();
// } catch (IllegalAccessException e) {
// teacherFight.rollDice();
// }
// System.out.println(currentPlayer.getName() + " is rolling the dice… and get a " + diceValue);
// if (diceValue == Game.LOSE_DICE_VALUE)
// System.out.println(currentPlayer.getName() + " loses his turn.");
// }
// case HOLD -> {
// teacherFight.passToNextPlayer();
// System.out.println(currentPlayer.getName() + " decides to hold his score and has now " + currentPlayer.getTotalScore());
// }
// case QUIT -> {
// System.out.println(currentPlayer.getName() + " quits.");
// return;
// }
// }
// }
//
// Player winner = teacherFight.getCurrentPlayer();
// System.out.println(winner.getName() + " wins the game !");
// }
}
Loading…
Cancel
Save