-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGameSpeedControlButton.java
More file actions
69 lines (57 loc) · 1.89 KB
/
GameSpeedControlButton.java
File metadata and controls
69 lines (57 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.ArrayList;
import java.util.List;
import greenfoot.GreenfootImage;
/**
* A special button that is used to change the game speed.
*/
public class GameSpeedControlButton extends Button {
public static final String[] IDLE_BUTTON_IMAGE_NAMES = { "fastforward-1-button.png", "fastforward-2-button.png" };
public static final String[] ACTIVE_BUTTON_IMAGE_NAMES = { "fastforward-1-button-active.png", "fastforward-2-button-active.png" };
private static List<GameSpeedControlButton> speedController = new ArrayList<>();
private int speed;
public GameSpeedControlButton(int speed, String idleImageName, String activeImageName) {
super(new GreenfootImage(idleImageName), new GreenfootImage(activeImageName));
setSpeed(speed);
speedController.add(this);
}
@Override
public void clickAction() {
speedToggle();
}
/**
* Changes the game speed in different ways when needed.
*/
private void speedToggle() {
GameWorld world = getWorld();
if(world.isPaused()) { // resume game with custom speed
world.getPauseResumeButton().pauseResumeToggle();
}
if(!world.isDefaultSpeed() && !isActive()) { // switch from another custom speed to this
for (GameSpeedControlButton gameExecutionController : speedController) {
gameExecutionController.turnOffSpeedButton();
}
turnOnSpeedButton();
} else if(!world.isDefaultSpeed() && isActive()) { // turn of this custom speed and return to default speed
turnOffSpeedButton();
world.setExecutionSpeed(GameWorld.DEFAULT_SPEED);
} else if(world.isDefaultSpeed() && !isActive()) {
turnOnSpeedButton();
}
}
private void turnOffSpeedButton() {
setActive(false);
}
private void turnOnSpeedButton() {
setActive(true);
getWorld().setExecutionSpeed(speed);
}
private void setSpeed(int speed) {
if(speed <= 0) {
this.speed = 1;
} else if(speed > 100) {
this.speed = 100;
} else {
this.speed = speed;
}
}
}