Java龟兔赛跑代码 过程模拟

合集下载

作业8java

作业8java

作业8-利用多线程技术模拟龟兔赛跑的场面。

提示:先设计一个线程类模拟两个参与赛跑的选手的行为;然后创建该类的两个对象分别代表乌龟和兔子;让兔子跑快些,但在路上睡眠休息时间长些,而乌龟跑慢些却不休息;当某个选手到达终点时其线程运行结束;二个选手均到达终点时,显示并祝贺获胜选手,然后主线程结束。

一.package t;public class T {public static void main(String[] args) {TortoiseRace a = new TortoiseRace();Thread runner1 = new Thread(a);RabbitRace b = new RabbitRace();Thread runner2 = new Thread(b);runner1.start();runner2.start();while (ready < 2) {try {Thread.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}}synchronized (lock) {lock.notifyAll();}}static Object lock = new Object();static int ready = 0;}class TortoiseRace implements Runnable {@Overridepublic void run() {synchronized (T.lock) {T.ready++;try {T.lock.wait();} catch (InterruptedException e1) {e1.printStackTrace();}}int TortoiseDistance = 0;for (int i = 0; TortoiseDistance <= 10; i++) {TortoiseDistance++;System.out.println("乌龟跑了1米!");try {Thread.sleep(1);} catch (InterruptedException e) {}}System.out.println("乌龟已经跑完了比赛路程!");}}class RabbitRace implements Runnable {@Overridepublic void run() {T.ready++;synchronized (T.lock) {try {T.lock.wait();} catch (InterruptedException e1) {e1.printStackTrace();}}int RabbitDistance = 0;for (int j = 0; RabbitDistance <= 10; j++) {RabbitDistance += 5;System.out.println("兔子跑了5米!");try {Thread.sleep(10);} catch (InterruptedException e) {}}System.out.println("兔子跑完了比赛路程!");}}二.package testtortoiserabbit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Random;import javax.swing.*;public class TestTortoiseRabbit extends JFrame {private static final long serialVersionUID = 987654321L;static final int MAX_LENGTH = 700;private JButton begin = new JButton("开始");private JButton exit = new JButton("退出");private Rabbit rabbit = new Rabbit("兔子");private Tortoise tortoise = new Tortoise("乌龟");private JLabel stateOfRabbit = new JLabel();private JLabel winner;public TestTortoiseRabbit() {super("龟兔赛跑");setLayout(null);setBounds(200, 150, 800, 400);setDefaultCloseOperation(EXIT_ON_CLOSE);add(rabbit);rabbit.setBounds(20, 100, 50, 20);add(tortoise);tortoise.setBounds(20, 150, 50 ,20);add(stateOfRabbit);stateOfRabbit.setBounds(300, 50, 100 ,20);add(begin);begin.setBounds(20, 200, 80, 30);add(exit);exit.setBounds(100, 200, 80, 30);setVisible(true);begin.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {new Thread(rabbit).start();new Thread(tortoise).start();begin.setVisible(false);stateOfRabbit.setText("兔子跑起来了!");}});exit.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {System.exit(0);}});}public static void main(String[] args) {TestTortoiseRabbit testTortoiseRabbit = new TestTortoiseRabbit(); }class Tortoise extends JLabel implements Runnable {private static final long serialVersionUID = 12345678L;public Tortoise(String name) {super(name);}public Tortoise(Icon icon) {super(icon);}boolean stop;int speed = 2;int x, y;@Overridepublic void run() {x = getLocation().x;y = getLocation().y;while (!stop) {x += speed;setLocation(x, y);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}if (x >= MAX_LENGTH) {if (TestTortoiseRabbit.this.winner == null) {TestTortoiseRabbit.this.winner = this;} else {JOptionPane.showMessageDialog(TestTortoiseRabbit.this,TestTortoiseRabbit.this.winner.getText()+ "胜利!");}stop = true;}}}}class Rabbit extends JLabel implements Runnable {private static final long serialVersionUID = 123456789L;public Rabbit(String name) {super(name);}public Rabbit(Icon icon) {super(icon);}boolean stop;int speed = 5;int x, y;Random r = new Random();@Overridepublic void run() {x = getLocation().x;y = getLocation().y;while (!stop) {x += speed;setLocation(x, y);try {Thread.sleep(50);if(r.nextInt(100) > 90){if(speed == 0){speed = 3;stateOfRabbit.setText("兔子跑起来了!");}else{speed = 0;stateOfRabbit.setText("兔子在睡觉!");}}} catch (InterruptedException e) {e.printStackTrace();}if (x >= MAX_LENGTH) {stateOfRabbit.setText("兔子到终点了!");if (TestTortoiseRabbit.this.winner == null) {TestTortoiseRabbit.this.winner = this;} else {JOptionPane.showMessageDialog(TestTortoiseRabbit.this,TestTortoiseRabbit.this.winner.getText()+ "胜利!");}stop = true;}}}}}。

龟兔赛跑游戏程序模块分析

龟兔赛跑游戏程序模块分析

龟兔赛跑游戏程序模块分析:游戏程序第一层主函数模块样式:main(){ int hare = 0, tortoise = 0, timer = 0; //timer是计时器,从0开始计时while (hare < RACE_END && tortoise < RACE_END){ tortoise += 乌龟根据他这一时刻的行为移动的距离;hare += 兔子根据他这一时刻的行为移动的距离;输出当前计时和兔子乌龟的位置;++timer;}if (hare > tortoise) cout << "\n hare wins!";else cout << "\n tortoise wins!";}抽取函数模块:乌龟在这一秒的移动距离:int move_tortoise();兔子在这一秒的移动距离:int move_hare();输出当前计时和兔子与乌龟的位置void print_position(int timer, int tortoise, int hare);由功能分成三个模块(分类模块):主模块移动模块move_tortoisemove_hare()输出模块print_position程序代码://文件:Random.h//随机函数库的头文件#ifndef _random_h#define _random_h//函数:RandomInit//用法:RandomInit()//作用:此函数初始化随机数种子void RandomInit();//函数:RandomInteger//用法:n = RandomInteger(low, high)//作用:此函数返回一个low到high之间的随机数,包括low和high int RandomInteger(int low, int high);#endif//文件:Random.cpp//该文件实现了Random库#include <cstdlib>#include <ctime>#include "Random.h"//函数:RandomInit//该函数取当前系统时间作为随机数发生器的种子void RandomInit(){srand(time(NULL));}// 函数:RandomInteger// 该函数将0到RAND_MAX的区间的划分成high - low + 1 个// 子区间。

Java学习笔记--线程

Java学习笔记--线程

Java学习笔记--线程线程简介我们先来看一个龟兔赛跑的例子(单线程实现):题目要求:设计一个龟兔赛跑游戏,赛程长度为10歩,每经过一秒,乌龟前进一步,兔子则可能前进两歩也有可能睡觉。

import static ng.System.out;public class TortoiseHareRace {public static void main(String[] args){boolean[] flags = {true, false};int totalStep = 10; //总步数int tortoiseStep = 0; //乌龟步数int hareStep = 0; //兔子步数out.println("龟兔赛跑开始...");while(tortoiseStep < totalStep && hareStep < totalStep){tortoiseStep++; //乌龟步数加一out.printf("乌龟跑了%d 步...\n", tortoiseStep);boolean isHareSleep = flags[((int) (Math.random()* 10))% 2]; //随机睡觉if(isHareSleep){out.println("兔子睡着了");}else{hareStep += 2;out.printf("兔子跑了%d 步...\n", hareStep);}}}}再来看看多线程是怎么实现的:乌龟:public class Tortoise implements Runnable {private int totalstep;private int step;public Tortoise(int totalstep){this.totalstep = totalstep;}@Overridepublic void run(){while(step < totalstep){step++;System.out.printf("乌龟跑了%d 歩\n", step);}}}兔子:public class Hare implements Runnable {private boolean[] flags = {true, false};private int totalstep;private int step;public Hare(int totalstep){this.totalstep = totalstep;}public void run(){while(step < totalstep){boolean isHareSleep = flags[((int) (Math.random()* 10))% 2];if(isHareSleep){System.out.println("兔子睡着了");}else{step += 2;System.out.printf("兔子跑了%d 歩\n", step);}}}}Main函数:public class TortoiseHareRace2 {public static void main(String[] args){Tortoise tortoise = new Tortoise(10);Hare hare = new Hare(10);Thread tortoisethread = new Thread(tortoise);Thread harethread = new Thread(hare);tortoisethread.start();harethread.start();}}从上面的代码中我们可以看到线程使用方面一些基本的语法,在这里我就不再赘述。

利用JAVA多线程技术模拟龟兔赛跑

利用JAVA多线程技术模拟龟兔赛跑

利用JAVA多线程技术模拟龟兔赛跑作者:刘惠敏来源:《电脑知识与技术》2008年第34期摘要:该文介绍了利用JAVA语言的多线程技术,对“龟兔赛跑”寓言故事的模拟。

从模拟程序的具体设计思路,到详细的实现过程,将技术的应用融入到一个有趣的问题的解决中,既可方便完成教学内容,又可有效激发学生学习兴趣,对JAVA多线程技术的案例教学实现有很好的参考价值。

关键词:多线程;模拟;龟兔赛跑;案例教学中图分类号:TP311文献标识码:A文章编号:1009-3044(2008)34-1982-02Tortoise and Hare Race simulation with JAVA Multi Thread TechnologyLIU Hui-min(Dept. of Computer Sci., Huanggang Polytechnic College, Huanggang 438002, China)Abstract: A simulation for the Tortoise and Hare Race apologue story with Java multi thread technology has been introduced in this paper. By the detail description on the simulation program design thinking to implementation procedures, the technology application has been embedded into the solving of an interesting real problem. This simulation tool will make the teaching easily, and stimulates student’s interesting on learning effectively. It will also have good reference value for the teaching of Java multi thread technology with cases.Key words: multi-thread; simulation; tortoise and hare race; teaching with cases1 引言“龟兔赛跑”的寓言故事家喻户晓,如果能够用直观形象的方式将故事表达的内容演示出来,那将更有利于人们对故事的理解和认识,怎样用程序的方式把故事模拟表示出来呢?为了便于计算机模拟,需要把故事中的情节数字化。

龟兔赛跑作品代码

龟兔赛跑作品代码

#include "stdio.h"#include "stdlib.h" /*随机数发生器头文件*/#include "time.h" /*系统挂起头文件*/#include "graphics.h" /*图形编辑函数头文件*/int m=0,n=0; /*定义全局变量,反应龟兔当前位置*/void kongwei(){int i;for(i=0;i<10;i++){printf("\n");}for(i=0;i<33;i++){printf(" ");} /*输出一系列换行及空格,控制获胜信息语句位置*/}void paodao(){setcolor(15); /*设置跑道颜色*/rectangle(0,0,600,80);rectangle(50,0,50,80);rectangle(0,40,600,40); /*画出跑道*/}void guitu(int m,int n) /*龟兔图形函数*/ {setcolor(5); /*龟兔颜色*/rectangle(6+m,20,12+m,20);circle(47+m,20,3);circle(18+m,31,2);circle(18+m,9,2);circle(38+m,31,2);ellipse(28+m,20,0,360,16,12); /*画出龟*/ellipse(38+n,51,0,360,6,4);ellipse(36+n,45,0,360,1,3);ellipse(40+n,45,0,360,1,3);ellipse(38+n,65,0,360,6,10);ellipse(45+n,71,0,360,3,1);ellipse(44+n,75,0,360,6,1);ellipse(29+n,73,0,360,4,2);circle(41+n,50,1); /*画出兔*/}void fugai(int m,int n) /*用背景色覆盖函数*/ {setcolor(0); /*设置为背景黑色*/rectangle(6+m,20,12+m,20);circle(47+m,20,3);circle(18+m,31,2);circle(38+m,31,2);circle(38+m,9,2);ellipse(28+m,20,0,360,16,12); /*覆盖上一刻龟图形*/ellipse(38+n,51,0,360,6,4);ellipse(36+n,45,0,360,1,3);ellipse(40+n,45,0,360,1,3);ellipse(38+n,65,0,360,6,10);ellipse(45+n,71,0,360,3,1);ellipse(44+n,75,0,360,6,1);ellipse(29+n,73,0,360,4,2);circle(41+n,50,1); /*覆盖上一刻兔图形*/}void GuiTu(int number) /*设置游戏规则函数*/ {if(number>=1 && number<=5){m+=12; /*乌龟前进12格*/if(number==6 || number==7){m+=3; /*乌龟前进3格*/}if(number>=8 && number<=10){m+=18; /*乌龟前进18格*/ }if(number==1 || number==2){n+=0; /*兔子原地不动*/ }if(number==3 || number==4){n+=24; /*兔子前进24格*/ }if(number==5)n+=12; /*兔子前进12格*/ }if(number>=6 && number<=8){n+=18; /*兔子前进18格*/ }if(number==9 || number==10){n+=3; /*兔子前进3格*/ }guitu(m,n); /*显示运动后龟兔*/}void main(){int d,a,number,i;d=DETECT;a=0;initgraph(&d,&a,""); /*自动检测硬件图形系统,并选用最大分辨率显示模式*/paodao(); /*画出跑道*/guitu(m,n); /*显示当前龟兔*/sleep(3); /*系统挂起3秒*/while(1){paodao(); /*补全被覆盖的部分跑道*/fugai(m,n); /*覆盖上一刻图形*/number=rand()%10+1; /*随机数发生器*/GuiTu(number); /*龟兔按所给规则运动*/if(m>=550 && n>=550) /*是否龟兔同时到达终点*/{kongwei();printf("Arrive together !\n"); /*输出同时到达信息*/break; /*跳出循环*/}if(m>=550) /*是否龟到达终点*/ {kongwei();printf("Gui win !\n"); /*输出龟赢信息*/ellipse(300,129,0,360,16,6);rectangle(278,129,284,129);circle(319,129,3);circle(290,134,2);rectangle(240,157,360,177);rectangle(270,137,330,157); /*画出领奖台*/break; /*跳出循环*/}if(n>=550) /*是否兔到达终点*/ {kongwei();printf("Tu win !\n"); /*输出兔赢信息*/ellipse(300,124,0,360,6,10);ellipse(300,110,0,360,6,4);ellipse(298,104,0,360,1,3);ellipse(302,104,0,360,1,3);ellipse(307,130,0,360,3,1);ellipse(306,134,0,360,6,1);ellipse(291,131,0,360,4,2);rectangle(240,157,360,177);rectangle(270,137,330,157); /*画出领奖台*/break; /*跳出循环*/}sleep(1); /*系统挂起1秒*/}sleep(5); /*系统挂起5秒后,程序结束*/}。

龟兔赛跑python代码

龟兔赛跑python代码

龟兔赛跑python代码龟兔赛跑是一个经典的寓言故事,讲述了一只乌龟和一只兔子之间的比赛。

在这个故事中,兔子因为自信过度而停下来休息,最终被乌龟赶超并赢得比赛。

这个故事告诉我们,自信是好的,但过度自信会导致失败。

在这篇文章中,我们将使用Python编写一个龟兔赛跑的程序,来模拟这个经典的故事。

我们需要安装Python的turtle模块。

这个模块可以让我们在屏幕上绘制图形,包括乌龟和兔子。

我们可以使用以下命令来安装turtle模块:```pip install turtle```接下来,我们需要编写程序来模拟龟兔赛跑。

我们可以使用Python 的随机数生成器来模拟兔子和乌龟的速度。

我们可以使用以下代码来生成一个随机数:```import randomspeed = random.randint(1, 10)```这个代码将生成一个1到10之间的随机数,表示兔子或乌龟的速度。

我们可以使用这个速度来移动兔子和乌龟的位置。

接下来,我们需要绘制乌龟和兔子。

我们可以使用turtle模块来绘制它们。

以下是绘制乌龟的代码:```import turtleturtle.shape('turtle')turtle.color('green')turtle.penup()turtle.goto(-200, 0)turtle.pendown()```这个代码将绘制一个绿色的乌龟,它的起始位置是屏幕左侧的-200像素处。

我们可以使用类似的代码来绘制兔子。

接下来,我们需要编写程序来模拟龟兔赛跑。

我们可以使用一个while循环来模拟比赛。

在每个循环中,我们将生成一个随机数来表示兔子和乌龟的速度。

然后,我们将使用这个速度来移动它们的位置。

我们可以使用以下代码来移动乌龟:```turtle.forward(speed)```这个代码将使乌龟向前移动speed个像素。

我们可以使用类似的代码来移动兔子。

龟兔赛跑java代码

龟兔赛跑java代码

龟兔赛跑java代码```javaimport java.util.Random;public class TortoiseAndHareRace {public static void main(String[] args) {// 生成随机数种子Random random = new Random();// 比赛距离int raceDistance = 100;// 兔子的速度int rabbitSpeed = 10;// 乌龟的速度int tortoiseSpeed = 2;// 模拟比赛过程Tortoise tortoise = new Tortoise(tortoiseSpeed);Rabbit rabbit = new Rabbit(rabbitSpeed, raceDistance, random);while (tortoise.getDistanceTraveled() < raceDistance && rabbit.getDistanceTraveled() < raceDistance) {System.out.println("兔子跑了 " + rabbit.getDistanceTraveled() + " 米,乌龟跑了 " + tortoise.getDistanceTraveled() + " 米。

");// 让兔子和乌龟继续跑tortoise.run();rabbit.run();}// 输出比赛结果if (tortoise.getDistanceTraveled() == raceDistance) {System.out.println("乌龟到达终点线,赢得比赛!");} else if (rabbit.getDistanceTraveled() == raceDistance) {System.out.println("兔子到达终点线,赢得比赛!");} else {System.out.println("兔子和乌龟都没有到达终点线。

龟兔赛跑java代码 -回复

龟兔赛跑java代码 -回复

龟兔赛跑java代码-回复“龟兔赛跑”是一则经典的寓言故事,它讲述了一只乌龟和一只兔子之间的竞争。

这个故事中,乌龟和兔子各自代表着不同的特点和策略。

在这篇文章中,我们将一步一步地解析“龟兔赛跑”的Java代码,帮助读者了解这个故事并学习如何使用Java语言来实现它。

首先,我们需要定义两个类:乌龟类(Turtle)和兔子类(Rabbit)。

乌龟类和兔子类分别代表了乌龟和兔子的特点和行为。

javapublic class Turtle {private int position;private int speed;public Turtle(int speed) {this.position = 0;this.speed = speed;}public void move() {this.position += this.speed;}public int getPosition() {return this.position;}}public class Rabbit {private int position;private int speed;public Rabbit(int speed) {this.position = 0;this.speed = speed;}public void move() {this.position += this.speed;}public int getPosition() {return this.position;}在代码中,乌龟类和兔子类都有一个私有的属性position表示它们的位置,以及一个私有的属性speed表示它们的速度。

构造方法用于初始化乌龟和兔子的速度。

move()方法被定义在乌龟类和兔子类中,用来改变它们的位置。

当调用move()方法时,乌龟和兔子的位置会根据它们的速度进行相应的改变。

getPosition()方法被定义在乌龟类和兔子类中,用于返回它们当前的位置。

赛跑游戏编程实现

赛跑游戏编程实现

赛跑游戏编程实现为了满足人们对于刺激与竞争的需求,赛跑游戏一直以其简单易懂的规则和快节奏的游戏体验获得了广泛的喜爱。

本文将介绍如何使用编程语言来实现一个基于控制台窗口的赛跑游戏,并给出相应的代码示例。

一、准备工作在开始编写代码之前,我们需要准备一个编程环境。

这里我们选用Python作为编程语言,并使用其内置的turtle库来实现图形绘制和动画效果。

请确保您已经安装了Python,并具备基本的编程知识。

二、创建游戏窗口首先,在Python的交互式环境中导入turtle库,并创建一个画布作为游戏窗口。

以下是相应的代码示例:```import turtlewindow = turtle.Screen()window.title("赛跑游戏")window.bgcolor("white")window.setup(width=800, height=600)```以上代码中,我们使用turtle.Screen()函数创建了一个名为window 的游戏窗口,并设置了窗口的标题、背景色以及大小。

三、绘制赛道接下来,我们需要在游戏窗口中绘制赛道。

为了使游戏有足够的挑战性,我们将绘制多条赛道,并给每条赛道设置不同的颜色。

以下是相应的代码示例:```import turtlewindow = turtle.Screen()window.title("赛跑游戏")window.bgcolor("white")window.setup(width=800, height=600)def draw_track():track_colors = ["red", "blue", "green", "yellow"]track_width = 400track_height = 20num_tracks = len(track_colors)for i in range(num_tracks):track = turtle.Turtle()track.shape("square")track.color(track_colors[i])track.shapesize(track_height / 20, track_width / 20)track.penup()track.goto(-track_width / 2, track_height * (i - num_tracks/2))draw_track()turtle.done()```以上代码中,我们定义了一个名为draw_track()的函数,该函数用于绘制赛道。

龟兔赛跑程序代码

龟兔赛跑程序代码

package com.lzw;import java.awt.BorderLayout;import java.awt.Color;import java.awt.EventQueue;import java.awt.Font;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextArea;import javax.swing.SwingConstants;import javax.swing.JComboBox;import com.swtdesigner.SwingResourceManager;public class Run extends JFrame {private String win = "";// 胜利信息private JTextArea textArea;// 文本域组件JLabel tortoise;// 乌龟标签组件JLabel tortoise1;// 乌龟标签组件JLabel tortoise2;// 乌龟标签组件JLabel rabbit;// 兔子标签组件JLabel rabbit1;// 兔子标签组件JLabel rabbit2;// 兔子标签组件private JLabel winLabel;// 显示胜利信息的标签组件private boolean isStart = false;// 游戏是否开始的状态变量private boolean sleep = true;// 兔子是否睡过觉的状态变量private JComboBox faceCombo; //页面的组合框,用于数量的选择BackgroundPanel backgroundPanel= new BackgroundPanel() ;// 创建面板组件public static void main(String args[]) {EventQueue.invokeLater(new Runnable() {public void run() {try {Run frame = new Run();// 创建本类实例对象frame.setVisible(true);// 显示窗体} catch (Exception e) { //处理异常e.printStackTrace();}}});}/*** Create the frame*/public Run() {super();setBounds(100, 100, 500, 700);backgroundPanel.setImage(SwingResourceManager.getImage(Run.class, "background.jpg"));getContentPane().add(backgroundPanel, BorderLayout.CENTER);// 添加面板到窗体faceCombo=new JComboBox();faceCombo.setBackground(Color.GREEN);faceCombo.setEnabled(true);faceCombo.addItem("1");faceCombo.addItem("2");faceCombo.addItem("3");faceCombo.setBounds(366, 10, 122, 44);backgroundPanel.add(faceCombo);// 添加标签到面板faceCombo.addActionListener(newActionListener(){public void actionPerformed(ActionEvent event){if(faceCombo.getSelectedIndex()==1){new ItemSelect();winLabel.setText("您选中的是一号模式,请单击开始按钮进行比赛");}if(faceCombo.getSelectedIndex()==0){new ItemSelect1();winLabel.setText("您选中的是二号模式,请单击开始按钮进行比赛");}}});final JButton button = new JButton();// 创建开始按钮button.setPressedIcon(SwingResourceManager.getIcon(Run.class, "start2.png"));button.setFocusPainted(false);button.setContentAreaFilled(false);button.setBorderPainted(false);button.setIcon(SwingResourceManager.getIcon(Run.class,"start.png"));button.addActionListener(new ActionListener() {// 为按钮添加事件监听器public void actionPerformed(final ActionEvent e) {new Thread(new Time()).start();}});button.setText("开始");button.setBounds(366, 537, 143, 170);backgroundPanel.add(button);// 添加按钮到面板组件textArea = new JTextArea();textArea.setForeground(Color.GREEN);textArea.setFocusable(false);textArea.setFont(new Font("楷体", Font.BOLD, 16));textArea.setOpaque(false);textArea.setEditable(false);textArea.setLineWrap(true);textArea.setText("请先选择比赛模式");textArea.setBounds(240, 10, 122, 44);backgroundPanel.add(textArea);winLabel = new JLabel();winLabel.setForeground(Color.GREEN);winLabel.setText("比赛中.......");winLabel.setBounds(51, 10, 157, 27);backgroundPanel.add(winLabel);}/*** Create the first model*/class ItemSelect{public ItemSelect(){rabbit = new JLabel();// 创建显示兔子的标签rabbit.setHorizontalTextPosition(SwingConstants.CENTER);rabbit.setIcon(SwingResourceManager.getIcon(Run.class, "rabbit.png"));rabbit.setBounds(135, 591, 73, 73);backgroundPanel.add(rabbit);// 添加标签到面板tortoise = new JLabel();// 创建显示乌龟的标签组件tortoise.setIcon(SwingResourceManager.getIcon(Run.class, "tortoise.png"));tortoise.setText("乌龟");tortoise.setBounds(267, 591, 82, 63);backgroundPanel.add(tortoise);// 添加标签到面板}}/*** Create the second model*/class ItemSelect1{public ItemSelect1(){rabbit = new JLabel();// 创建显示兔子的标签rabbit.setHorizontalTextPosition(SwingConstants.CENTER);rabbit.setIcon(SwingResourceManager.getIcon(Run.class, "rabbit.png"));rabbit.setBounds(115, 591, 73, 73);backgroundPanel.add(rabbit);// 添加标签到面板rabbit1 = new JLabel();// 创建显示兔子的标签rabbit1.setHorizontalTextPosition(SwingConstants.CENTER);rabbit1.setIcon(SwingResourceManager.getIcon(Run.class, "rabbit.png"));rabbit1.setBounds(185, 591, 70, 73);backgroundPanel.add(rabbit1);// 添加标签到面板tortoise = new JLabel();// 创建显示乌龟的标签组件tortoise.setIcon(SwingResourceManager.getIcon(Run.class,"tortoise.png"));tortoise.setText("乌龟");tortoise.setBounds(225, 591, 82, 63);backgroundPanel.add(tortoise);// 添加标签到面板tortoise1 = new JLabel();// 创建显示乌龟的标签组件tortoise1.setIcon(SwingResourceManager.getIcon(Run.class, "tortoise.png"));tortoise1.setText("乌龟");tortoise1.setBounds(225, 591, 82, 63);backgroundPanel.add(tortoise1);// 添加标签到面板}}/*** 设置胜利者的方法,该方法是线程同步的*/private synchronized void setWin(String str) {if (win.isEmpty()) {// 如果没有设置胜利者win = str;// 设置胜利者为str参数指定角色winLabel.setText(win);isStart = false;}}/*** 比赛开始*/class Time implements Runnable{private RabbitThread rabbitThread;private TortoiseThread tortoiseThread;public void run() {rabbit.setLocation(135, 591);// 设置兔子标签的位置tortoise.setLocation(267, 591);// 设置乌龟标签的位置win = "";// 清除胜利信息winLabel.setText("比赛中.......");// 设置比赛状况信息isStart = true;sleep = true;if(faceCombo.getSelectedIndex()==1){new Thread(new RabbitThread()).start();//创建线程并开始执行线程new Thread(new TortoiseThread()).start();//创建线程并开始执行线程}if(faceCombo.getSelectedIndex()==0){new Thread(new RabbitThread()).start();//创建线程并开始执行线程new Thread(new TortoiseThread()).start();//创建线程并开始执行线程new Thread(new RabbitOneThread()).start();//创建线程并开始执行线程new Thread(new TortoiseOneThread()).start();//创建线程并开始执行线程}} }/*** 控制兔子1的线程*/class RabbitThread implements Runnable {private int SPEED ;//兔子的移动速度private boolean stop=true;private boolean awake=true;public void run() {while(stop){SPEED = (int)(Math.random()*10);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}if(rabbit.getLocation().y > rabbit.getHeight()/2) {//如果兔子1没到终点Point point2 = rabbit.getLocation();//获取兔子1的位置rabbit.setLocation(point2.x, point2.y - SPEED);//使兔子1移动}else{setWin("兔子1胜利");stop=false;}Point point = rabbit.getLocation();Point point1 = tortoise.getLocation();if(((point.y+100)<point1.y)&&awake){rabbit.setText("睡觉");try {Thread.sleep((long)(Math.random() * 4000 + 4000));// 线程随机休眠8至12秒} catch (InterruptedException e) {e.printStackTrace();}rabbit.setText("");} }}}/*** 控制兔子2的线程*/class RabbitOneThread implements Runnable{private int SPEED ;//兔子1的移动速度private boolean stop=true;private boolean awake=true;public void run(){while(stop){SPEED = (int)(Math.random()*10);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}if(rabbit1.getLocation().y > rabbit1.getHeight()/2) {//如果兔子2没到终点Point point2 = rabbit1.getLocation();//获取兔子2的位置rabbit1.setLocation(point2.x, point2.y - SPEED);//使兔子2移动}else{setWin("兔子2胜利");stop=false;}Point point = rabbit1.getLocation();Point point3 = tortoise1.getLocation();if(((point.y+100)<point3.y)&&awake){rabbit1.setText("睡觉");try {Thread.sleep((long) (Math.random() * 4000 + 4000));// 线程随机休眠8至12秒} catch (InterruptedException e) {e.printStackTrace();}rabbit1.setText("");}}}}/*** 控制乌龟1的线程*/class TortoiseThread implements Runnable {private int SPEED;//乌龟1的移动速度private boolean stop=true;public void run() {while(stop){SPEED = (int)(Math.random()*5);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}if (tortoise.getLocation().y > tortoise.getHeight()/2) {//如果乌龟没到终点Point point = tortoise.getLocation();//获取乌龟的位置tortoise.setLocation(point.x, point.y - SPEED);//使乌龟移动}else{setWin("乌龟1胜利");stop=false;}} }}/*** 控制乌龟2的线程*/class TortoiseOneThread implements Runnable{private int SPEED;//乌龟1的移动速度private boolean stop=true;public void run() {if(faceCombo.getSelectedIndex()==0){while(stop){SPEED = (int)(Math.random()*5);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}if (tortoise1.getLocation().y > tortoise1.getHeight()/2) {//如果乌龟2没到终点Point point = tortoise1.getLocation();//获取乌龟2的位置tortoise1.setLocation(point.x, point.y - SPEED);//使乌龟2移动}else{setWin("乌龟2胜利");stop=false;}}}}}}。

java编程

java编程

龟兔赛跑问题用线程模拟龟兔赛跑问题。

即,兔子每次跳两步或者打瞌睡,乌龟每秒走一步。

路程为10步。

public class TortoiseHareRace {public static void main(String[] args) throws InterruptedException{ boolean[]flags={true,false};int totalStep=10;int tortoiseStep=0;int hareStep=0;System.out.println("龟兔赛跑开始。

");while (tortoiseStep<totalStep&&hareStep<totalStep) {Thread.sleep(1000);tortoiseStep++;System.out.printf("乌龟跑了%d步。

%n",tortoiseStep);boolean isHareSleep= flags[((int)(Math.random()*10))%2];if(isHareSleep){System.out.println("兔子睡着了zzzz");}else{hareStep+=2;System.out.printf("兔子跑了%d步....%n",hareStep);}}}}生产者消费者问题编写一个生产者消费者程序,生产者在生产了一个整数后,必须等待消费者访问处理该整数后才能生产下一个数。

生产者将顺序生产整数1~10,消费者在消费到最后一个整数10时将结束运行。

【基本思路】建立一个共享区域类,该类中有两个方法,一个用于设置共享整数值,一个用于获取共享整数值,通过一个布尔变量来控制共享整数的设置与获取的交替进行。

在主程序中首先创建该类的一个共享对象,然后将该共享对象分别传递给生产者线程和消费者线程。

龟兔赛跑程序代码

龟兔赛跑程序代码

Public i As Integer, m As Integer, n As Integer, k As Integer, j As IntegerPrivate Sub b2_Click()MsgBox "初次尝试,欢迎多多指教!", 48, "关于龟兔赛跑"End SubPrivate Sub HScroll1_Change()Text3.Text = HScroll1.V alueEnd SubPrivate Sub p5_Click()Label1.Caption = "预备"Text1.Text = "0:00:00"Text2.Text = "0:00:00"Timer2.Enabled = FalseTimer3.Enabled = Falsen = 0k = 0p3.Left = 1680p4.Left = 1680i = 1Timer1.Enabled = TrueEnd SubPrivate Sub a1_Click()p5_ClickEnd SubPrivate Sub a2_Click()EndEnd SubPrivate Sub b1_Click()Form3.ShowEnd SubPrivate Sub p5_KeyDown(KeyCode As Integer, Shift As Integer)j = HScroll1.V alueStatic blin1 As BooleanStatic blin2 As BooleanIf KeyCode = vbKeyA Or KeyCode = vbKeyS ThenIf i < 8 ThenText2.Text = "抢跑"MsgBox "兔选手,你抢跑了!", 16, "犯规" Text2.Text = "0:00:00"Text1.Text = "0:00:00"n = 0k = 0i = 1Exit SubEnd IfEnd IfIf blin1 = False And i = 8 ThenIf KeyCode = vbKeyA Thenp3.Left = p3.Left + jblin1 = Not blin1blin2 = Not blin2End IfEnd IfIf blin2 = True And i = 8 ThenIf KeyCode = vbKeyS Thenp3.Left = p3.Left + jblin2 = Not blin2blin1 = Not blin1End IfEnd IfStatic blin3 As BooleanStatic blin4 As BooleanIf KeyCode = 186 Or KeyCode = 222 ThenIf i < 8 ThenText2.Text = "抢跑"MsgBox "龟选手,你抢跑了!", 16, "犯规"i = 1Text2.Text = "0:00:00"n = 0k = 0Exit SubEnd IfEnd IfIf blin3 = False And i = 8 ThenIf KeyCode = 186 Thenp4.Left = p4.Left + jblin3 = Not blin3blin4 = Not blin4End IfIf blin4 = True And i = 8 ThenIf KeyCode = 222 Thenp4.Left = p4.Left + jblin4 = Not blin4blin3 = Not blin3End IfEnd IfIf p3.Left >= p1.Width - p3.Width + 1680 ThenTimer3.Enabled = Falsep3.Left = p1.Width - p3.Width + 1680End IfIf p4.Left >= p2.Width - p4.Width + 1680 ThenTimer2.Enabled = Falsep4.Left = p2.Width - p4.Width + 1680End IfIf p3.Left >= p1.Width - p3.Width + 1680 And p4.Left >= p2.Width - p4.Width + 1680 ThenIf k = n ThenMsgBox "和局!", 48Label1.Visible = FalseTimer2.Enabled = FalseTimer3.Enabled = Falsek = 0n = 0Text1.Text = "0:00:00"Text2.Text = "0:00:00"p3.Left = 1680p4.Left = 1680End IfIf n > k ThenMsgBox "龟选手,你赢了!", 48Label1.Visible = FalseTimer2.Enabled = FalseTimer3.Enabled = Falsek = 0n = 0Text1.Text = "0:00:00"Text2.Text = "0:00:00"p3.Left = 1680p4.Left = 1680If k > n ThenMsgBox "兔选手,你赢了!", 48Label1.Visible = FalseTimer2.Enabled = FalseTimer3.Enabled = Falsek = 0n = 0Text1.Text = "0:00:00"Text2.Text = "0:00:00"p3.Left = 1680p4.Left = 1680End IfEnd IfEnd SubPrivate Sub Timer1_Timer()Label1.Visible = Not Label1.Visiblei = i + 1If i = 8 ThenLabel1.Caption = "开始"Label1.Visible = TrueTimer2.Enabled = TrueTimer3.Enabled = TrueTimer1.Enabled = FalseEnd IfEnd SubPrivate Sub Timer3_Timer()n = n + 1n0 = n Mod 60n1 = (n \ 60) Mod 60n2 = ((n \ 60) \ 60) Mod 60Text1.Text = Right(("0" & CStr(n2)), 2) & ":" & Right(("0" + CStr(n1)), 2) & ":" & Right("0" & CStr(n0), 2)End SubPrivate Sub Timer2_Timer()k = k + 1k0 = k Mod 60k2 = ((k \ 60) \ 60) Mod 60Text2.Text = Right(("0" & CStr(k2)), 2) & ":" & Right(("0" + CStr(k1)), 2) & ":" & Right("0" & CStr(k0), 2)End Sub。

java 龟兔赛跑

java 龟兔赛跑

/** RabbitTortoiseThrea.java** Created on __DATE__, __TIME__*/package Thread;import Thread.TuZi;import Thread.WuGui;/**** @author __USER__*/public class RabbitTortoiseThrea extends javax.swing.JFrame {/** Creates new form RabbitTortoiseThrea */public RabbitTortoiseThrea() {initComponents();}/** 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.*///GEN-BEGIN:initComponents// <editor-fold defaultstate="collapsed" desc="Generated Code">private void initComponents() {jLabel1 = new javax.swing.JLabel();jLabel2 = new javax.swing.JLabel();jLabel3 = new javax.swing.JLabel();jProgressBarRabbit = new javax.swing.JProgressBar();jProgressBarTortoise = new javax.swing.JProgressBar();jButton1 = new javax.swing.JButton();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);jLabel1.setText("\u9f9f\u5154\u8d5b\u8dd1");jLabel2.setText("\u5154\u5b50");jLabel3.setText("\u4e4c\u9f9f");jProgressBarRabbit.setBackground(new java.awt.Color(255, 255, 255)); jProgressBarRabbit.addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorMoved(javax.swing.event.AncestorEvent evt) {}public void ancestorAdded(javax.swing.event.AncestorEvent evt) {jProgressBarRabbitAncestorAdded(evt);}public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {}});jProgressBarTortoise.addAncestorListener(new javax.swing.event.AncestorListener() { public void ancestorMoved(javax.swing.event.AncestorEvent evt) {}public void ancestorAdded(javax.swing.event.AncestorEvent evt) {jProgressBarTortoiseAncestorAdded(evt);}public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {}});jButton1.setText("\u5f00\u59cb\u6bd4\u8d5b");jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt);}});javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(21,21,21).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(jLabel2).addComponent(jLabel3)).addGap(18,18).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,false).addComponent(jProgressBarRabbit,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addComponent(jProgressBarTortoise,javax.swing.GroupLayout.DEFAULT_SIZE,288,Short.MAX_VALUE))).addGroup(layout .createSequentialGroup().addGap(155,155).addComponent(jButton1)).addGroup(layout.createSequentialGroup().addGap(176,176,176).addComponent(jLabel1))).addContainerGap(63, Short.MAX_VALUE)));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(45, 45, 45).addComponent(jLabel1).addGap(47, 47, 47).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel2).addComponent( jProgressBarRabbit,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(58, 58, 58).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addComponent(jLabel3).addComponent( jProgressBarTortoise,javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(53, 53, 53).addComponent(jButton1).addGap(52, 52, 52)));pack();}// </editor-fold>//GEN-END:initComponentsprivate void jProgressBarRabbitAncestorAdded(javax.swing.event.AncestorEvent evt) {jProgressBarRabbit.setVisible(true);}private void jProgressBarTortoiseAncestorAdded(javax.swing.event.AncestorEvent evt) {jProgressBarTortoise.setVisible(true);}private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { TuZi tuZi = new TuZi(jProgressBarRabbit);Thread tuziThread = new Thread(tuZi);WuGui wuGui = new WuGui(jProgressBarTortoise);Thread wuguiThread = new Thread(wuGui);tuziThread.start();wuguiThread.start();}/*** @param args the command line arguments*/public static void main(String args[]) {java.awt.EventQueue.invokeLater(new Runnable() {public void run() {new RabbitTortoiseThrea().setVisible(true);}});}//GEN-BEGIN:variables// Variables declaration - do not modifyprivate javax.swing.JButton jButton1;private javax.swing.JLabel jLabel1;private javax.swing.JLabel jLabel2;private javax.swing.JLabel jLabel3;private javax.swing.JProgressBar jProgressBarRabbit;private javax.swing.JProgressBar jProgressBarTortoise;// End of variables declaration//GEN-END:variables}。

java课程设计龟兔赛跑源码

java课程设计龟兔赛跑源码

java课程设计龟兔赛跑源码一、教学目标本节课的教学目标是让学生通过学习《龟兔赛跑》的Java源码,掌握以下知识目标:1.掌握Java编程的基本语法和结构;2.理解并掌握类、对象、继承、多态等面向对象编程的基本概念;3.掌握异常处理、输入输出流等基本编程技能;4.能够使用Java编写简单的程序;5.能够分析并解决编程过程中遇到的问题;6.能够独立完成《龟兔赛跑》的Java源码编写和调试。

情感态度价值观目标:1.培养学生的编程兴趣,提高学生对编程的认同感和自信心;2.培养学生团队合作意识和解决问题的能力;3.培养学生诚实守信、不畏困难的品质。

二、教学内容本节课的教学内容以《龟兔赛跑》的Java源码为主线,主要包括以下几个部分:1.Java编程的基本语法和结构;2.面向对象编程的基本概念,包括类、对象、继承、多态等;3.异常处理和输入输出流的基本使用;4.《龟兔赛跑》的Java源码编写和调试。

三、教学方法为了达到本节课的教学目标,我们将采用以下几种教学方法:1.讲授法:讲解Java编程的基本语法和结构,面向对象编程的基本概念;2.案例分析法:分析并讨论《龟兔赛跑》的Java源码,引导学生掌握异常处理和输入输出流的使用;3.实验法:让学生动手编写和调试《龟兔赛跑》的Java源码,提高学生的编程技能。

四、教学资源为了支持本节课的教学内容和教学方法的实施,我们将准备以下教学资源:1.教材:《Java编程思想》;2.多媒体资料:PPT课件,龟兔赛跑的Java源码示例;3.实验设备:计算机,网络环境。

五、教学评估为了全面、客观、公正地评估学生的学习成果,我们将采用以下评估方式:1.平时表现:通过课堂参与、提问、回答问题等方式评估学生的学习态度和积极性,占总评的30%;2.作业:布置与课程内容相关的编程作业,评估学生的编程能力和理解程度,占总评的30%;3.考试:进行期末考试,涵盖课程所有知识点,评估学生的综合运用能力,占总评的40%。

python乌龟赛跑代码

python乌龟赛跑代码

python乌龟赛跑代码乌龟赛跑是一个有趣的游戏,可以通过编写Python代码来模拟这个游戏。

这个游戏的规则是,有几只乌龟在指定的距离上进行比赛,第一只到达终点的乌龟获胜。

首先,我们需要创建一个乌龟类。

每只乌龟都有一个名字和速度属性,可以通过调整速度来模拟不同乌龟的速度差异。

```pythonimport randomclass Turtle:def __init__(self, name, speed): = nameself.speed = speed```接下来,我们需要创建一个比赛函数。

在比赛函数中,我们会生成一些乌龟对象,并模拟它们的移动,直到有一只乌龟到达终点。

```pythondef race(distance):turtles = [Turtle('乌龟1', random.randint(1, 10)),Turtle('乌龟2', random.randint(1, 10)),Turtle('乌龟3', random.randint(1, 10))]winner = Nonewhile True:for turtle in turtles:turtle.speed += random.randint(-1, 1) # 模拟乌龟的速度变化turtle.speed = max(1, turtle.speed) # 限制乌龟的最小速度为1turtle.distance += turtle.speed # 乌龟移动的距离if turtle.distance >= distance:winner = turtlebreakif winner:breakprint('获胜的乌龟是:', )```最后,我们可以调用比赛函数,并传入指定的距离来开始比赛。

```pythonrace(100) # 指定比赛的距离为100```运行代码后,你会看到输出结果中会显示获胜的乌龟的名字。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

要求龟兔赛跑:--普通格,共100格龟:每次随机移动1至3格兔子:每次随机移动1至6格每20格会随机出现以下功能格各一次(不会在同一格内出现两种或两种以上功能)功能格:(**和^^可以连续执行,@@和==不能连续执行)**幸运星格:选手可再行动一次@@地雷格:兔子回到上数两个地雷格,龟回到上一地雷格(若后方无地雷格则回到起点)==传送格:兔子到达下一传送格,龟到达下数两个传送格(若前方无传送格则到达终点)||树格:兔子停止三次行动^^下坡格:龟前进10格主程序/地图package gtsp;//包名import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Mapp {public static String[] functionPosition() {//每20格出现随机功能实现int[] t = new int[5];String[] partMap = new String[20];for (int i = 0; i < 5;) {int random = (int) (20 * Math.random());int judge = 0;for (int j = 0; j < 5; j++) {if (t[j] == random) {judge = 0;break;} else {judge = 1;}}if (judge == 1) {t[i] = random;i++;}}for (int i = 0; i < 20; i++) {partMap[i] = "∷";}partMap[t[0]] = "★";partMap[t[1]] = "@" ;partMap[t[2]] = "=";partMap[t[3]] = "|";partMap[t[4]] = "^";return partMap;}public static String[] getMap() {//创建地图分成五部分每部分20格 String[] map = new String[100];String[] partMap1 = functionPosition();for (int i = 0; i < 20; i++) {map[i] = partMap1[i];}String[] partMap2 = functionPosition();for (int i = 0; i < 20; i++) {map[i + (20 * 1)] = partMap2[i];}String[] partMap3 = functionPosition();for (int i = 0; i < 20; i++) {map[i + (20 * 2)] = partMap3[i];}String[] partMap4 = functionPosition();for (int i = 0; i < 20; i++) {map[i + (20 * 3)] = partMap4[i];}String[] partMap5 = functionPosition();for (int i = 0; i < 20; i++) {map[i + (20 * 4)] = partMap5[i];}return map;}public static void showMap(String[] map, Turtle T, Rabbit r) {//打印地图String[] t = new String[100];for (int i = 0; i < 100; i++) {t[i] = map[i];}t[T.position] = "龟";if (t[r.position] == "龟") {t[r.position] = "遇";} else {t[r.position] = "兔";}for (String i : t) {System.out.print(i);}}public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※");System.out.println("※※");System.out.println("※※ ");System.out.println("※龟兔赛跑※");System.out.println("※※ ");System.out.println("※※ ");System.out.println("※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※\n\n");String[] map = new String[100];map = getMap();Turtle T = new Turtle();Rabbit r = new Rabbit();showMap(map, T, r);InputStreamReader in = null;BufferedReader br = null;in = new InputStreamReader(System.in); //该处的System.in是各InputSream类型的;br = new BufferedReader(in);while ((T.position < 99) && (r.position < 99)) {try {String str = br.readLine();if (str.length() == 0) {T.execute(map, T);r.execute(map, T);if ((T.position < 99) && (r.position < 99)) {showMap(map, T, r);}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (T.position >=99) {System.out.println("\n乌龟赢了");} else {System.out.println("\n兔子赢了");}}}抽象类/部分功能格功能package gtsp;public abstract class Game {//抽象类Game 行走等功能int position = 0;boolean landmineJudge;boolean doorJudge;public void execute(String[] map, Turtle T) {//执行行走landmineJudge = true;doorJudge = true;position = position + getStep();function(map, T);}public void again(String[] map, Turtle T) {//调用execute方法再走一次System.out.println("再走一次");execute(map, T);}public abstract int getStep();public void landmine(String[] map) {//地雷功能System.out.println("遇到地雷");position = position - 1;while (map[position] != "@") {if (position != 0) {position--;} else {break;}}}public void door(String[] map) {//传送System.out.println("执行传送门");position = position + 1;while (map[position] != "=") {if (position != 99) {position++;} else {break;}}}public abstract void function(String[] map, Turtle T);}兔子类package gtsp;public class Rabbit extends Game {@Overridepublic int getStep() {//兔子行进步数1-6// TODO Auto-generated method stubint step = (int)(Math.random()*10) % 6 + 1;System.out.println("兔子行进" + step + "格");return step;}@Overridepublic void function(String[] map, Turtle T) {//兔子功能实现if (position < 99) {if (map[position] == "★") {System.out.println("兔子遇到幸运星");again(map, T);}if (map[position] == "@") {System.out.println("兔子遇到地雷");if (landmineJudge) {landmine(map);if (position != 0) {landmine(map);}}landmineJudge = false;}if (map[position] == "=") {System.out.println("兔子遇到传送门");if (doorJudge) {door(map);}doorJudge = false;}if (map[position] == "|") {System.out.println("兔子遇到树");T.execute(map, T);T.execute(map, T);T.execute(map, T);}}}}乌龟类package gtsp;public class Turtle extends Game {//继承Game@Overridepublic int getStep() {//乌龟每次行进次数1-3int step = (int)(Math.random()*10) % 3 + 1;System.out.println("乌龟行进" + step + "格");return step;}@Overridepublic void function(String[] map, Turtle T) {//乌龟功能格if (position < 99) {if (map[position] == "★") {System.out.println("乌龟遇到幸运星");again(map, T);}if (map[position] == "@") {System.out.println("乌龟遇到地雷");if (landmineJudge) {landmine(map);}landmineJudge = false;}if (map[position] == "=") {System.out.println("乌龟遇到传送门");if (doorJudge) {door(map);if (position != 99) {door(map);}}doorJudge = false;}if (map[position] == "^") {System.out.println("乌龟遇到下坡");position = position + 10;}}}}总共四个文件直接导入到一个包中就能运行必要修改包名或者删除文件中的包名。

相关文档
最新文档