数据结构与算法分析-第一章Java类(05)

许多游戏都可以在滚动两枚骰子的基础上进行。定义一个Die类表示一枚有n个面的骰子。n的默认值是6.该类能滚动骰子,并测得其像上面的值。使用随机数来模拟骰子的滚动。并可依用户要求以图形界面来演示骰子的面。

代码实现:

核心:随机数的生成,使用了java.util.Math类的random,这个方法返回一个0-1之间的浮点数(包含0,不包含1),我们将其与10相乘得到一个0-10(不含10)之间的整数,然后让该整数与骰子的面数取余数后加1,得到的就是一个1-6(骰子面数)的数字

package com.crazycoder2010.datastructure.ch01;

public class Die {
	private int faces;// 总共的面数
	private int number;// 朝上的数字

	public Die(int faces) {
		super();
		this.faces = faces;
	}

	public void die() {
		this.number = (int) (Math.random() * 10)%faces+1;
	}

	public int getNumber() {
		return number;
	}

	public int getFaces() {
		return faces;
	}
}
测试类:图形界面

package com.crazycoder2010.datastructure.ch01;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DieTest extends JFrame {
	private static final long serialVersionUID = 3757821367773739338L;
	public DieTest(){
		setTitle("掷骰子游戏");
		setSize(800, 200);
		setResizable(false);
		this.getContentPane().setLayout(new FlowLayout());
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		final JLabel label = new JLabel();
		this.getContentPane().add(label);
		JButton throwButton = new JButton("掷骰子");
		this.getContentPane().add(throwButton);
		JLabel dieLabel = new JLabel("骰子A:");
		final JLabel dieValue1 = new JLabel("");
		JLabel dieLabe2 = new JLabel("骰子B:");
		final JLabel dieValue2 = new JLabel("");
		this.getContentPane().add(dieLabel);
		this.getContentPane().add(dieValue1);
		this.getContentPane().add(dieLabe2);
		this.getContentPane().add(dieValue2);
		throwButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Die die1 = new Die(6);
				die1.die();
				Die die2 = new Die(6);
				die2.die();
				dieValue1.setText(die1.getFaces()+"面,点数:"+die1.getNumber());
				dieValue2.setText(die2.getFaces()+"面,点数:"+die2.getNumber());
			}
		});
		
	}
	public static void main(String[] args) {
		new DieTest().setVisible(true);
	}
}
运行结果截图:




posted @ 2012-08-10 07:26  java简单例子  阅读(274)  评论(0编辑  收藏  举报