TurtleSoup Java测试学习项目

TurtleSoup Java测试学习项目

项目文件下载:
Java测试学习项目

前言

实习题目给的是全英文的,由于整个描述也比较长,前言这里做一个简述概括,整个实习2主要是教我们如何通过测试用例进行开发编程,即测试驱动开发,通过JUnit测试用例以及相应应该得到的结果去对文件进行相应的编程

Problem 1: Import

Create Java project, and import the codes to your project.

这一步就没什么好说的,各种方法都可以进行java程序项目的导入

Problem 2: Warm up with mayUseCodeInAssignment

a. Look at the source code contained in RulesOf6005.java in package rules. Your warm-up task is to implement:

mayUseCodeInAssignment(

boolean writtenByYourself, boolean availableToOthers,

boolean writtenAsCourseWork, boolean citingYourSource,

boolean implementationRequired)

Once you’ve implemented this method, run the main method in RulesOf6005.java.

public static void main(String[] args) is the entry point for Java programs. In this case, the main method calls the mayUseCodeInAssignment method with input parameters. To run main in RulesOf6005, right click on the file RulesOf6005.java in either your Package Explorer, Project View, or Navigator View, go to the Run As option, and click on Java Application.

用人话讲就是你需要去实现mayUseCodeInAssignment这个功能,怎么实现呢?根据RulesOf6005Test里的测试用例以及他所定义的应该返回的情况进行撰写,这里我们首先导入RulesOf6005,然后在同一个包中新建一个JUnit测试,记得选择类名为RulesOf6005Test然后将其中的测试放入到JUnit生成出的下图的java文件中(由于题目的Junit和我所使用的的版本不同,故需如此操作)

我们可以看到该测试用例中有两种测试情况,一种是当参数为false,true,false,false,false时应返回false

当参数为true,false,true,true,true时应返回true,于是我们在RulesOf6005中按所给用例情况实现mayUseCodeInAssignment:

  public static boolean mayUseCodeInAssignment(boolean writtenByYourself,
            boolean availableToOthers, boolean writtenAsCourseWork,
            boolean citingYourSource, boolean implementationRequired) 
    {
        
        if(!writtenByYourself&&availableToOthers&&!writtenAsCourseWork&&!citingYourSource&&!implementationRequired)
        {
        	return false;
        }
        else if(writtenByYourself&&!availableToOthers&&writtenAsCourseWork&&citingYourSource&&implementationRequired)
        {
        	return true;
        }
        else
        {
        	return false;
        }
    }

运行Junit测试,成功通过

Problem 3 Turtle graphics and the Logo language

In the rest of problem set 0, we will be playing with a simple version of turtle graphics for Java that contains a restricted subset of the Logo language:

· forward(units)
Moves the turtle in the current direction by units pixels, where units is an integer. Following the original Logo convention, the turtle starts out facing up.

· turn(degrees)
Rotates the turtle by angle degrees to the right (clockwise), where degrees is a double precision floating point number.

You can see the definitions of these commands in Turtle.java.

Do NOT use any turtle commands other than forward and turn in your code for the following methods.

we need to finish:

drawSquare

Look at the source code contained in TurtleSoup.java in package turtle.

Your task is to implement drawSquare(Turtle turtle, int sideLength), using the two methods introduced above: forward and turn.

Once you’ve implemented the method, run the main method in TurtleSoup.java. The main method in this case simply creates a new turtle, calls your drawSquare method, and instructs the turtle to draw. Run the method by going to Run → Run As… → Java Application. A window will pop up, and, once you click the “Run!” button, you should see a square drawn on the canvas.

用人话讲就是首先我们需要完成drawSquare(Turtle turtle, int sideLength)并且需要使用上面介绍的forwardturn方法实现。最终效果是画一个正方形

这里首先聚焦给我们的java文件框架:

其中的Turtle.java接口即定义了我们等会需要使用的

· forward(units)

· turn(degrees)

这两个功能,然后DrawableTurtle.java实现了这个接口

public class DrawableTurtle implements Turtle {
private static final int CANVAS_WIDTH = 512;
private static final int CANVAS_HEIGHT = 512;

private static final int CIRCLE_DEGREES = 360;
private static final int DEGREES_TO_VERTICAL = 90;

private final List<Action> actionList;
private final List<LineSegment> lines;

private Point currentPosition;
private double currentHeading;
private PenColor currentColor;

/**
 * Create a new turtle for drawing on screen.
 */
public DrawableTurtle() {
    this.currentPosition = new Point(0, 0);
    this.currentHeading = 0.0;
    this.currentColor = PenColor.BLACK;
    this.lines = new ArrayList<>();
    this.actionList = new ArrayList<>();
}

public void forward(int steps) {
    double newX = currentPosition.x() + Math.cos(Math.toRadians(DEGREES_TO_VERTICAL - currentHeading)) * (double)steps;
    double newY = currentPosition.y() + Math.sin(Math.toRadians(DEGREES_TO_VERTICAL - currentHeading)) * (double)steps;

    LineSegment lineSeg = new LineSegment(currentPosition.x(), currentPosition.y(), newX, newY, currentColor);
    this.lines.add(lineSeg);
    this.currentPosition = new Point(newX, newY);

    this.actionList.add(new Action(ActionType.FORWARD, "forward " + steps + " steps", lineSeg));
}

public void turn(double degrees) {
    degrees = (degrees % CIRCLE_DEGREES + CIRCLE_DEGREES) % CIRCLE_DEGREES;
    this.currentHeading = (this.currentHeading + degrees) % CIRCLE_DEGREES;
    this.actionList.add(new Action(ActionType.TURN, "turn " + degrees + " degrees", null));
}

public void color(PenColor color) {
    this.currentColor = color;
    this.actionList.add(new Action(ActionType.COLOR, "change to " + color.toString().toLowerCase(), null));
}

/**
 * Draw the image created by this turtle in a window on the screen.
 */
public void draw() {
    SwingUtilities.invokeLater(() -> {
        (new TurtleGUI(actionList, CANVAS_WIDTH, CANVAS_HEIGHT)).setVisible(true);
    });
    return;
 }
}

所以其实我们只需要调用这个功能就可以了,我们很容易想到画一个正方形就是先forward(length)然后turn(90)重复执行4次,故我们实现这个功能

 public static void drawSquare(Turtle turtle, int sideLength) {		
	turtle.forward(sideLength);
	turtle.turn(90);
	turtle.forward(sideLength);
	turtle.turn(90);
	turtle.forward(sideLength);
	turtle.turn(90);
	turtle.forward(sideLength);
	turtle.turn(90);
}

实现效果如下图:


Polygons and headings

For detailed requirements, read the specifications of each function to be implemented above its declaration in TurtleSoup.java**. Be careful when dealing with mixed integer and floating point calculations.**

You should not change any of the method declarations (what’s a declaration?) below. If you do so, you risk receiving zero points on the problem set.

Drawing polygons

· Implement calculateRegularPolygonAngle
There’s a simple formula for what the inside angles of a regular polygon should be; try to derive it before googling/binging/duckduckgoing.

· Run the JUnit tests in TurtleSoupTest
The method that tests calculateRegularPolygonAngle should now pass and show green instead of red.

If testAssertionsEnabled fails, you did not follow the instructions in the Getting Started guide. Getting Started step 2 has setup you must perform before using Eclipse.

· Implement calculatePolygonSidesFromAngle
This does the inverse of the last function; again, use the simple formula. However, make sure you correctly round to the nearest integer. Instead of implementing your own rounding, look at Java’s java.lang.Math class for the proper function to use.

· Implement drawRegularPolygon
Use your implementation of calculateRegularPolygonAngle. To test this, change the main method to call drawRegularPolygon and verify that you see what you expect.

Calculating headings

· Implement calculateHeadingToPoint
This function calculates the parameter to turn required to get from a current point to a target point, with the current direction as an additional parameter. For example, if the turtle is at (0,1) facing 30 degrees, and must get to (0,0), it must turn an additional 150 degrees, so calculateHeadingToPoint(30, 0, 1, 0, 0) would return 150.0.

· Implement calculateHeadings
Make sure to use your calculateHeadingToPoint implementation here. For information on how to use Java’s List interface and classes implementing it, look up java.util.List in the Java library documentation. Note that for a list of n points, you will return n-1 heading adjustments; this list of adjustments could be used to guide the turtle to each point in the list. For example, if the input lists consisted of xCoords=[0,0,1,1] and yCoords=[1,0,0,1] (representing points (0,1), (0,0), (1,0), and (1,1)), the returned list would consist of [180.0, 270.0, 270.0].

用人话将就是绘制多边形

  • 实现calculateRegularPolygonAngle ,即求正多边形的内角是多大

  • 在JUnit测试中运行。测试TurtleSoupTest
    方法calculateRegularPolygonAngle现在应该通过并显示绿色而不是红色。

    如果testAssertionsEnabled失败,则您没有遵循《入门指南》中的说明。 入门步骤2已完成设置,使用Eclipse之前必须执行此设置。

  • 实现calculatePolygonSidesFromAngle
    这与最后一个函数相反。再次,使用简单的公式。但是,请确保正确舍入到最接近的整数。不用实现自己的舍入,而是查看Java的java.lang.Math类以了解要使用的正确函数。

  • 实施drawRegularPolygon
    实现calculateRegularPolygonAngle。要对此进行测试,请更改main调用方法,drawRegularPolygon并确认您看到了期望的结果。

计算标题

  • 实施calculateHeadingToPoint
    该功能turn以当前方向为附加参数,计算从当前点到目标点所需的参数。例如,如果乌龟在(0,1)处面对30度,并且必须到达(0,0),则它必须再旋转150度,因此calculateHeadingToPoint(30, 0, 1, 0, 0)将返回150.0
  • 实施calculateHeadings
    确保在calculateHeadingToPoint此处使用您的实施。有关如何使用Java的List接口以及实现该接口的类的信息,请查阅java.util.ListJava库文档。请注意,对于n个点的列表,您将返回n-1个标题调整;此调整列表可用于将乌龟引导到列表中的每个点。例如,如果输入列表由xCoords=[0,0,1,1]和组成yCoords=[1,0,0,1](表示点(0,1),(0,0),(1,0)和(1,1)),则返回列表将由组成[180.0, 270.0, 270.0]

我们接下来一个个实现:


  • 首先实现calculateRegularPolygonAngle

    即求正多边形内角,我们可以很容易查出正多边形内角和公式为180*(n-2),故每个内角为180 *(n-2)/n:

运行测试结果:

可以看到此测试通过;

  • 同时我们完成与之相对的反向操作calculatePolygonSidesFromAngleTest,即通过角度得出边数

  • 接下来实现drawRegularPolygon ,即画一个长度为x的正n边形。我们可以很容易想到先通过n求出角度然后进行绘图,代码如下:

     public static void drawRegularPolygon(Turtle turtle, int sides, int sideLength) {
            double angle=180.0-calculateRegularPolygonAngle(sides);
            for(int i=0;i<sides;i++)
            {
            	turtle.forward(sideLength);
                turtle.turn(angle);
            }
     }
    

    结果如下(5边形)测试:

  • 接下来实现calculateBearingToPoint,即某点到另一点的角度偏移

    public static double calculateBearingToPoint(double currentBearing, int currentX, int currentY,int targetX, int targetY) 
      {
        	double angle = Math.atan2(targetX - currentX, targetY - currentY) * 180 / Math.PI; 
        	double turnAngle = angle - currentBearing;
            if (turnAngle < 0)
                turnAngle += 360;
            return  turnAngle;
      }
    

测试通过:

  • 然后来实现calculateBearings

     public static List<Double> calculateBearings(List<Integer> xCoords, List<Integer> yCoords) 
        {
        	int xListLength = xCoords.size();
    		int yListLength = yCoords.size();
    		List<Double> list = new ArrayList<>();
    		if (0 == Integer.compare(xListLength, yListLength) && xListLength > 1) {
    			double currentBearing = 0;
    			for (int i = 0; i < xListLength - 1; ++i) {
    				double adjustmentsBearing = calculateBearingToPoint(currentBearing, xCoords.get(i), yCoords.get(i),
    						xCoords.get(i + 1), yCoords.get(i + 1));
    				list.add(adjustmentsBearing);
    				currentBearing = adjustmentsBearing - currentBearing;
    			}
    		}
    		return list;
        }
    

    测试结果如下:

    绘制drawPersonalArt
    public static void drawPersonalArt(Turtle turtle) {
        	double angle=10.0;
        	for(int i=1;i<10000;i++)
        	{
        		turtle.forward(50);
                turtle.turn(angle*i);    	
        	}
      }
    

    定长,每次旋转度数+10,最后结果如下:

    神奇的发现最终重合了!

  • 12
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值