Для проекта Java в школе я должен создать простую гоночную игру. Я создал несколько классов: один класс Vehicle, один класс JDessin
, который является Canvas
, один класс JeuKarting
, который соответствует кадру. Есть несколько проблем с моим кодом:
- Я добавил
KeyListener
, чтобы заставить автомобиль двигаться или вращаться при нажатии кнопок со стрелками, но он не работает, и я не понимаю, почему.
- Я добавил преобразование
Graphics2D
, чтобы заставить мой автомобиль вращаться, когда я нажимаю стрелку влево или вправо, но так как на экране не отображается холст.
Вот мой код:
\\JDessin class corresponding to the Canvas
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.Graphics2D;
@SuppressWarnings("serial")
public class JDessin extends JPanelAnime implements KeyListener {
static final int T_CANVAS = 500; // taille du Canvas en pixels (carré)
static final int D_INFLUENCE = 25;
static final int D_MIN_DU_BORD = 30;
Piste piste; // la piste
Vehicule vehicule;// le vehicule
public JDessin(int d) {
super(d);
try {
// appel du constructeur de la classe mère
setPreferredSize (new Dimension(T_CANVAS, T_CANVAS));
vehicule = new Vehicule (T_CANVAS - 100, T_CANVAS - 100, 0, 0, 0, ImageIO.read(new File("C:\\Users\\Adrien\\Desktop\\Imagejava\\voiture_exemple.jpg")) , "NORMAL");
addKeyListener(this); // rend le canvas réactif au déplacement du véhicule
}
catch(IOException exc) {
exc.printStackTrace();
}
}
// Drawing the rotated image at the required drawing locations
/* dessin sur le Canvas (méthode invoquée automatiquement lorsque nécessaire) */
public void paint(Graphics2D g) {
double locationX = vehicule.image.getWidth(null);
double locationY = vehicule.image.getHeight(null);
AffineTransform tx = AffineTransform.getRotateInstance(vehicule.a, locationX, locationY);
// On dessine le fond, puis le véhicule et la piste :
g.setColor(Color.WHITE);
g.fillRect(0, 0, T_CANVAS, T_CANVAS);
try {
g.drawImage(vehicule.image, tx, null); }
catch(NullPointerException e) {}
}
protected void testerFinPartie() {
}
/* calcule la distance entre deux points */
static protected double distance(int x1, int y1, int x2, int y2) {
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
boolean touche_g = false;
boolean touche_h = false;
boolean touche_d = false;
boolean touche_b = false;
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT :
touche_g = true;
vehicule.tourner_g();
break;
case KeyEvent.VK_RIGHT :
touche_d = true;
vehicule.tourner_d();
break;
case KeyEvent.VK_UP :
touche_h = true;
vehicule.avancer();
break;
case KeyEvent.VK_DOWN :
touche_b = true;
vehicule.reculer();
break;
}
}
public void deplacer() {
vehicule.tourner_d();
}
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT :
touche_g = false;
break;
case KeyEvent.VK_RIGHT :
touche_d = false;
break;
case KeyEvent.VK_UP :
touche_h = false;
break;
case KeyEvent.VK_DOWN :
touche_b = false;
break; }
if (touche_d == false && touche_b == false && touche_h == false && touche_g == false) {
vehicule.ralentir();
}
}
public void keyTyped(KeyEvent e) { }
}
Vehicle
класс
import java.awt.image.BufferedImage;
public class Vehicule {
int x;
int y;
int a;
int dx;
int da;
BufferedImage image;
String mode;
public Vehicule(int x, int y, int a, int dx, int da, BufferedImage image, String mode) {
this.x = x;
this.y = y;
this.a = a;
this.dx = dx;
this.da = da;
this.image = image;
mode = "NORMAL";
}
public void tourner_g() {
if (da < (Math.PI/3))
{da += (5*Math.PI/180);}
a += da;
}
public void tourner_d() {
if (da < (Math.PI/3))
{da += (5*Math.PI/180);}
a -= da;
}
public void avancer() {
if (dx < 10)
{dx +=1;}
x += dx*Math.cos(a);
y += dx*Math.sin(a);
}
public void reculer() {
if (dx < 10)
{dx +=1;}
x -= dx*Math.cos(a);
y -= dx*Math.sin(a);
}
public void ralentir( ) {
if (dx > 0 || da > 0) {
dx -= 1;
da -= 5*Math.PI/180;
}
}
public void deplacer( ) {
switch(mode) {
case "NORMAL":
case "GLISSADE":
}
}
}
JeuKarting
соответствует рамке
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JeuKarting implements ActionListener {
JFrame f; // la fenêtre principale du jeu
JDessin c; // le canvas ou on dessine la cible et le(s) palets
public JeuKarting() {
// création de la fenêtre (classe Frame) :
f = new JFrame("Jeu de Karting...");
JPanel d = new JPanel ();
// création du canvas animé pour le jeu :
c = new JDessin(50);
// création de boutons :
JButton l = new JButton("Lancer une partie");
JButton p = new JButton("Pause");
JButton s = new JButton("Sauvegarder");
// ajout des sous composants à la frame et affichage :
f.add(c, BorderLayout.NORTH);
d.add(s);
d.add(l);
d.add(p);
f.add(d);
f.pack();
f.setVisible(true);
// pour sortir du programme si on ferme la fenêtre (par défaut la fenêtre est juste masquée) :
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// rend le bouton réactif au clic :
s.addActionListener(this);
p.addActionListener(this);
l.addActionListener(this);
// lancement de l'animation :
c.animer();
}
// Méthode invoquée pour les événements de type "action" :
public void actionPerformed(ActionEvent e) {
}
static public void main(String[] args) {
new JeuKarting();
}
}