efsun manisa
unread,Apr 25, 2022, 7:39:50 PM4/25/22You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
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 snake 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 questions that come to my mind. You would make me very happy if you could solve some or all of these questions. In the meantime, I would be very happy if you 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 snake game. In other words, I want to take some of the codes in the GamePanel 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 GamePanel 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 game to start when I press this button. But when I run the current trouble program, my game entry does not appear. My aim is to make the game entry appear 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 snake will speed up and I want it to write "level 2" to indicate it. When the score 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);
}
}
//******************************************************
package snake;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GamePanel extends JPanel implements ActionListener {
SnakeFoodApple apple = new SnakeFoodApple(600, 600, 25);
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 600;
static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / UNIT_SIZE;
static int DELAY = 75;
final int X[] = new int[GAME_UNITS];
final int Y[] = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random = new Random();
GamePanel() {
random = 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 = true;
timer = 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 = 0; i < bodyParts; i++) {
if (i == 0) {
g.setColor(Color.green);
g.fillRect(X[i], Y[i], UNIT_SIZE, UNIT_SIZE);
} else {
g.setColor(new Color(random.nextInt(255), random.nextInt(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 = getFontMetrics(g.getFont());
g.drawString("SCORE: " + applesEaten, (SCREEN_WIDTH - metrics.stringWidth("SCORE: " + applesEaten)) / 2, g.getFont().getSize());
} else {
gameOver(g);
}
}
public void move() {
for (int i = bodyParts; i > 0; i--) {
X[i] = X[i - 1];
Y[i] = Y[i - 1];
}
switch (direction) {
case 'U':
Y[0] = Y[0] - UNIT_SIZE;
break;
case 'D':
Y[0] = Y[0] + UNIT_SIZE;
break;
case 'L':
X[0] = X[0] - UNIT_SIZE;
break;
case 'R':
X[0] = X[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if ((X[0] == apple.getX()) && (Y[0] == apple.getY())) {
bodyParts++;
applesEaten++;
apple.newApple();
}
}
public void checkCollisions() {
for (int i = bodyParts; i > 0; i--) {
if ((X[0] == X[i]) && (Y[0] == Y[i])) {
running = false;
}
}
if (X[0] < 0) {
running = false;
}
if (X[0] > SCREEN_WIDTH) {
running = false;
}
if (Y[0] < 0) {
running = false;
}
if (Y[0] > SCREEN_HEIGHT) {
running = false;
}
if (!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("SCORE: " + applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("SCORE: " + applesEaten)) / 2, g.getFont().getSize());
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("GAME OVER", (SCREEN_WIDTH - metrics2.stringWidth("GAME OVER")) / 2, SCREEN_HEIGHT / 2);
}
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if (direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if (direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if (direction != 'U') {
direction = '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 = new Random();
private int appleX;
private int appleY;
public SnakeFoodApple(int screenWidth, int screenHeight, int unitSize) {
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.unitSize = unitSize;
}
public void newApple() {
appleX = random.nextInt(screenWidth / unitSize) * unitSize;
appleY = random.nextInt(screenHeight / unitSize) * unitSize;
}
public int getX() {
return appleX;
}
public int getY() {
return appleY;
}
}
//************************************************
package snake;
public class Home extends javax.swing.JFrame {
public Home() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
b_start_game = new javax.swing.JButton();
jLabel3 = 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 java.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 = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.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.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(71, 71, 71)
.addComponent(b_start_game, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/snake/snake.png"))); // NOI18N
jLabel3.setText("jLabel3");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 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.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 438, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(77, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void b_start_gameActionPerformed(java.awt.event.ActionEvent evt) {
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Home().setVisible(true);
}
});
}
// Variables declaration - do not modify
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
}