While playing the snake game, there were questions that came to my mind. Can you help me?
efsun manisa <[email protected]> Mon, 25 Apr 2022 16:39:49 -0700 (PDT)
| Newsgroups | alt.comp.lang.java-games |
|---|---|
| Message-ID | <[email protected]> |
Hello! I am currently new to java. I am also making a snake game to improve=
myself. My snake game is working fine now. But I want to improve this snak=
e game. I know I have too many questions. But one of my goals is to improve=
myself in this field. Naturally, while developing myself, there are questi=
ons that come to my mind. You would make me very happy if you could solve s=
ome or all of these questions. In the meantime, I would be very happy if yo=
u could explain the questions I asked by writing code. In this way, I will =
understand better. Thank you for your immediate attention.
First I want to duplicate the class pages to handle the class issue in my s=
nake game. In other words, I want to take some of the codes in the GamePane=
l in my code and put them in a different class page. For example, I want to=
create a page called motion and put the parts related to motion in GamePan=
el inside this page. How can I do that?
Secondly, I have now designed the game intro with the help of Swing. And I =
put a button called Start Game at the entrance of the game. Now I want my g=
ame to start when I press this button. But when I run the current trouble p=
rogram, my game entry does not appear. My aim is to make the game entry app=
ear first and then to start the game when I press the button. How can I do =
that?
Third, I want to add sound to the game. How can I do that?
Fourth, I want to have a level part in my game. When the score is 5 my snak=
e will speed up and I want it to write "level 2" to indicate it. When the s=
core is 10, let the snake get even faster and write "level 3". So how do I =
do this? And what part of this code will I place?
My code:
package snake;
public class Main {
public static void main(String[] args) {
new GameFrame();
}
}
//****************************************************
package snake;
import javax.swing.JFrame;
public class GameFrame extends JFrame{
GameFrame()
{
this.add(new GamePanel());
this.setTitle("Snake Game");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null); =20
} =20
}
//******************************************************
package snake;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener {
=20
SnakeFoodApple apple =3D new SnakeFoodApple(600, 600, 25);
static final int SCREEN_WIDTH =3D 600;
static final int SCREEN_HEIGHT =3D 600;
static final int GAME_UNITS =3D (SCREEN_WIDTH * SCREEN_HEIGHT) / UNIT_S=
IZE;
static int DELAY =3D 75;
final int X[] =3D new int[GAME_UNITS];
final int Y[] =3D new int[GAME_UNITS];
int bodyParts =3D 6;
int applesEaten;
int appleX;
int appleY;
char direction =3D 'R';
boolean running =3D false;
Timer timer;
Random random =3D new Random();
GamePanel() {
random =3D new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
apple.newApple();
running =3D true;
timer =3D new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if (running) {
g.setColor(Color.red);
g.fillOval(apple.getX(), apple.getY(), UNIT_SIZE, UNIT_SIZE);
for (int i =3D 0; i < bodyParts; i++) {
if (i =3D=3D 0) {
g.setColor(Color.green);
g.fillRect(X[i], Y[i], UNIT_SIZE, UNIT_SIZE);
} else {
g.setColor(new Color(random.nextInt(255), random.nextIn=
t(255), random.nextInt(255)));
g.fillRect(X[i], Y[i], UNIT_SIZE, UNIT_SIZE);
}
}
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics =3D getFontMetrics(g.getFont());
g.drawString("SCORE: " + applesEaten, (SCREEN_WIDTH - metrics.s=
tringWidth("SCORE: " + applesEaten)) / 2, g.getFont().getSize());
} else {
gameOver(g);
}
}
public void move() {
for (int i =3D bodyParts; i > 0; i--) {
X[i] =3D X[i - 1];
Y[i] =3D Y[i - 1];
}
switch (direction) {
case 'U':
Y[0] =3D Y[0] - UNIT_SIZE;
break;
case 'D':
Y[0] =3D Y[0] + UNIT_SIZE;
break;
case 'L':
X[0] =3D X[0] - UNIT_SIZE;
break;
case 'R':
X[0] =3D X[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if ((X[0] =3D=3D apple.getX()) && (Y[0] =3D=3D apple.getY())) {
bodyParts++;
applesEaten++;
apple.newApple();
}
}
public void checkCollisions() {
for (int i =3D bodyParts; i > 0; i--) {
if ((X[0] =3D=3D X[i]) && (Y[0] =3D=3D Y[i])) {
running =3D false;
}
}
=20
if (X[0] < 0) {
running =3D false;
}
if (X[0] > SCREEN_WIDTH) {
running =3D false;
}
=20
if (Y[0] < 0) {
running =3D false;
}
if (Y[0] > SCREEN_HEIGHT) {
running =3D false;
}
if (!running) {
timer.stop();
}
}
=20
public void gameOver(Graphics g) {
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics1 =3D getFontMetrics(g.getFont());
g.drawString("SCORE: " + applesEaten, (SCREEN_WIDTH - metrics1.stri=
ngWidth("SCORE: " + applesEaten)) / 2, g.getFont().getSize());
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 75));
FontMetrics metrics2 =3D getFontMetrics(g.getFont());
g.drawString("GAME OVER", (SCREEN_WIDTH - metrics2.stringWidth("GAM=
E OVER")) / 2, SCREEN_HEIGHT / 2);
}
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkApple();
checkCollisions();
}
repaint(); =20
}
public class MyKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (direction !=3D 'R') {
direction =3D 'L';
}
break;
case KeyEvent.VK_RIGHT:
if (direction !=3D 'L') {
direction =3D 'R';
}
break;
case KeyEvent.VK_UP:
if (direction !=3D 'D') {
direction =3D 'U';
}
break;
case KeyEvent.VK_DOWN:
if (direction !=3D 'U') {
direction =3D 'D';
}
break;
}
}
}
}
//***************************
package snake;
import java.util.Random;
public class SnakeFoodApple {
private final int screenWidth;
private final int screenHeight;
private final int unitSize;
private final Random random =3D new Random();
private int appleX;
private int appleY;
public SnakeFoodApple(int screenWidth, int screenHeight, int unitSize) =
{
this.screenWidth =3D screenWidth;
this.screenHeight =3D screenHeight;
this.unitSize =3D unitSize;
}
public void newApple() {
appleX =3D random.nextInt(screenWidth / unitSize) * unitSize;
appleY =3D random.nextInt(screenHeight / unitSize) * unitSize;
}
public int getX() {
return appleX;
}
public int getY() {
return appleY;
}
=20
}
//************************************************
package snake;
public class Home extends javax.swing.JFrame {
public Home() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate=3D"collapsed" desc=3D"Generated Code"> =
=20
private void initComponents() {
jPanel1 =3D new javax.swing.JPanel();
jPanel4 =3D new javax.swing.JPanel();
jLabel2 =3D new javax.swing.JLabel();
b_start_game =3D new javax.swing.JButton();
jLabel3 =3D new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE)=
;
setTitle("Snake Game");
setResizable(false);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new ja=
va.awt.Color(255, 0, 0), 4));
jPanel4.setBackground(new java.awt.Color(51, 255, 51));
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 44)); // NOI18N
jLabel2.setText("SNAKE GAME");
b_start_game.setBackground(new java.awt.Color(0, 51, 255));
b_start_game.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
b_start_game.setForeground(new java.awt.Color(255, 255, 255));
b_start_game.setText("START GAME");
b_start_game.addActionListener(new java.awt.event.ActionListener() =
{
public void actionPerformed(java.awt.event.ActionEvent evt) {
b_start_gameActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout =3D new javax.swing.GroupLayo=
ut(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Align=
ment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(b_start_game, javax.swing.GroupLayout.DEFAULT=
_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel2)
.addContainerGap(24, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Align=
ment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SI=
ZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(71, 71, 71)
.addComponent(b_start_game, javax.swing.GroupLayout.PREFERR=
ED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Shor=
t.MAX_VALUE))
);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/=
snake/snake.png"))); // NOI18N
jLabel3.setText("jLabel3");
javax.swing.GroupLayout jPanel1Layout =3D new javax.swing.GroupLayo=
ut(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align=
ment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SI=
ZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement=
.UNRELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE=
, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align=
ment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, ja=
vax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SI=
ZE, 438, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(77, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout =3D new javax.swing.GroupLayout(getC=
ontentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE=
ADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILI=
NG, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_S=
IZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE=
ADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, ja=
vax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold> =20
private void b_start_gameActionPerformed(java.awt.event.ActionEvent evt=
) { =20
} =20
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Home().setVisible(true);
}
});
}
// Variables declaration - do not modify =20
private javax.swing.JButton b_start_game;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel4;
// End of variables declaration =20
}