Java snake game 🐍 | code game java | | Kiến thức học thiết kế hữu ích nhất

Nếu bạn đang tìm bài viết code game java thì vui lòng xem ngay những thông tin bên trong bài viết này nhé.

Java snake game 🐍 | code game java.

[button color=”primary” size=”medium” link=”#” icon=”” target=”false” nofollow=”false”]XEM VIDEO BÊN DƯỚI[/button]

See also  Virtual Network Switch on Hyper-V [ภาษาไทย] | virtual คือ

Ngoài việc xem những mẹo vặt hay mới cập nhật này bạn có thể xem thêm nhiều nội dung mới khác do Khunganhtreotuong cung cấp tại đây nhé.

code game java và các Chia sẻ liên quan đến đề tài này.

Hướng dẫn chơi game rắn Java cho người mới bắt đầu # Java #snake # trò chơi Trại đào tạo mã hóa ghét anh ta! Hãy xem anh ấy có thể dạy bạn viết mã bằng một thủ thuật đơn giản này như thế nào … Bro Code là loạt bài hướng dẫn số 1 về viết mã bằng các ngôn ngữ lập trình khác nhau và các video hướng dẫn khác trong vũ trụ đã biết. .

See also  รีวิวการนั่งเครื่องสำหรับมือใหม่จากสนามบินดอนเมืองไปอุดรธานี | ຂັ້ນຕອນການຂີ່ຍົນງ່າຍໆສຳລັບມືໃຫມ່ | เที่ยวบิน อุดร กรุงเทพ

Java snake game 🐍 và các hình ảnh liên quan đến chuyên mục này.

Java snake game 🐍
Java snake game 🐍

>> Ngoài việc xem đề tài này bạn có thể tìm xem thêm nhiều mẹo hay khác do chúng tôi cung cấp tại đây nhé: Xem thêm tin tức mới cập nhật tại đây.

See also  แต่งตัวด้วยเสื้อผ้าหลักร้อย EP.2 เกาหลีได้ไม่ต้องง้อของแพง!! | Qmiy | เสื้อ คลุม ยาว เกาหลี

Rất mong những Thông tin về chủ đề code game java này sẽ có giá trị cho bạn. Chân thành cảm ơn bạn.

#Java #snake #game.

Java snake game,Java snake game tutorial,java snake game eclipse,java snake tutorial,java snake code,java,snake,game,tutorial,for beginners,java snake game code eclipse,snake game in java,java snake game,snake game java,java snake,snake in java.

Java snake game 🐍.

code game java.

42 thoughts on “Java snake game 🐍 | code game java | | Kiến thức học thiết kế hữu ích nhất”

  1. I didn't really expect this video to blow up. This was meant to be more of a practice project.
    I probably would have spent more time optimizing the code if I knew it would get this many views lol
    Well what you see is what you get I guess…
    //*****************************************

    public class SnakeGame {

    public static void main(String[] args) {

    new GameFrame();

    }

    }
    //*****************************************

    import javax.swing.JFrame;

    public class GameFrame extends JFrame{

    GameFrame(){

    this.add(new GamePanel());

    this.setTitle("Snake");

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setResizable(false);

    this.pack();

    this.setVisible(true);

    this.setLocationRelativeTo(null);

    }

    }
    //*****************************************

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    import java.util.Random;

    public class GamePanel extends JPanel implements ActionListener{

    static final int SCREEN_WIDTH = 1300;

    static final int SCREEN_HEIGHT = 750;

    static final int UNIT_SIZE = 50;

    static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);

    static final int DELAY = 175;

    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;

    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() {

    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) {

    /*

    for(int i=0;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {

    g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);

    g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);

    }

    */

    g.setColor(Color.red);

    g.fillOval(appleX, appleY, 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(45,180,0));

    //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 newApple(){

    appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;

    appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;

    }

    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] == appleX) && (y[0] == appleY)) {

    bodyParts++;

    applesEaten++;

    newApple();

    }

    }

    public void checkCollisions() {

    //checks if head collides with body

    for(int i = bodyParts;i>0;i–) {

    if((x[0] == x[i])&& (y[0] == y[i])) {

    running = false;

    }

    }

    //check if head touches left border

    if(x[0] < 0) {

    running = false;

    }

    //check if head touches right border

    if(x[0] > SCREEN_WIDTH) {

    running = false;

    }

    //check if head touches top border

    if(y[0] < 0) {

    running = false;

    }

    //check if head touches bottom border

    if(y[0] > SCREEN_HEIGHT) {

    running = false;

    }

    if(!running) {

    timer.stop();

    }

    }

    public void gameOver(Graphics g) {

    //Score

    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());

    //Game Over text

    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;

    }

    }

    }

    }
    //*****************************************

    Reply
  2. I had two problems with the snake:
    Sometimes lag and sometimes it went off the edges. If someone has any of these problems, here is the solution.

    The lag I resolved adding this line in the main class before call GameFrame:

    System.setProperty("sun.java2d.opengl", "true");

    The problem with edges I resolved modifing the next if conditions in the checkCollitions method:

    //Check if head touches right border
    if (x[0] > SCREEN_WIDTH – UNIT_SIZE) {
    running = false;
    }

    //Check if head touches bottom border
    if (y[0] > SCREEN_HEIGHT – UNIT_SIZE) {
    running = false;
    }

    I work on Linux and I use Apache Netbeans.

    Reply
  3. I followed this tutorial and it worked out great, my only problem is, that I just got into Java and I don't really know why certain things work like they do in the code, I don't know if you fully understand what I mean, but could you give me some tips for understanding how certain things work because you didn't go into detail as to why you did the things you did ( I don't wanna say you should have gone into detail because this is clearly not meant for beginners but it would be great to learn from you or at least understand a bit of what you did) great work <3

    Reply
  4. here is what I did to add restart functionality and add random start position for the snake :

    =======================================

    static final int X_UNITS = SCREEN_WIDTH/UNIT_SIZE;

    static final int Y_UNITS = SCREEN_HEIGHT/UNIT_SIZE;

    public void startGame() {

    applesEaten=0;

    direction='R';

    for(int i = bodyParts;i>0;i–) // reset snake

    x[i]=y[i]=-UNIT_SIZE;

    bodyParts=6;

    // randomize the snake starting position to start in the left quarter of the screen

    x[0]=random.nextInt((int)(X_UNITS/4))*UNIT_SIZE;

    y[0]=random.nextInt(Y_UNITS)*UNIT_SIZE;

    newApple();

    running = true;

    if (timer==null) {

    timer = new Timer(delay, this);

    timer.start();

    }

    }

    =========================================

    Now remove timer.stop(); from checkCollisions

    and add the following to the end of gameOver()

    =========================================

    g.setFont( new Font("Ink Free",Font.BOLD, 35));

    FontMetrics metrics3 = getFontMetrics(g.getFont());

    g.drawString("Press space bar to play again", (SCREEN_WIDTH – metrics3.stringWidth("Press space bar to play again"))/2, SCREEN_HEIGHT/2+50);

    =========================================

    and lastly, add the case to MyKeyAdapter

    =========================================

    case KeyEvent.VK_SPACE:

    if (!running)

    startGame();

    break;

    =========================================

    Reply
  5. Hello bro, I have an error while writing this code. I made the snake game. But when i run it the snake dosen't appear to move. But if I minimize my gameframe and maximize again the snake moves forward with respective DELAY variable value. So to see my snake moving I constantly need to mini-maxi-mize my gameframe window. Then only I see my snake moved.
    Could you suggest a solution to this??

    Reply
  6. Thank you so much, your channel helps me in many ways!

    I added a check in newApple(), so the apple doesn't get planted underneath the body:

    public void newApple() {

    appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE)) * UNIT_SIZE;

    appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE)) * UNIT_SIZE;

    for(int i = bodyParts; i > 0; i–) {

    if((x[i] == appleX) && (y[i] == appleY)) {

    newApple();

    }

    }

    }

    Reply

Leave a Comment