feat(Game.java): ajout fonction togglePause

This commit is contained in:
2025-11-01 10:23:51 +01:00
parent 974fa21c3d
commit 2488aec5a2
2 changed files with 40 additions and 9 deletions

View File

@@ -20,7 +20,7 @@ public class Game
private ArrayList<GameObserver> obs = new ArrayList<>();
private Random random = new Random();
private boolean pause = false;
private boolean paused = false;
public static Game create()
{
@@ -86,21 +86,37 @@ public class Game
return false;
}
private synchronized void step() throws InterruptedException
private void step() throws InterruptedException
{
// if (pause) wait();
for (GameObserver o : obs)
{
if (!o.apply())
synchronized (this)
{
System.err.println("Une erreur s'est produite pendant le jeu.");
System.exit(1);
// pause du jeu
if (paused) wait();
boolean isSuccess = o.apply();
if (!isSuccess)
{
System.err.println("Une erreur s'est produite pendant le jeu.");
System.exit(1);
}
}
}
}
public synchronized boolean togglePause()
{
if (paused)
{
notifyAll();
paused = false;
}
else paused = true;
return paused;
}
public void run()
{
if (this.cars == null || this.map == null)
@@ -108,7 +124,6 @@ public class Game
while (!isFinish())
{
// notifyAll();
try
{
step();

View File

@@ -1,11 +1,27 @@
public class Main {
public static void main(String[] args) {
public static void main(String[] args) throws InterruptedException {
Map m = Map.fromChars(new Character[][] {
{'3', '#', '2'},
{'#', ' ', 'S'},
{'9', '#', 'F'},
});
Thread t = new Thread(() -> {
while (true)
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Game.create().togglePause() ? "stop" : "fini");
}
});
t.start();
Game.create()
.init(3, m)
.run();