8-1三子棋
编写程序,实现简单的三子棋游戏。在三子棋中,双方在3×3的棋盘中轮流下棋,一方用*示,另一方用O表示。如果一方的3个棋子占据了同一行,同一列或者对角线,则该方获胜。如果棋盘已被棋子占满,但没有一方获胜则出现平局。在程序中,一方为用户,用户在界面上输入每次下棋的位置;另一方下棋的位置为随机自动生成。
参考代码 有所修改
import java.util.Random;
import javax.swing.*;
class CheckerBoard{static final Integer BOUNDARY = 3;char[][] board;int count;int[] route;boolean firstPlayer;public CheckerBoard() {count = 0;int num = 1;route = new int[10];board = new char[5][5];for(int i = 1; i <= BOUNDARY; i++){for(int j = 1; j <= BOUNDARY; j++){board[i][j] = (char) ('0' + num++);}}}public void update(int local, char c) {int i = (local + 3 - 1) / 3;int j = (local - 1) % 3 + 1;board[i][j] = c;count++;route[count] = local;}public boolean goBack(){if(count <= 1){return false;}count-=2;for(int k = 1; k <= 2; k++){int local = route[count + k];int i = (local + 3 - 1) / 3;int j = (local - 1) % 3 + 1;board[i][j] = (char) (local + '0');}return true;}public boolean check(int local) {int i = (local + 3 - 1) / 3;int j = (local - 1) % 3 + 1;return board[i][j] == '*' || board[i][j] == 'o';}public String output() {StringBuilder str = new StringBuilder("-----------------------\n");for(int i = 1; i <= BOUNDARY; i++) {str.append(" | ").append(board[i][1]).append(" | ").append(board[i][2]).append(" | ").append(board[i][3]).append(" |\n");str.append("------------------------\n"); }return str.toString();}public boolean isExceed(int local) {return local < 1 || local > 9 ;}public boolean isWin() {//判断行列for(int i = 1; i <= BOUNDARY; i++) {if(board[i][1] == board[i][3] && board[i][2] == board[i][1])return true;if(board[1][i] == board[3][i] && board[2][i] == board[1][i])return true;}//判断对角线if(board[1][1] == board[3][3] && board[1][1] == board[2][2])return true;return board[1][3] == board[3][1] && board[1][3] == board[2][2];}
}
public class TicTacToe {static CheckerBoard b = new CheckerBoard();public static void robotPut () {Random rand = new Random();int local = rand.nextInt(9) + 1;while(b.check(local)) {local = rand.nextInt(9) + 1;}b.update(local, 'o');}public static void userPut() {UIManager.put("OptionPane.cancelButtonText", "撤销");String s = JOptionPane.showInputDialog(b.output() + "请输入位置:");while("".equals(s) || s == null || b.isExceed(Integer.parseInt(s)) || b.check(Integer.parseInt(s))) {if(s == null){if(b.goBack()){JOptionPane.showMessageDialog(null, "撤销成功!");}else{JOptionPane.showMessageDialog(null, "撤销失败!","提示",JOptionPane.ERROR_MESSAGE);}userPut();return;}JOptionPane.showMessageDialog(null, "输入有误, 请重新输入!","提示",JOptionPane.ERROR_MESSAGE);s = JOptionPane.showInputDialog(b.output() + "请输入位置:");}b.update(Integer.parseInt(s), '*');}public static void main(String[] args) {int f=JOptionPane.showConfirmDialog(null,"你是否要先下?","选择",JOptionPane.YES_NO_CANCEL_OPTION);boolean curPlayer=true;if(f==0) {curPlayer=true;JOptionPane.showMessageDialog(null,"你先下!");}else if(f==1){curPlayer=false;JOptionPane.showMessageDialog(null,"机器人先下!");}else System.exit(0);if(curPlayer) {userPut();} else {robotPut();}curPlayer = !curPlayer;while(!b.isWin()) {if(b.count == 9) {//判断是否平局JOptionPane.showMessageDialog(null,b.output() + "平局!");System.exit(0);}if(curPlayer) {userPut();} else {robotPut();}curPlayer = !curPlayer;}String str = curPlayer ? "机器人" : "你";if(str.equals("机器人"))JOptionPane.showMessageDialog(null, b.output()+"很遗憾,你输了!");JOptionPane.showMessageDialog(null, b.output() + "恭喜你赢了!");System.exit(0);}
}
8-3绘制随机图形
定义4个类,MyShape、MyLine、MyRectangle和MyOval,其中MyShape是其他三个类的父类。MyShape为抽象类,包括图形位置的四个坐标;一个无参的构造方法,将所有的坐标设置为0;一个带参的构造函数,将所有的坐标设置为相应值;每个坐标的设置和读取方法;abstract void draw(Graphics g)
方法。MyLine类负责画直线,实现父类的draw方法;MyRectangle负责画矩形,实现父类的draw方法;MyOval负责画椭圆,实现父类的draw方法。编写一个应用程序,使用上面定义的类,随机选取位置和形状,绘制20个图形。
参考代码
package ticTacToe.pack;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;abstract class MyShape{double a;double b;double c;double d;public MyShape(){a=0;b=0;c=0;d=0;}public MyShape(double a,double b,double c,double d) {this.a=a;this.b=b;this.c=c;this.d=d;}public double getA() {return a;}public void setA(int a) {this.a = a;}public double getB() {return b;}public void setB(int b) {this.b = b;}public double getC() {return c;}public void setC(int c) {this.C = c;}public double getD() {return d;}public void setD(int d) {this.d = d;}abstract void draw(Graphics g);
}
class MyLine extends MyShape{public MyLine(double a,double b,double c,double d) {super(a,b,c,d);}void draw(Graphics g) {Graphics2D g2=(Graphics2D )g;Line2D line=new Line2D.Double(this.a,this.b,this.c,this.d);g2.draw(line);}
}
class MyRectangle extends MyShape{public MyRectangle(double a,double b,double c,double d) {super(a,b,c,d);}void draw(Graphics g) {Graphics2D g2=(Graphics2D )g;Rectangle2D rectangle=new Rectangle2D.Double(this.a,this.b,this.c,this.d);g2.draw(rectangle);}
}
class MyOval extends MyShape{public MyOval(double a,double b,double c,double d) {super(a,b,c,d);}void draw(Graphics g) {Graphics2D g2=(Graphics2D )g;Ellipse2D ellipse=new Ellipse2D.Double(this.a,this.b,this.c,this.d);g2.draw(ellipse);}
}public class Paint{public static void main(String []args) {EventQueue.invokeLater(new Runnable(){public void run(){JFrame Frame = new JFrame();Frame.add(new DrawComponent());Frame.pack();Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Frame.setVisible(true);}});}
}
class DrawComponent extends JComponent
{private static final int DEFAULT_WIDTH=500;private static final int DEFAULT_HEIGHT=500;public void paintComponent(Graphics g){for(int i=0;i<20;i++) {double a = Math.random()*300;double b = Math.random()*300;double c = Math.random()*300;double d = Math.random()*300;if(i<6) {MyOval aMyOval = new MyOval(a, b, c, d);aMyOval.draw(g);}else if(i<12) {MyRectangle aMyRectangle = new MyRectangle(a, b, c, d);aMyRectangle.draw(g);}else {MyLine aLine = new MyLine(a, b, c, d);aLine.draw(g);}}}public Dimension getPreferredSize(){return new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT);}
}
8-4猜数游戏
编写一个猜数程序,该程序随机在1到1000的范围中选择一个供用户猜测的整数。界面上提供一个文本框来接收用户输入的猜测的数,如果用户猜得太大,则背景变为红色,如果猜得太小,背景变为蓝色。用户猜对后,文本框变为不可编辑,同时提示用户猜对了。界面上提供一个按钮,使用户可以重新开始这个游戏。在界面上还需显示用户猜测的次数。
实验步骤:
(1) 定义继承自JFrame的类,在该类中添加界面各部分;
(2) 定义事件监听器类完成事件处理;
(3) 定义一个包含main方法的测试类,在该类中创建框架类对象,并显示。
实验提示:
(1) 使用面板进行页面布局;
(2) 可以使用内部类定义事件监听器类;
(3) 按钮点击通过处理ActionEvent事件来完成响应。
参考代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
class Gs extends JPanel implements ActionListener{private int cnt;private int truenb;private JPanel all;private JLabel lb1,lb2,lb3,lb4,lb5;private JButton bnt1,bnt2,bnt3;private JTextField inp;private JFrame jf;public void generate(){//生成随机数作为答案Random r=new Random();truenb=r.nextInt(1000)+1;}public Gs(){cnt=0;generate();//生成所有物件的容器all=new JPanel();all.setLayout(null); all.setBounds(100,80,350,200);// JLabel提示信息lb1= new JLabel("你已经猜了"+cnt+"次"); //已经猜了x次lb1.setBounds(0, 5, 150, 20);lb1.setFont(new Font("宋体",Font.BOLD,14));// lb1.setVisible(true);all.add(lb1);lb2=new JLabel(); //输入猜测的数lb2.setText("输入猜测的数");lb2.setFont(new Font("宋体",Font.BOLD,14));lb2.setBounds(10, 40, 110, 20);all.add(lb2); inp=new JTextField(); //输入框inp.setBounds(110, 40, 120, 20);inp.setBackground(Color.WHITE);all.add(inp);lb3=new JLabel(); //太大or太小lb3.setFont(new Font("宋体",Font.BOLD,14));lb3.setBounds(240, 40, 120, 20);lb3.setVisible(false);all.add(lb3);lb4=new JLabel("恭喜你猜对了");lb4.setFont(new Font("宋体",Font.BOLD,14));lb4.setBounds(10, 125, 120, 20);lb4.setVisible(false);all.add(lb4);lb5=new JLabel("猜测范围在1—~1000之间");lb5.setFont(new Font("宋体",Font.BOLD,14));lb5.setBounds(10,60,180,20);all.add(lb5);bnt1=new JButton("确定");bnt1.setBounds(10, 90, 90, 30);all.add(bnt1);bnt2=new JButton("重新开始");bnt2.setBounds(120, 90, 90, 30);all.add(bnt2);bnt3=new JButton("退出");bnt3.setBounds(230, 90, 90, 30);all.add(bnt3);//给按钮添加事件监听bnt1.addActionListener(this); //传this指针方便判断bnt2.addActionListener(this);bnt3.addActionListener(this);//将Jpanel加入Jframejf=new JFrame();jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);jf.setTitle("猜数游戏");// jf.setLayout(null);jf.setBounds(250,200,350,200);jf.add(all);jf.setVisible(true);}public void actionPerformed(ActionEvent e){if(e.getSource()==bnt1){ //确定按钮cnt++;lb1.setText("您已经猜了"+cnt+"次");int gus=Integer.valueOf(inp.getText());if(gus<truenb){ //太小lb3.setVisible(true);lb3.setText("太小");all.setBackground(Color.BLUE);}else if(gus>truenb){ //太大lb3.setVisible(true);lb3.setText("太大!");all.setBackground(Color.RED);}else{ //猜对了lb4.setVisible(true);inp.setEditable(false); //禁止用户编辑bnt1.setEnabled(false); //禁止按确认按钮lb3.setVisible(false);all.setBackground(Color.GREEN);}}else if(e.getSource()==bnt2) //重开{cnt=0; //重开次数置零lb1.setText("您已经猜了"+cnt+"次");generate(); //生成新数all.setBackground(null); //清除背景色inp.setText(null); //清空输入框inp.setEditable(true);lb4.setVisible(false); //胜利提示关掉bnt1.setEnabled(true); //允许按确认按钮lb3.setVisible(false);}else { //退出System.exit(0);}}
}
public class guess {public static void main(String[] args) {new Gs();}
}