Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Package;
- import javax.swing.*;
- import java.awt.*;
- public class Main {
- public static void main(String[] args) {
- /*
- JFrame myFrame = new JFrame("Snake Game");
- myFrame.setTitle("Snake By Seba");
- ImageIcon image = new ImageIcon("Snake_logo.png");
- myFrame.setIconImage(image.getImage());
- myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- JButton button = new JButton();
- button.setBounds(150, 350, 200, 50);
- button.addActionListener(e -> {
- start_function(); // avvia la funzione initBoard()
- });
- myFrame.add(button);
- Font buttonFont = new Font("Arial", Font.BOLD, 20);
- button.setForeground(Color.GREEN);
- button.setFont(buttonFont);
- button.setBackground(Color.BLUE);
- button.revalidate();
- button.repaint();
- */
- JFrame myFrame = new JFrame("Snake Game");
- myFrame.setTitle("Snake By Seba");
- ImageIcon image = new ImageIcon("Snake_logo.png");
- myFrame.setIconImage(image.getImage());
- myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- myFrame.add(new SnakeGame());
- myFrame.pack();
- myFrame.setLocationRelativeTo(null);
- myFrame.setVisible(true);
- }
- }
- package Package;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.KeyEvent;
- import java.awt.event.KeyListener;
- import java.util.LinkedList;
- import java.util.Random;
- import javax.swing.*;
- import javax.swing.border.Border;
- import java.awt.Graphics2D;
- public class SnakeGame extends JPanel implements ActionListener, KeyListener {
- //Costanti
- private static final int WIDTH = 500;
- private static final int HEIGHT = 600;
- private static final int DOT_SIZE = 10;
- private static final int RAND_POS = 50;
- private static final int DELAY = 140;
- //Variabili di gioco
- private boolean inGame = true;
- JButton button = new JButton("Restart");
- ImageIcon muretto = new ImageIcon("muretto.png");
- ImageIcon melaR = new ImageIcon("melaR.png");
- ImageIcon melaG = new ImageIcon("melaG.png");
- ImageIcon melaB = new ImageIcon("melaB.png");
- private int snakeL;
- private int appleX;
- private int appleY;
- private int appleG_X;
- private int appleG_Y;
- private int appleB_X;
- private int appleB_Y;
- private final int[] wallX = new int[20];
- private final int[] wallY = new int[20];
- private final Random r = new Random();
- private int chooseA;
- private LinkedList<Point> snake;
- private int direction = KeyEvent.VK_RIGHT;
- public SnakeGame() {
- initBoard();
- }
- //TODO: sezione initBoard/Game
- public void initBoard() {
- // inizializza il gioco
- setBackground(new Color(128, 208, 63));
- setFocusable(true);
- //Border blackBorder = BorderFactory.createLineBorder(Color.BLACK, 10);
- //setBorder(blackBorder);
- addKeyListener(this);
- setPreferredSize(new Dimension(WIDTH, HEIGHT));
- revalidate();
- repaint();
- initGame();
- }
- private void initGame() {
- //Inizializza una nuova partita
- snakeL = 2;//Lunghezza iniziale snake
- snake = new LinkedList<>();
- for (int i = 0; i < snakeL; i++) {
- snake.add(new Point(50, 50));
- }
- newApple();
- createWall();
- Timer timer = new Timer(DELAY, this);
- timer.start();
- }
- //TODO: sezione movimenti
- private void move() {
- // muove il serpente
- Point head = snake.getFirst();
- switch(direction) {
- case KeyEvent.VK_LEFT:
- head = new Point(head.x - DOT_SIZE, head.y);
- break;
- case KeyEvent.VK_RIGHT:
- head = new Point(head.x + DOT_SIZE, head.y);
- break;
- case KeyEvent.VK_UP:
- head = new Point(head.x, head.y - DOT_SIZE);
- break;
- case KeyEvent.VK_DOWN:
- head = new Point(head.x, head.y + DOT_SIZE);
- break;
- }
- if (head.x >= WIDTH) {
- head.x = 0;
- } else if (head.x < 0) {
- head.x = WIDTH - DOT_SIZE;
- }
- if (head.y >= HEIGHT) {
- head.y = 0;
- } else if (head.y < 0) {
- head.y = HEIGHT - DOT_SIZE;
- }
- if (snake.contains(head)) {
- //Il serpente ha colpito se stesso
- inGame = false;
- } else {
- //Il serpente si è mosso sulla casella vuota
- snake.addFirst(head);
- if (snake.size() > snakeL) {
- //Rimuove la coda del serpente se si è allungato per permettere lo spostamento
- snake.removeLast();
- }
- }
- }
- //TODO: sezione drawSnake
- private void drawSnake(Graphics s) {
- //Disegna il serpente
- s.setColor(new Color(19, 80, 42));
- for (Point p : snake) {
- s.fillRect(p.x, p.y, DOT_SIZE, DOT_SIZE);
- }
- s.setColor(Color.BLUE);
- Font f1 = new Font(Font.SANS_SERIF, Font.BOLD, 40);
- s.setFont(f1);
- s.setColor(Color.BLUE);
- s.drawString("Score: " + (snakeL - 2), 175, 560);
- s.setColor(Color.BLACK);
- Graphics2D g2 = (Graphics2D) s;
- g2.setStroke(new BasicStroke(20));
- g2.drawLine(0, 500, 500, 500);
- }
- //TODO: sezione drawApple
- private void drawApple(Graphics g) {
- //Mela importata via immagine
- g.drawImage(melaR.getImage(), appleX, appleY, null);
- //--------------------------------------------------------------
- //disegna la mela
- /*
- g.setColor(Color.RED);
- g.fillOval(appleX, appleY, DOT_SIZE, DOT_SIZE);
- wallMovement();
- */
- }
- private void drawGoldApple(Graphics g) {
- g.drawImage(melaG.getImage(), appleG_X, appleG_Y, null);
- }
- private void drawBlueApple(Graphics g) {
- g.drawImage(melaB.getImage(), appleB_X, appleB_Y, null);
- }
- //TODO: sezione newApple
- private void newApple() {
- //Genera una nuova mela in posizione casuale
- do {
- chooseA = r.nextInt() % 40;
- } while (chooseA < 0);
- if (chooseA != 0 && chooseA > 15) {
- for (int i = 0; i < 20; i++) {
- do {
- appleX = r.nextInt(RAND_POS) * DOT_SIZE;
- appleY = r.nextInt(RAND_POS) * DOT_SIZE;
- } while (appleX == wallX[i] && appleY == wallY[i] || appleX >= 490 || appleX <= 10 || appleY >= 490 || appleY <= 10);
- }
- } else if (chooseA == 0) {
- for (int i = 0; i < 20; i++) {
- do {
- appleG_X = r.nextInt(RAND_POS) * DOT_SIZE;
- appleG_Y = r.nextInt(RAND_POS) * DOT_SIZE;
- } while (appleG_X == wallX[i] && appleG_Y == wallY[i] || appleG_X >= 490 || appleG_X <= 10 || appleG_Y >= 490 || appleG_Y <= 10);
- }
- } else {
- for (int i = 0; i < 20; i++) {
- do {
- appleB_X = r.nextInt(RAND_POS) * DOT_SIZE;
- appleB_Y = r.nextInt(RAND_POS) * DOT_SIZE;
- } while (appleB_X == wallX[i] && appleB_Y == wallY[i] || appleB_X >= 490 || appleB_X <= 10 || appleB_Y >= 490 || appleB_Y <= 10);
- }
- }
- }
- //TODO: sezione checkApple
- private void checkApple() {
- // controlla se il serpente ha mangiato la mela rossa
- if (snake.getFirst().x == appleX && snake.getFirst().y == appleY) {
- snakeL++;
- newApple();
- wallMovement();
- }
- }
- private void checkBlueApple(){
- //Controlla se il serpente ha mangiato la mela blu
- if(snake.getFirst().x == appleB_X && snake.getFirst().y == appleB_Y){
- snakeL++;
- snakeL++;
- newApple();
- wallMovement();
- }
- }
- private void checkGoldApple(){
- //Controlla se il serpente ha mangiato la mela d'oro
- if(snake.getFirst().x == appleG_X && snake.getFirst().y == appleG_Y){
- snakeL++;
- snakeL++;
- snakeL++;
- snakeL++;
- snakeL++;
- newApple();
- wallMovement();
- }
- }
- //TODO: sezione checkCollisions
- private boolean checkCollisions() {
- //Controllo per la collisione del serpente con qualche muro
- Point head = snake.getFirst();
- for(int i = 0; i < 20; i++){
- if ((head.x >= wallX[i] && head.x < wallX[i] + DOT_SIZE) && (head.y >= wallY[i] && head.y < wallY[i] + DOT_SIZE)) {
- inGame = false;
- break;
- }
- }
- return inGame;
- }
- private void checkBoard(){
- //Controllo per la collisione del serpente con i bordi
- Point head = snake.getFirst();
- if (head.x == 0 || head.x == 490 || head.y == 0 || head.y == 490) {
- inGame = false;
- }
- }
- //TODO: sezione wall
- private void createWall() {
- int wallWidth = 2 * DOT_SIZE;
- int wallHeight = 2 * DOT_SIZE;
- int wallBuffer = 2 * DOT_SIZE;
- int boardWidth = WIDTH - 2 * wallBuffer;
- int boardHeight = HEIGHT - 2 * wallBuffer;
- boardHeight -= 100;
- //Genera i muri con coordinate random
- for(int i = 0; i < 20; i++){
- do {
- wallX[i] = r.nextInt(boardWidth / wallWidth) * wallWidth + wallBuffer;
- wallY[i] = r.nextInt(boardHeight / wallHeight) * wallHeight + wallBuffer;
- }while(wallX[i] <= 10 && wallX[i] >=490 && wallY[i] <= 10 && wallY[i] >= 490);
- }
- }
- private void drawWall(Graphics g){
- g.setColor(Color.BLACK);
- for(int i = 0; i < 20; i++){
- //Muretti importati via immagine
- g.drawImage(muretto.getImage(), wallX[i], wallY[i], null);
- //------------------------
- //Muretti disegnati
- //g.fillRect(wallX[i], wallY[i], DOT_SIZE, DOT_SIZE);
- }
- }
- private void wallMovement(){
- if (snakeL % 2 == 0) {
- for(int i = 0; i < 20; i++){
- if(i%2 == 0){
- wallX[i] += 10;
- wallY[i] -= 10;
- } else{
- wallX[i] -= 10;
- wallY[i] += 10;
- }
- }
- } else{
- for(int i = 0; i < 20; i++){
- if(i%2 == 0){
- wallX[i] -= 10;
- wallY[i] += 10;
- } else{
- wallX[i] += 10;
- wallY[i] -= 10;
- }
- }
- }
- }
- //TODO: sezione azioni
- @Override public void paintComponent(Graphics g) {
- super.paintComponent(g);
- inGame = checkCollisions();
- checkBoard();
- if (inGame) {
- drawSnake(g);
- if(chooseA > 15){
- drawApple(g);
- } else if(chooseA == 0){
- drawGoldApple(g);
- } else if(chooseA >= 1){
- drawBlueApple(g);
- }
- drawWall(g);
- } else {
- gameOver(g);
- }
- }
- @Override public void actionPerformed(ActionEvent e) {
- if (inGame) {
- move();
- if(chooseA > 15) {
- checkApple();
- }else if(chooseA == 0){
- checkGoldApple();
- } else if(chooseA >= 1){
- checkBlueApple();
- }
- }
- repaint();
- }
- @Override public void keyPressed(KeyEvent e) {
- int key = e.getKeyCode();
- if (key == KeyEvent.VK_LEFT && direction != KeyEvent.VK_RIGHT) {
- direction = KeyEvent.VK_LEFT;
- } else if (key == KeyEvent.VK_RIGHT && direction != KeyEvent.VK_LEFT) {
- direction = KeyEvent.VK_RIGHT;
- } else if (key == KeyEvent.VK_UP && direction != KeyEvent.VK_DOWN) {
- direction = KeyEvent.VK_UP;
- } else if (key == KeyEvent.VK_DOWN && direction != KeyEvent.VK_UP) {
- direction = KeyEvent.VK_DOWN;
- }
- }
- @Override public void keyReleased(KeyEvent e) {
- }
- @Override public void keyTyped (KeyEvent e){
- }
- //TODO: sezione gameOver
- private void gameOver(Graphics g) {
- //Visualizza il messaggio di gameOver
- String msg = "Game Over";
- Font f1 = new Font(Font.SANS_SERIF, Font.BOLD, 25);
- g.setFont(f1);
- g.setColor(Color.BLUE);
- g.drawString(msg, (WIDTH - g.getFontMetrics().stringWidth(msg)) / 2, HEIGHT / 2);
- g.drawString("Final score: " + (snakeL - 2), (WIDTH - g.getFontMetrics().stringWidth("Final score: " + (snakeL - 2))) / 2, (HEIGHT / 2) + 20);
- button.setBounds(150, 350, 200, 50);
- button.addActionListener(e -> initGame());
- add(button);
- Font buttonFont = new Font("Arial", Font.BOLD, 20);
- button.setForeground(Color.GREEN);
- button.setFont(buttonFont);
- button.setBackground(Color.BLUE);
- revalidate();
- repaint();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement