如何暂停和恢复Java中的简单游戏

如何暂停和恢复Java中的简单游戏

本文介绍了如何暂停和恢复Java中的简单游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用java制作了简单的游戏,它是关于网球背景"和网球"的,并且球是自动随机移动的,

i made simple game by java , it's about "tennis background" and "tennis ball" , and the ball is randomally move automatically ,

我的游戏包含两个文件,第一个文件用于Jpanel,第二个文件用于JFrame,

my game consist of two file , 1st file fore Jpanel , and 2nd file for JFrame ,

我的问题是:我需要通过单击鼠标来控制停止和恢复"球,我试图在线程运行循环中放入wait(),但是失败了,我不知道是什么原因! ,所以请查看我的代码,然后告诉我在简单的游戏中什么是错误的以及暂停和恢复"线程的真正方法是什么!

my question is : i need to control of "stopping and resuming" the ball by clicking the mouse ,i tried to put wait() during thread running loop , but it's faild , i don't know what is the reason ! , so please review my code and then tell me what is the wrong , and what is the true method of "pause&resume" thread in my simple game !

tennis.java文件(包含线程):

tennis.java file (which contain the thread):

/*
 * tennis.java
 *
 * Created on Nov 15, 2011, 3:35:28 PM
 */
package io;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;


public class tennis extends javax.swing.JPanel implements Runnable{

    BufferedImage ball;
    BufferedImage bg;
    int ball_h = 0;
    int ball_w = 0;
    int height = 0;
    int width  = 0;
    int yPos   = -1;
    int xPos   = 10;
    int pause  = 20;

    // Move Speed
    int xMov   = 5;
    int yMov   = 10;
    boolean clicked = false;
    int play    =   0;

    Thread runner;

    /** Creates new form tennis */
    public tennis() throws IOException {

        ball = ImageIO.read(new File("tennis/ball.png"));
        bg = ImageIO.read(new File("tennis/bg.jpg"));
        ball_h = 50;
        ball_w = 50;
        height = 600 - ball_h;
        width  = 800  - ball_w;

        runner = new Thread(this);
        runner.start();

    }

    public void start(){
       if(play == 0){

           play     =   1;
           clicked = true;

       }else{
           play    =  0;
           clicked = true;
       }

       System.out.println(play);
    }

    public void stop(){
        runner = null;
    }




    @Override
    public void paint(Graphics g){
        Graphics2D g2D  =   (Graphics2D) g;

        g2D.drawImage(bg, 0, 0, 800,600, this);
        g2D.drawImage(ball, xPos, yPos,50,50, this);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>
    // Variables declaration - do not modify
    // End of variables declaration

    @Override
    public void run() {

        while(runner == runner){



                    if(xPos >= (width))
                        {
                           xMov   *= -1;
                        }



                           xPos   += xMov;

                    if(xPos < 1)
                        {
                           xMov   *= -1;
                        }

                    if(yPos >= (height-ball_h))
                        {
                            yMov    *= -1 ;
                        }



                            yPos    += yMov;

                     if(yPos < 1)
                        {
                            yMov    *= -1 ;
                        }

                    repaint();



                    try {
                        if(play == 1){
                            Thread.sleep(pause);
                        }else{
                            synchronized(this){
                                while(play == 0){
                                wait();
                              }
                            }
                        }

                    } catch (InterruptedException ex) {
                        Logger.getLogger(tennis.class.getName()).log(Level.SEVERE, null, ex);
                    }

        }
    }

}

Tennis3D.java文件(用于启动游戏并定义线程的框架):

Tennis3D.java file(frame for starting the game and define the thread) :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Tennis3D.java
 *
 * Created on Nov 15, 2011, 3:42:42 PM
 */
package io;

import io.tennis;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Tennis3D extends javax.swing.JFrame implements MouseListener{

    tennis tennis;

    /** Creates new form Tennis3D */
    public Tennis3D() {
        super("Tennis3D");
        setSize(800,600);


        try {
            tennis = new tennis();
            add(tennis);
            tennis.addMouseListener(this);
        } catch (IOException ex) {
            Logger.getLogger(Tennis3D.class.getName()).log(Level.SEVERE, null, ex);
        }


        setVisible(true);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       Tennis3D tennis = new Tennis3D();
    }
    // Variables declaration - do not modify
    // End of variables declaration

    @Override
    public void mouseClicked(MouseEvent e) {
       tennis.start();
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}

谢谢您的帮助:)

推荐答案

这是Nerdtron在上面评论中写的内容的附带内容.通常,游戏循环如下所示:

This is piggy-backing on what Nerdtron wrote in the comment above. Typically a game loop looks like this

 while (!game.isOver())
 {
      if (!game.isPaused())
           game.update()  // this moves your ball, players, etc
 }

这篇关于如何暂停和恢复Java中的简单游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:20