Voici mon premier jeu en java. Il s'agit du célébrissime jeu du serpent gourmand
qui mange des pommes, au point qu'on le voit grandir à vue d'oeil.
Il pourra servir de base pour d'autres. Il peut être bien sûr amélioré.
J'ai utilisé le double buffering pour des animations plus souples, j'ai mis une petite musique de fond sympa, etc...
Source / Exemple :
package essais;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Sons extends Thread{
AudioInputStream audioInputStream = null;
SourceDataLine line;
public Sons(){
run();
}
public void run(){
File fichier = new File("Halo2Theme.wav");
try {
AudioFileFormat format = AudioSystem.getAudioFileFormat(fichier);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
audioInputStream = AudioSystem.getAudioInputStream(fichier);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);
try {
line = (SourceDataLine) AudioSystem.getLine(info);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
}
try {
line.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
}
line.start();
try {
byte bytes[] = new byte[1024];
int bytesRead=0;
while ((bytesRead = audioInputStream.read(bytes, 0, bytes.length)) != -1) {
line.write(bytes, 0, bytesRead);
}
} catch (IOException io) {
io.printStackTrace();
return;
}
}
}
package jeux;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Serpent extends JPanel implements Runnable {
/**
private static final long serialVersionUID = 1L;
private int x, y;
private int pommeX;
private int pommeY;
private int pointsX[] = new int [1000];
private int pointsY[] = new int [1000];
private int corps = 3;
private int a,b = 0;
private Image tete, points, pomme;
private Thread animator;
private boolean enJeu = true;
private final int NORD = 1;
private final int EST = 2;
private final int SUD = 3;
private final int OUEST = 4;
private int direction;
private JTextField jtfBox;
private int score;
private final int DELAY = 80;
public Serpent() {
Sons son = new Sons();
son.start();
setBackground(Color.BLACK);
setDoubleBuffered(true);
setFocusable(true);
addKeyListener(new TAdapter());
ImageIcon ii = new ImageIcon(this.getClass().getResource("head.png"));
ImageIcon iii = new ImageIcon(this.getClass().getResource("dot.png"));
ImageIcon iiii = new ImageIcon(this.getClass().getResource("apple.png"));
tete = ii.getImage();
points = iii.getImage();
pomme = iiii.getImage();
x = 245;
y = 245;
direction = EST;
pointsX[0]=245;
pointsY[0]=245;
pointsX[1]=235;
pointsY[1]=245;
pointsX[2]=225;
pointsY[2]=245;
pointsX[3]=215;
pointsY[3]=245;
controles();
rajoutePomme();
}
private void controles(){
JPanel ctrls = new JPanel(); //
ctrls.setLayout( new BoxLayout(ctrls, BoxLayout.X_AXIS));
jtfBox = new JTextField("Score: 0 pts");
jtfBox.setEditable(false);
ctrls.add(jtfBox);
this.add(ctrls);
}
public void setScore(int score)
{ jtfBox.setText("Score : " + score+" pts"); }
private void rajoutePomme() {
double pox = Math.random()*460;
double poy = Math.random()*460;
pommeX = ((int) pox/10)*10;
pommeY = ((int) poy/10)*10;
}
public void addNotify() {
super.addNotify();
animator = new Thread(this);
animator.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
if (enJeu){
for (int i = corps; i >-1 ; i--){
pointsX[0] = x; pointsY[0]=y;
if (i==0){
g2d.drawImage(tete, x, y, this);
//il se mord la queue ?
for (int j=2;j<corps-1;j++){
if ((pointsX[0]-pointsX[j])<2 &&(pointsX[0] -pointsX[j])>-2
&&(pointsY[0]- pointsY[j])<2&&(pointsY[0] - pointsY[j])>-2){
enJeu = false;
gameOver();
}
}
}
else{
g2d.drawImage(points, pointsX[i], pointsY[i], this);
//repositionnement du corps
pointsX[i]=pointsX[i-1];
pointsY[i]=pointsY[i-1];
}
}
g2d.drawImage(pomme, pommeX, pommeY, this);
pointsX[0] = pointsX[0]-a;
pointsY[0] = pointsY[0]-b;
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
}
public void cycle() {
if (direction == OUEST) {
x = x - 10;
a=10;b=0;
}
if (direction == EST) {
x = x + 10;
a=-10;b=0;
}
if (direction == NORD) {
y = y - 10;
b=10;a=0;
}
if (direction == SUD) {
y = y + 10;
b=-10;a=0;
}
if (x > 484) {
x = 484;
//gameOver();
}
if (x <= 0) {
x = 0;
//gameOver();
}
if (y > 464) {
y = 464;
//gameOver();
}
if (y < 0) {
y = 0;
//gameOver();
}
//Vérification mange pomme
if ((pointsX[0]-pommeX)<10 &&(pointsX[0] -pommeX)>-10
&&(pointsY[0]- pommeY)<10&&(pointsY[0] - pommeY)>-10) {
rajoutePomme();
corps = corps +1;
score = corps - 3;
setScore(score);
}
}
void gameOver(){
String msg = "Game Over";
JOptionPane jo = new JOptionPane();
jo.showMessageDialog(this,msg+" - Votre score est de "+score);
}
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true) {
cycle();
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT)) {
direction = OUEST;
}
if ((key == KeyEvent.VK_RIGHT)) {
direction = EST;
}
if ((key == KeyEvent.VK_UP)) {
direction = NORD;
}
if ((key == KeyEvent.VK_DOWN)) {
direction = SUD;
}
}
}
}
package jeux;
import javax.swing.JFrame;
public class SerpentMain extends JFrame{
public SerpentMain() {
add(new Serpent());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
setTitle("Serpent 1.0");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new SerpentMain();
}
}
Conclusion :
Bon jeu !!!
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.