21xrx.com
2024-11-05 18:37:44 Tuesday
登录
文章检索 我的文章 写文章
Java实现简单的游戏
2023-06-18 19:54:08 深夜i     --     --
Java 游戏开发 Swing

Java作为一门非常流行的编程语言,在游戏开发领域也有着广泛的应用。本文将介绍如何使用Java语言开发一款简单的游戏,并提供相关的代码案例。

在开始之前需要明确,游戏开发需要涉及到图形界面的设计,Java提供了一套图形界面设计库Swing,可以较为简单方便地实现一些简单的游戏。

下面是一个使用Swing实现的简单的“跳跳球”游戏的代码案例:


import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Point;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.Timer;

public class BouncingBall extends JPanel implements ActionListener {

  private int ballRadius = 30;

  private Point ballPosition = new Point(0, 0);

  private int xDirection = 10;

  private int yDirection = 10;

  private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

  private int screenWidth = screenSize.width;

  private int screenHeight = screenSize.height;

  private float redValue = 0;

  private float greenValue = 0;

  private float blueValue = 0;

  private Color ballColor = new Color(redValue, greenValue, blueValue);

  private Timer timer;

  public BouncingBall() {

    setBackground(Color.BLACK);

    timer = new Timer(50, this);

    timer.start();

  }

  public static void main(String[] args) {

    JFrame frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(500, 500);

    frame.setLocationRelativeTo(null);

    frame.setContentPane(new BouncingBall());

    frame.setVisible(true);

  }

  @Override

  public void actionPerformed(ActionEvent e) {

    moveBall();

    repaint();

  }

  private void moveBall() {

    ballPosition.x += xDirection;

    ballPosition.y += yDirection;

    if ((ballPosition.x + ballRadius) >= screenWidth || ballPosition.x <= 0) {

      xDirection *= -1;

      changeBallColor();

    }

    if ((ballPosition.y + ballRadius) >= screenHeight || ballPosition.y <= 0) {

      yDirection *= -1;

      changeBallColor();

    }

  }

  private void changeBallColor() {

    redValue = (float) Math.random();

    greenValue = (float) Math.random();

    blueValue = (float) Math.random();

    ballColor = new Color(redValue, greenValue, blueValue);

  }

  @Override

  protected void paintComponent(Graphics g) {

    super.paintComponent(g);

    g.setColor(ballColor);

    g.fillOval(ballPosition.x, ballPosition.y, ballRadius, ballRadius);

  }

}

通过上述代码,可以实现一个小球在窗口中左右弹跳,并随机改变小球的颜色,从而实现一个简单的跳跳球游戏。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复