public GameCanvas(HelicopterGame midlet) {
this.midlet = midlet;
this.isRunning = true;
this.background = new Background("/background.png", 2); // Caminho e velocidade do background
new Thread(this).start();
}
protected void paint(Graphics g) {
// Atualiza e desenha o background
background.update();
background.draw(g);
// Aqui você desenha o helicóptero e outros elementos
}
public void run() {
while (isRunning) {
repaint();
try {
Thread.sleep(50); // Ajuste para controlar a taxa de atualização
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Para combinar os dois códigos e manter a funcionalidade original, além dos textos e comportamentos, precisamos integrar o HelicopterCanvas (do primeiro código) dentro do GameCanvas da classe HelicopterGame (do segundo código). Vou fazer essa união e preservar todas as funcionalidades e mensagens conforme solicitado:
java
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
// Classe principal do jogo
public class HelicopterGame extends MIDlet implements CommandListener {
private Display display;
private HelicopterCanvas helicopterCanvas;
public HelicopterGame() {
display = Display.getDisplay(this);
helicopterCanvas = new HelicopterCanvas(this);
}
protected void startApp() {
display.setCurrent(helicopterCanvas);
}
protected void pauseApp() {}
protected void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c.getLabel().equals("Quit")) {
notifyDestroyed();
}
}
}
// Classe que implementa o comportamento do helicóptero
class HelicopterCanvas extends GameCanvas implements Runnable {
private boolean isRunning;
private int helicopterX;
private int helicopterY;
private int currentFrame;
private int helicopterWidth = 40;
private int helicopterHeight = 20;
private Image[] helicopterSprites;
private static final int SPRITE_COUNT = 3;
private static final int FRAME_DELAY = 100;
private int screenWidth;
private int screenHeight;
private boolean isAscending;
private double gravityPercentage = 0.15D;
private double ascendPercentage = 0.2D;
private double velocity;
private Player ascendSound;
private Player idleSound;
private Background background;
public HelicopterCanvas(MIDlet midlet) {
super(true);
this.screenWidth = getWidth();
this.screenHeight = getHeight();
this.helicopterX = this.screenWidth / 2;
this.helicopterY = this.screenHeight / 2;
this.currentFrame = 0;
this.isRunning = true;
this.isAscending = false;
this.velocity = 0.0D;
loadSprites();
initAudio();
this.background = new Background("/background.png", 2); // Caminho e velocidade do background
new Thread(this).start();
}
private void loadSprites() {
this.helicopterSprites = new Image[3];
try {
this.helicopterSprites[0] = Image.createImage("/helicopter1.png");
this.helicopterSprites[1] = Image.createImage("/helicopter2.png");
this.helicopterSprites[2] = Image.createImage("/helicopter3.png");
System.out.println("Sprites carregados com sucesso.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Erro ao carregar sprites: " + e.getMessage());
}
}
private void initAudio() {
try {
this.ascendSound = Manager.createPlayer(getClass().getResourceAsStream("/ascend.amr"), "audio/amr");
this.ascendSound.setLoopCount(-1);
this.idleSound = Manager.createPlayer(getClass().getResourceAsStream("/helicopter.amr"), "audio/amr");
this.idleSound.setLoopCount(-1);
this.idleSound.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (this.isRunning) {
updateGame();
repaint();
try {
Thread.sleep(100L);
} catch (InterruptedException interruptedException) {}
}
}
protected void paint(Graphics g) {
// Atualiza e desenha o background
background.update();
background.draw(g);
g.setColor(255);
g.fillRect(0, 0, this.screenWidth, this.screenHeight);
if (this.helicopterSprites[this.currentFrame] != null) {
g.drawImage(this.helicopterSprites[this.currentFrame], this.helicopterX, this.helicopterY, Graphics.VCENTER | Graphics.HCENTER);
} else {
System.out.println("Erro: Sprite não carregado corretamente.");
}
}
private void updateGame() {
this.currentFrame = (this.currentFrame + 1) % 3;
double ascendRate = this.screenHeight * this.ascendPercentage / 100.0D;
double gravityRate = this.screenHeight * this.gravityPercentage / 100.0D;
if (this.isAscending) {
this.velocity = -ascendRate;
} else {
this.velocity += gravityRate;
}
this.helicopterY = (int)(this.helicopterY + this.velocity);
if (this.helicopterY < 0) {
this.helicopterY = 0;
this.velocity = 0.0D;
} else if (this.helicopterY > this.screenHeight) {
this.helicopterY = this.screenHeight;
this.velocity = 0.0D;
}
}
public void keyPressed(int keyCode) {
int gameAction = getGameAction(keyCode);
if (keyCode == 53 || gameAction == 8) {
this.isAscending = true;
increaseAscendPercentage();
try {
if (this.idleSound != null && this.idleSound.getState() == 400) {
this.idleSound.stop();
}
if (this.ascendSound != null && this.ascendSound.getState() != 400) {
this.ascendSound.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void keyReleased(int keyCode) {
if (keyCode == 53 || keyCode == -5 || getGameAction(keyCode) == 1) {
this.isAscending = false;
try {
if (this.ascendSound != null && this.ascendSound.getState() == 400) {
this.ascendSound.stop();
}
if (this.idleSound != null && this.idleSound.getState() != 400) {
this.idleSound.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void increaseAscendPercentage() {
this.ascendPercentage += 1.5D;
if (this.ascendPercentage > 0.9D) {
this.ascendPercentage = 0.9D;
}
}
public void reduceHelicopterSize() {
if (this.helicopterWidth > 0 && this.helicopterHeight > 0) {
this.helicopterWidth /= 2;
this.helicopterHeight /= 2;
this.helicopterX = this.screenWidth / 2;
this.helicopterY = this.screenHeight / 2;
}
}
}
// Classe para o background
class Background {
private Image image;
private int width;
private int height;
private int x;
private int y;
private int speed;
public Background(String imagePath, int speed) {
try {
this.image = Image.createImage(imagePath);
} catch (Exception e) {
e.printStackTrace();
}
this.width = image.getWidth();
this.height = image.getHeight();
this.speed = speed;
}
public void update() {
x -= speed;
if (x < -width) {
x = 0;
}
}
public void draw(Graphics g) {
g.drawImage(image, x, y, Graphics.TOP | Graphics.LEFT);
g.drawImage(image, x + width, y, Graphics.TOP | Graphics.LEFT);
}
}
Explicações:
HelicopterGame: Este é o MIDlet principal que inicia o aplicativo e exibe o HelicopterCanvas.
HelicopterCanvas: Integra o código do helicóptero no GameCanvas, mantendo a lógica do movimento e do som.
Background: Nova classe criada para representar um fundo rolável, utilizada no método paint do HelicopterCanvas.
Esta integração mantém a lógica original dos sprites do helicóptero e sons, enquanto adiciona a funcionalidade original de plano de fundo rolável da primeira implementação.
tente adaptar a background somente para dentro do helicoptercanvas.java
public class HelicopterGame extends MIDlet implements CommandListener {
private Display display;
private HelicopterCanvas gameCanvas;
private Command exitCommand;
code
public HelicopterGame() {
try {
this.display = Display.getDisplay(this);
this.gameCanvas = new HelicopterCanvas(this, 240, 320);
this.exitCommand = new Command("Exit", Command.EXIT, 0);
this.gameCanvas.addCommand(this.exitCommand);
this.gameCanvas.setCommandListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void startApp() {
if (this.display != null && this.gameCanvas != null) {
this.display.setCurrent(this.gameCanvas);
} else {
System.out.println("Erro: Display ou GameCanvas não inicializado corretamente.");
}
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c == this.exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}
class HelicopterCanvas extends Canvas implements Runnable {
private HelicopterGame midlet;
private boolean isRunning;
private int helicopterX;
private int helicopterY;
private int currentFrame;
private Image[] helicopterSprites;
private static final int SPRITE_COUNT = 3;
private static final int FRAME_DELAY = 100;
private int screenWidth;
private int screenHeight;
private boolean isAscending;
private double gravityPercentage = 0.15;
private double ascendPercentage = 0.2;
private double velocity;
private Background background;
private Player ascendSound;
private Player idleSound;
code
}
class Background {
private Image background;
private int x;
private int speed;
code
public Background(String path, int speed) {
try {
this.background = Image.createImage(path);
} catch (Exception e) {
e.printStackTrace();
}
this.x = 0;
this.speed = speed;
}
public void update() {
x -= speed;
if (x <= -background.getWidth()) {
x = 0;
}
}
public void draw(Graphics g) {
g.drawImage(background, x, 0, Graphics.TOP | Graphics.LEFT);
g.drawImage(background, x + background.getWidth(), 0, Graphics.TOP | Graphics.LEFT);
}
}
Para adaptar o "background" diretamente dentro do HelicopterCanvas, basta integrar a classe Background dentro do mesmo arquivo e assegurar que o método paint no HelicopterCanvas desenhe primeiro o fundo rolante antes de desenhar o helicóptero. Veja como ficaria:
java
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.midlet.MIDlet;
class HelicopterCanvas extends GameCanvas implements Runnable {
private boolean isRunning;
private int helicopterX;
private int helicopterY;
private int currentFrame;
private int helicopterWidth;
private int helicopterHeight;
private Image[] helicopterSprites;
private static final int SPRITE_COUNT = 3;
private static final int FRAME_DELAY = 100;
private int screenWidth;
private int screenHeight;
private boolean isAscending;
private double gravityPercentage = 0.15D;
private double ascendPercentage = 0.2D;
private double velocity;
private Player ascendSound;
private Player idleSound;
private Background background;
public HelicopterCanvas(MIDlet midlet, int width, int height) {
super(true);
this.screenWidth = width;
this.screenHeight = height;
this.helicopterWidth = 40;
this.helicopterHeight = 20;
this.helicopterX = this.screenWidth / 2;
this.helicopterY = this.screenHeight / 2;
this.currentFrame = 0;
this.isRunning = true;
this.isAscending = false;
this.velocity = 0.0D;
loadSprites();
initAudio();
this.background = new Background("/background.png", 2); // Caminho e velocidade do background
(new Thread(this)).start();
}
private void loadSprites() {
this.helicopterSprites = new Image[3];
try {
this.helicopterSprites[0] = Image.createImage("/helicopter1.png");
this.helicopterSprites[1] = Image.createImage("/helicopter2.png");
this.helicopterSprites[2] = Image.createImage("/helicopter3.png");
System.out.println("Sprites carregados com sucesso.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Erro ao carregar sprites: " + e.getMessage());
}
}
private void initAudio() {
try {
this.ascendSound = Manager.createPlayer(getClass().getResourceAsStream("/ascend.amr"), "audio/amr");
this.ascendSound.setLoopCount(-1);
this.idleSound = Manager.createPlayer(getClass().getResourceAsStream("/helicopter.amr"), "audio/amr");
this.idleSound.setLoopCount(-1);
this.idleSound.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (this.isRunning) {
updateGame();
repaint();
try {
Thread.sleep(100L);
} catch (InterruptedException interruptedException) {}
}
}
public void paint(Graphics g) {
background.update();
background.draw(g);
// Desenha o helicóptero e outros elementos
g.setColor(255);
g.fillRect(0, 0, this.screenWidth, this.screenHeight);
if (this.helicopterSprites[this.currentFrame] != null) {
g.drawImage(this.helicopterSprites[this.currentFrame], this.helicopterX, this.helicopterY, Graphics.VCENTER | Graphics.HCENTER);
} else {
System.out.println("Erro: Sprite não carregado corretamente.");
}
}
private void updateGame() {
this.currentFrame = (this.currentFrame + 1) % 3;
double ascendRate = this.screenHeight * this.ascendPercentage / 100.0D;
double gravityRate = this.screenHeight * this.gravityPercentage / 100.0D;
if (this.isAscending) {
this.velocity = -ascendRate;
} else {
this.velocity += gravityRate;
}
this.helicopterY = (int)(this.helicopterY + this.velocity);
if (this.helicopterY < 0) {
this.helicopterY = 0;
this.velocity = 0.0D;
} else if (this.helicopterY > this.screenHeight) {
this.helicopterY = this.screenHeight;
this.velocity = 0.0D;
}
}
public void keyPressed(int keyCode) {
int gameAction = getGameAction(keyCode);
if (keyCode == 53 || gameAction == 8) {
this.isAscending = true;
increaseAscendPercentage();
try {
if (this.idleSound != null && this.idleSound.getState() == 400) {
this.idleSound.stop();
}
if (this.ascendSound != null && this.ascendSound.getState() != 400) {
this.ascendSound.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void keyReleased(int keyCode) {
if (keyCode == 53 || keyCode == -5 || getGameAction(keyCode) == 1) {
this.isAscending = false;
try {
if (this.ascendSound != null && this.ascendSound.getState() == 400) {
this.ascendSound.stop();
}
if (this.idleSound != null && this.idleSound.getState() != 400) {
this.idleSound.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void increaseAscendPercentage() {
this.ascendPercentage += 1.5D;
if (this.ascendPercentage > 0.9D) {
this.ascendPercentage = 0.9D;
}
}
public void reduceHelicopterSize() {
if (this.helicopterWidth > 0 && this.helicopterHeight > 0) {
this.helicopterWidth /= 2;
this.helicopterHeight /= 2;
this.helicopterX = this.screenWidth / 2;
this.helicopterY = this.screenHeight / 2;
}
}
// Classe interna para gerenciar o fundo rolável
class Background {
private Image background;
private int x;
private int speed;
public Background(String path, int speed) {
try {
this.background = Image.createImage(path);
} catch (Exception e) {
e.printStackTrace();
}
this.x = 0;
this.speed = speed;
}
public void update() {
x -= speed;
if (x <= -background.getWidth()) {
x = 0;
}
}
public void draw(Graphics g) {
g.drawImage(background, x, 0, Graphics.TOP | Graphics.LEFT);
g.drawImage(background, x + background.getWidth(), 0, Graphics.TOP | Graphics.LEFT);
}
}
}
Alterações Realizadas:
Classe Background: Incorporada como uma classe interna no HelicopterCanvas, simplificando a interação entre as duas.
Método paint: Agora, desenha primeiro o fundo antes de pintar o helicóptero, assegurando que este fique sobre o fundo.
Método run e updateGame: Não necessitaram de alterações estruturais, mas o background é atualizado em cada iteração do loop, proporcionando um movimento contínuo.
Agora, a funcionalidade do fundo rolante está integrada diretamente dentro do HelicopterCanvas, o que facilita a manutenção e a expansão do código.