您的位置:首页 > 编程语言 > Java开发

JAVA大作业 - 五道三星题

2016-04-11 20:55 429 查看
写在前面:

看了一下我的博客,发现距离上一篇博文的发表已经快一年了,深感自己的颓废,所以打算重新写博客(其实是记录= =),于是从上学期的JAVA大作业开始慢慢整理一下,就是这样!

·问题描述

五道三星题:

1. Scissor Rock Paper

Write a program that plays thepopular scissor-rock-paper game(A scissor can cut a paper .a rock can knock ascissor ,and a paper can wrapa rock ).The program randomly generates a number0,1 or 2 representing scissor ,rock ,and paper .The program prompts the
user toenter a number 0,1 or 2and displays a message indicating whether the user orthe computer wins ,loses ,or draws .Revise the program to let user continuouslyplay until either the user or the computer wins more than two time.

2. Bean Machine

The bean machine ,also known as aquincunx or the Galton box ,is a device for statistic experiments named afterEnglish scientist Sir Francis Galton ,It consists of an upright board withevenly spaced nails(or pegs)in a triangular form .

Each ball takes a random path andfalls into a slot.

Balls are dropped from the openingof the board ,Every time a ball hits a nail ,it has a 50% chance of falling tothe left or to the right .the piles of balls are accumulated in the slots atthe bottom of the board.

Write a program that simulates thebean machine .Your program should prompt the user to enter the number of theballs and the number of the slots in the machine ,Simulate the falling of eachball by printing its path for the ball in Figure 6.14(c) Is RLRRLRR
.Displaythe final buildup of the balls in the slots in a histogram .here is a samplerun of the program.

3. TicTacToe game

In a game if TicTacToe ,twoplayers take turns marking an available cell in a 3x3 grid with theirrespective tokens(either X or O).Whenone player has placed three tokens in a horizontal ,vertical or diagonal row onthe gird ,the game is over and that player
has won ,A draw(no winner) occurswhen all the cells on the gird have been filled with tokens and neither playerhas achieved a win .Create a program for playing TicTacToe .The program promptstwo players to enter X token is entered ,the program redisplays the
board onthe console and deter=mines the of the game (win ,draw ,orcontinue).

4. Hangman

Write a hangman game that randomlygenerates a word and prompts the user to guess one letter at a time ,as shownin the sample run .Each letter in the word is displayed as an asterisk .Whenthe user finishes a word ,display the number of misses and ask the
user whetherto continue for another word .Declare an array to store words ,as follows:

String[] word = {"write ","that",...};

5. Now Time

InvokingSystem.currentTimeMillis() return the elapse time in milliseconds sincemidnight of January 1 ,1970.write a program that displays the date and time.

·设计思路

在不同的类中实现不同的游戏,然后整合在一起。主界面设计类Homework,建立五个大小和字体相同的按钮。每一个按钮对应建立一个游戏类的对象,组合到一块就实现将五个三星题集合到一个图形界面中了。

解题思路:

1. Scissor Rock Paper:

定义两个INT型变量,com_t记录电脑赢的次数,user_t记录玩家赢的次数。当进行游戏的总次数不超过三局时,进行游戏:由电脑自动给出一个处于0~2内的随机数(int)(System.currentTimeMillis()%3),然后玩家手动给出一个0~2内的数(0对应石头,1对应剪刀,2对应布)。然后系统进行判断(0<1,1<2,2<0)哪一方胜利,赢得一方次数加一,平局则双方次数不变。系统再次进行判断游戏次数的次数是否到达3次,若无,重复进行游戏直到游戏满次数满3次为止。游戏结束。

2. Bean Machine:

定义两个INT型变量,由用户手动给出小球数和通道层数。进入循环,循环次数为小球数,对每一个小球进行向左滚、向右滚判断,每一次向左向右由系统随机给出。最终打印出每一个小球的运动轨迹(向左L向右R向左L······)和对应通道的小球数。

3. TicTacToe game:

定义一个三行三列的数组,初始化为0,当玩家一确定一位置后,该位置的值置为1,当玩家二确定一位置后,该位置的值置为2。每次的玩家输入后,对数组进行遍历,当发现有三个一或者二连成一列或者一行或者一对角线,该玩家获胜。

4. Hangman:

定义一字符数组,初始化为任意所想设置的单词,本题以color为例。定义好字符数组过后,再顶一个等长的字符数组和状态数组,字符数组初始化为全部为*号,状态数组初始化全为0。当每次的输入正确时,猜对的对应单词上的状态数组上位置标为1,相应的等长字符数组检测在状态数组为1的位置改为相应单词,每次输入过后改变状态数组和字符数组,并且输出字符数组,当所有位置的都猜对的时候结束程序。

5. Now Time:

定义一个Long int型变量保存从1990年1月1日到当前的毫秒数,对毫秒数处理:先除以3得到秒数sec,除以60取余数的当前秒数currentsec,将sec除以60再除以60取余数得分钟currentminu,将sec除以3600加上8再除以24取余数得当前时currenthour。进一步处理可得准确年月日。

·算法分析实现

主界面HomeWork.java

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class HomeWork extends JFrame{
private static JButton jb1=new JButton();
private static JButton jb2=new JButton();
private static JButton jb3=new JButton();
private static JButton jb4=new JButton();
private static JButton jb5=new JButton();
private static JPanel jp=new JPanel();
public void Frame(){
JFrame jf=new JFrame();
jf.setSize(300,400);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setTitle("HomeWork");

jp.setLayout(new GridLayout(5,1,2,2));
jb1.setText("1.	Scissor Rock Paper(剪刀石头布)");
jb2.setText("2.	Bean Machine(向左滚向右滚)");
jb3.setText("3.	TicTacToe game(九宫格三子棋)");
jb4.setText("4.	Hangman(猜词游戏)");
jb5.setText("5.	Now Time(系统当前时间)");
jb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new ScissorRockPaper();
}
});
jb2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new BeanMachine();
}
});
jb3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new TicTacToe();
}
});
jb4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new HangMan();
}
});
jb5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new NowTime();
}
});
jp.add(jb1);
jp.add(jb2);
jp.add(jb3);
jp.add(jb4);
jp.add(jb5);
jf.add(jp);
jf.setVisible(true);
}
public static void main(String[] args) {
HomeWork hm=new HomeWork();
hm.Frame();
}
}

游戏一:ScissorRockPaper.java

<span style="font-size:12px;">import java.util.Scanner;

import javax.swing.JOptionPane;

public class ScissorRockPaper {
public ScissorRockPaper(){
int n=0;
while(n==0){
int com_t=0,user_t=0;
int cs=0;
while(cs<3){
int user;
int com=(int)(System.currentTimeMillis()%3);
Scanner in=new Scanner(System.in);
System.out.print("scissor(0),rock(1),paper(2): ");
user=in.nextInt();
if(com==0)
System.out.print("The compuer is scissor.");
else if(com==1)
System.out.print("The compuer is rock.");
else
System.out.print("The compuer is paper.");
if(user==0)
System.out.print("You are scissor");
else if(user==1)
System.out.print("You are rock");
else if(user==2)
System.out.print("You are paper");
else{
System.out.print("Input error!");
System.exit(0);
}
if((com==0&&user==1)||(com==1&&user==2)||(com==2&&user==0)){
System.out.println(".You won.");++user_t;}
else if((com==1&&user==0)||(com==2&&user==1)||(com==0&&user==2)){
System.out.println(".The computer won.");++com_t;}
else
System.out.println(" too.It is a draw.");
System.out.println("Computer:User = "+com_t+":"+user_t);
++cs;
}
if(com_t>user_t)
System.out.println("The computer won!");
else if(user_t>com_t)
System.out.println("You won!");
else
System.out.println("It is a draw.");
n=JOptionPane.showConfirmDialog(null,"是否继续游戏?" ,"系统提示",JOptionPane.YES_NO_OPTION);
}
System.out.println("Game Over");
}
}</span><span style="font-size:18px;">
</span>


游戏二:BeanMachine.java

<span style="font-size:12px;">import java.util.Scanner;

import javax.swing.JOptionPane;

public class BeanMachine {
public BeanMachine() {
Scanner in=new Scanner(System.in);
int i=0;
while(i==0){
System.out.print("Enter the number of balls to drop:");
int balls=in.nextInt();
System.out.print("Enter the number of slots in the bean machine:");
int n=in.nextInt();
int []slots=new int
;
game(slots,balls,n);
output(slots,n);
i=JOptionPane.showConfirmDialog(null,"是否继续游戏?" ,"系统提示",JOptionPane.YES_NO_OPTION);
}
}
public static void game(int[]slots,int balls,int n){
for(int i=0;i<balls;++i){
System.out.println();
int r=0;
for(int j=0;j<n;++j){
int chance=(int)(Math.random()*2);        //产生随机数1-2
if(chance==1){
System.out.print("R");               //向右滚+1
r++;
}
else{
System.out.print("L");               //向左滚+1
}
}
slots[r]++;
}
System.out.println('\n');
}
//显示
public static void output(int[]slots,int n){
int max=0;
for(int i=0;i<n;++i){
if(max<slots[i])
max=slots[i];                       //找出高度最大值
}
for(int i=max;i>0;--i){
for(int j=0;j<n;++j){
int num=slots[j]-i;
if(num<0){                          //从下向上打印球
System.out.print(" ");
}
else{
System.out.print("O");
}
}
System.out.println();
}
}
}</span><span style="font-size:18px;">
</span>


游戏三:TicTacToe.java

<span style="font-size:12px;">import java.util.Scanner;

import javax.swing.JOptionPane;

public class TicTacToe {
private static int[][] array = new int[3][3];
private static int tokenRow, tokenColumn; // tokenRow表示横向格子,tokenColumn表示纵向格子
private static int player1 = 1, player2 = 2;// player1表示为X ; player2表示为O
private static int player = player1; // 初始化先落子的玩家为X玩家
public TicTacToe() {
int k=0;
while(k==0){
showGrids();
Scanner input = new Scanner(System.in);
setzero();
while (judgeDraw() == true) {
while (true) {
System.out.print("Enter a row(0, 1 or 2) for player "+ (player == 1 ? "X" : "Y") + ": ");
tokenRow = input.nextInt();
System.out.print("Enter a column(0, 1 or 2) for player "+ (player == 1 ? "X" : "Y") + ": ");
tokenColumn = input.nextInt();
if (judgeToken(tokenRow, tokenColumn, player) == 1) {               //判断落子情况
break;
}
}
// 判断玩家是否获胜,获胜则返回0,否则返回1
if (judgeWin(player) == 0) {
System.out.println((player == 1 ? "X" : "Y") + " player win.");
break;
}
// 更换落子的玩家
if (player == player1) {
player = player2;
}
else {
player = player1;
}
}
k=JOptionPane.showConfirmDialog(null,"是否继续游戏?" ,"系统提示",JOptionPane.YES_NO_OPTION);
}
}
//数组置零
private static void setzero(){
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
array[i][j]=0;
}
}
}
//判断棋盘是否下满
private static boolean judgeDraw() {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (array[i][j] == 0) {
return true;
}
}
}
System.out.println("X and O draw.");
return false;
}
//判断落子是否超出范围或该位置被占用
private static int judgeToken(int r, int c, int p) {
if (r > 2 || r < 0 || c > 2 || c < 0) {
System.out.println("Input Error! Please re-enter.");
return 0;
}
else {
if (array[r][c] == 0) {
array[r][c] = p;
showGrids();
judgeWin(p);
return 1;
} else {
System.out.println("This grid is occupied, please re-enter.");
return 0;
}
}
}
// 判断玩家是否获胜
private static int judgeWin(int p) {
int count = 1;
for (int i = 0; i < 3; ++i) {
//判断行、列是否相等
if (array[i][0] == array[i][1] && array[i][1] == array[i][2]&& array[i][2] == p) {
return 0;
} else if (array[0][i] == array[1][i] && array[1][i] == array[2][i]&& array[2][i] == p) {
return 0;
}
}
//判断两条斜线是否相等
if (array[0][0] == array[1][1] && array[1][1] == array[2][2]
&& array[2][2] == p) {
return 0;
} else if (array[0][2] == array[1][1] && array[1][1] == array[2][0]
&& array[2][0] == p) {
return 0;
}
return 1;
}
// 显示棋盘
private static void showGrids() {
System.out.println("-------------");
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
System.out.print("| "
+ (array[i][j] == 0 ? " " : (array[i][j] == 1 ? "X": "Y")) + " ");
if (j == 2) {
System.out.println("|");
}
}
System.out.println("-------------");
}
}
}</span><span style="font-size:18px;">
</span>


游戏四:HangMan.java

<span style="font-size:12px;">import java.util.Scanner;

import javax.swing.JOptionPane;

public class HangMan {
public HangMan() {
String[] words = { "write", "read", "apple", "program", "color",
"communicate", "internal" };
int n=0;
while(n==0){
int w = (int) (Math.random() * (6 - 0 + 0));
int len = words[w].length();
HangWord guess = new HangWord(len,words[w]);
Scanner in=new Scanner(System.in);
while (!guess.judge()) {
System.out.print("(Guess)Enter a letter in word ");
guess.show();
System.out.print(" > ");
String gl=in.nextLine();
char gletter=gl.charAt(0);
guess.start(gletter);

}
n=JOptionPane.showConfirmDialog(null,"是否继续游戏?" ,"系统提示",JOptionPane.YES_NO_OPTION);
}
}
}
HangMan的副类:HangWord.java
public class HangWord {
int length;
String words;
char[] letter;
int[] ler=new int[20];
static int times;
public HangWord(int len,String w){
length=len;
words=w;
letter=words.toCharArray();
times=0;
for(int i=0;i<length;++i)
ler[i]=0;        //0为不显示
}
public int getLength() {
return length;
}
public char[] getLetter() {
return letter;
}
public void start(char z){
int t1 = 0;//本次猜对的次数
int t2=0;//本次猜重複的次數
for(int i=0;i<length;++i){
if(letter[i]==z){
if(ler[i]==1){
System.out.println(z+" is already in the word");
++t2;
break;
}
else
ler[i]=1;
++t1;
}
}
if(t1==0&&t2==0){
System.out.println(z+" is not in the word");
times++;
}
}
public boolean judge(){
for(int i=0;i<length;++i){
if(ler[i]==0)
return false;
}
System.out.print("The word is ");
System.out.print(getLetter());
System.out.println(". You missed "+times+" time.");
return true;
}
public void show(){
for(int i=0;i<length;++i){
if(ler[i]==0)
System.out.print("*");
else
System.out.print(letter[i]);
}
}
}</span><span style="font-size:18px;">
</span>


游戏五:NowTime.java

<span style="font-size:12px;">public class NowTime {
public NowTime() {
long sec=System.currentTimeMillis()/1000;
long currentsec=sec%60;
long currentminu=sec/60%60;
long currenthour=(sec/60/60+8)%24;
System.out.print("Current date and time is ");
year(1970,sec);
System.out.println(" "+currenthour+":"+currentminu+":"+currentsec);
}
public static int israin(int y)
{
if((y%4==0&&y%100!=0)||(y%400==0))
return 1;
else
return 0;
}
public static void year(int currenty,long sec)
{
while((israin(currenty)==1&&(sec>=366*24*360))||(israin(currenty)==0&&(sec>=365*24*3600))){
++currenty;
if(israin(currenty)==1)
sec-=366*24*3600;
else
sec-=365*24*3600;
}
month(currenty,sec);
System.out.print(currenty);
}
public static void month(int currenty,long sec)
{
int []days={0,31,28,31,30,31,30,31,31,30,31,30,31};
int currentd=(int)sec/(3600*24);
int currentm=0;
for(int i=0;currentd>0;++i)
{
currentd-=days[i];
++currentm;
}
if(currentd<=0){
currentd+=days[currentm-1]+1;
--currentm;
}
switch(currentm)
{
case 1:System.out.print("January");break;
case 2:System.out.print("February");break;
case 3:System.out.print("March");break;
case 4:System.out.print("April");break;
case 5:System.out.print("May");break;
case 6:System.out.print("June");break;
case 7:System.out.print("July");break;
case 8:System.out.print("August");break;
case 9:System.out.print("September");break;
case 10:System.out.print("October");break;
case 11:System.out.print("November");break;
case 12:System.out.print("December");break;
}
System.out.print(" "+currentd+",");
}
}</span>

测试及运行结果



总结与体会

由于我选择做五道三星题,因此我做本次大作业非常得心应手。尽管也遇到了很多困难,但是我通过上网查阅资料、去图书馆借阅书籍,完美的解决了我的困惑。我非常高兴我能接触到JAVA这一充满了独特魅力的语言,也许一开始我会习惯性的用C的方式解决问题,解决一个是一个,但是现在,我认识到JAVA是一门面向对象的语言,我的思维方式需要大大的转变。我相信,通过本次大作业,本门课程,我会在学习JAVA、运用JAVA、乃至掌握JAVA的道路上越走越远。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: