Пример #1
0
  public void flush() throws IOException {
    if (!dirty) return;

    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    try {
      fos = new FileOutputStream(filePath);
      osw = new OutputStreamWriter(fos, charset);

      // 全局数据
      for (Line l : globalLines) {
        osw.write(l.toString());
        osw.write('\n');
      }

      // 各个块
      for (Sector s : sectors) {
        osw.write(s.toString());
      }

      dirty = false;
    } finally {
      // XXX 因为stream之间有一定的依赖顺序,必须按照一定的顺序关闭流
      if (osw != null) osw.close();
      if (fos != null) fos.close();
    }
  }
Пример #2
0
  /** By Dingding */
  private Set<Line.Segment> getRemovableLineSegments(
      Map<Position, Piece> pieceMap, PieceColor pieceColor) {
    Set<Line.Segment> removableLines = new HashSet<>();
    Set<Line> linesOnTheBoard =
        Line.getLinesOnTheBoard(
            this); // Get all the possible lines on the board. Positions don't need to be occupied.

    for (Line line : linesOnTheBoard) {
      Position currentPosition = line.getStartPosition();
      Position startOfSegment = null;
      Position endOfSegment = null;
      Direction direction = line.getDirection();
      int consecutivePieces =
          0; // We start at a dot position, so we can assume that we don't start in a set of
             // consecutive pieces
      boolean isInLineSegment = false;

      // Break the for-loop if an endOfSegment has been found (because the largest lines only have 7
      // positions on the board, there
      // can't be more than one set of four pieces of the same color (requiring at least 9
      // positions) on the board.
      for (;
          endOfSegment == null && isPositionOnPlayAreaOrOuterDots(currentPosition);
          currentPosition = currentPosition.next(direction)) {
        PieceColor currentPieceColor =
            pieceMap.containsKey(currentPosition)
                ? pieceMap.get(currentPosition).getPieceColor()
                : null;

        // Update the consecutivePieces
        if (currentPieceColor == pieceColor) consecutivePieces++;
        if (consecutivePieces == 4) isInLineSegment = true;
        if (currentPieceColor != pieceColor) consecutivePieces = 0;

        if (isInLineSegment) {
          if (isDotPosition(currentPosition) || currentPieceColor == null) {
            endOfSegment = currentPosition.previous(direction);
          }
        }

        // Update the startOfSegment if necessary
        if (startOfSegment == null) {
          if (currentPieceColor != null) {
            startOfSegment = currentPosition;
          }
        }
        if (currentPieceColor == null && endOfSegment == null) {
          startOfSegment = null;
        }

        // Add a line segment to the list if we have found one
        if (endOfSegment != null) {
          removableLines.add(new Line.Segment(this, startOfSegment, endOfSegment, direction));
        }
      }
    }

    return removableLines;
  }
Пример #3
0
  static Point project(Line l, Point p) {
    Point p1 = l.getP1();
    Point p2 = l.getP2();

    Vector base = new Vector(p2, p1);
    double r = Vector.dot(new Vector(p, p1), base) / base.norm();

    return base.scalarMul(r).plus(p1).toPoint();
  }
  private static List<String> update(List<String> lines, Line line) {
    String text = line.getText();

    int index = lines.indexOf(text);
    if (index < 0) {
      throw new IllegalArgumentException();
    }

    String updatedText = Line.join(line.getParts());

    lines.set(index, updatedText);

    return lines;
  }
Пример #5
0
    @Override
    public String toString() {
      StringBuilder sb = new StringBuilder();
      if (space0 != null) sb.append(space0);
      sb.append('[');
      if (space1 != null) sb.append(space1);
      if (name != null) sb.append(name);
      if (space2 != null) sb.append(space2);
      sb.append(']');
      if (space3 != null) sb.append(space3);
      if (comment != null) sb.append(comment);
      sb.append('\n');

      for (Line l : lines) sb.append(l.toString()).append('\n');
      return sb.toString();
    }
Пример #6
0
    private Line makeLine(Element lineNode, ClassGraphics graphics) {

      Lineprops lp = getLineProps(lineNode);

      int w = graphics.getBoundWidth();
      int h = graphics.getBoundHeight();
      FixedCoords fc1 = getFixedCoords(lineNode, w, h, "1");
      FixedCoords fc2 = getFixedCoords(lineNode, w, h, "2");

      Line newLine =
          new Line(fc1.x, fc1.y, fc2.x, fc2.y, getColor(lineNode), lp.strokeWidth, lp.lineType);
      newLine.setFixedX1(fc1.fx);
      newLine.setFixedX2(fc2.fx);
      newLine.setFixedY1(fc1.fy);
      newLine.setFixedY2(fc2.fy);

      return newLine;
    }
Пример #7
0
  public void setString(String sector, String key, String value) {
    dirty = true;

    Collection<Line> lines = getSectorLines(sector);
    if (lines == null) {
      Sector s = new Sector();
      s.name = sector;
      sectors.add(s);
      lines = s.lines;
    }

    for (Line l : lines) {
      if (l.key.equals(key)) {
        l.value = value;
        return;
      }
    }

    Line l = new Line();
    l.key = key;
    l.equalSign = true;
    l.value = value;
    lines.add(l);
  }
Пример #8
0
  private static Line parseLine(String line) {
    Line ret = new Line();
    String s = line;

    // 注释
    int index = StringUtil.find_first_of(s, COMMENT_STARTERS);
    if (index >= 0) {
      ret.comment = s.substring(index);
      s = s.substring(0, index);
    } else {
      ret.comment = null;
    }

    // space0
    index = StringUtil.find_first_not_of(s, SPACES);
    if (index >= 0) {
      ret.space0 = s.substring(0, index);
      s = s.substring(index);
    } else {
      ret.space0 = s;
      s = "";
    }

    // space3
    index = StringUtil.find_last_not_of(s, SPACES);
    if (index >= 0) {
      ret.space3 = s.substring(index + 1);
      s = s.substring(0, index + 1);
    } else {
      ret.space3 = s;
      s = "";
    }

    // '='
    index = s.indexOf('=');
    String strKey, strValue;
    if (index >= 0) {
      ret.equalSign = true;
      strKey = s.substring(0, index);
      strValue = s.substring(index + 1);
    } else {
      ret.equalSign = false;
      strKey = s;
      strValue = "";
    }

    // key, space1
    index = StringUtil.find_last_not_of(strKey, SPACES);
    if (index >= 0) {
      ret.space1 = strKey.substring(index + 1);
      ret.key = strKey.substring(0, index + 1);
    } else {
      ret.space1 = strKey;
      ret.key = "";
    }

    // space2, value
    index = StringUtil.find_first_not_of(strValue, " \t");
    if (index >= 0) {
      ret.space2 = strValue.substring(0, index);
      ret.value = strValue.substring(index);
    } else {
      ret.space2 = strValue;
      ret.value = null;
    }
    return ret;
  }
  public String draw(String title, Map<String, List<Double>> data, List<String> xLabels) {

    /*
        Scale values
    */
    Double maxValue = Double.MIN_VALUE;
    Double minValue = Double.MAX_VALUE;
    for (List<Double> doubles : data.values()) {
      for (Double d : doubles) {
        maxValue = Math.max(d, maxValue);
        minValue = Math.min(d, minValue);
      }
    }
    double k = 100.0 / maxValue;
    HashMap<String, List<Double>> scaled = new HashMap<>();
    for (Map.Entry<String, List<Double>> entry : data.entrySet()) {
      List<Double> value = new ArrayList<>();
      for (Double next : entry.getValue()) {
        value.add(next * k);
      }
      scaled.put(entry.getKey(), value);
    }
    data = scaled;

    Random rnd = new Random(42);

    // Defining lines
    ArrayList<Line> lines = new ArrayList<>();
    for (Map.Entry<String, List<Double>> entry : data.entrySet()) {
      Color color =
          Color.newColor(
              String.format("%02X%02X%02X", rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
      Line line = Plots.newLine(Data.newData(entry.getValue()), color, entry.getKey());
      line.setLineStyle(LineStyle.newLineStyle(3, 1, 0));
      line.addShapeMarkers(Shape.DIAMOND, color, 12);
      line.addShapeMarkers(Shape.DIAMOND, Color.WHITE, 8);
      lines.add(line);
    }

    // Defining chart.
    LineChart chart = GCharts.newLineChart(lines);
    chart.setSize(600, 450);
    chart.setTitle(title, WHITE, 14);
    int stepCount = 5;
    chart.setGrid(100 / stepCount, 100 / stepCount, 3, 3);

    // Defining axis info and styles

    // Make x axis
    AxisStyle axisStyle = AxisStyle.newAxisStyle(WHITE, 12, AxisTextAlignment.CENTER);
    AxisLabels xAxis = AxisLabelsFactory.newAxisLabels(xLabels);
    xAxis.setAxisStyle(axisStyle);

    // Calculate y axis labels
    List<String> yLabels = new ArrayList<>();
    for (int i = 0; i <= stepCount; i++) {
      yLabels.add(String.valueOf(maxValue / stepCount * i));
    }
    AxisLabels yAxis = AxisLabelsFactory.newAxisLabels(yLabels);
    yAxis.setAxisStyle(axisStyle);

    // Adding axis info to chart.
    chart.addXAxisLabels(xAxis);
    chart.addYAxisLabels(yAxis);

    // Defining background and chart fills.
    chart.setBackgroundFill(Fills.newSolidFill(Color.newColor("1F1D1D")));
    LinearGradientFill fill = Fills.newLinearGradientFill(0, Color.newColor("363433"), 100);
    fill.addColorAndOffset(Color.newColor("2E2B2A"), 0);
    chart.setAreaFill(fill);

    return chart.toURLString();
  }
  /** tests cat. This one has IDREFs. */
  public void testCat() throws Exception {
    Cat cat = new Cat();
    Circle face = new Circle();
    face.setRadius(20);
    cat.setFace(face);
    Triangle ear = new Triangle();
    ear.setBase(5);
    ear.setHeight(10);
    ear.setId("earId");
    cat.setEars(Arrays.asList(ear, ear));

    // The eyes are the same as the ears, but so it needs to be for this test.
    cat.setEyes(new Triangle[] {ear, ear});

    Line noseLine = new Line();
    noseLine.setId("noseId");
    Line mouthLine = new Line();
    mouthLine.setId("mouthLine");

    cat.setNose(noseLine);
    cat.setMouth(mouthLine);
    cat.setWhiskers(Arrays.asList(noseLine, mouthLine));

    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    ObjectMapper catMapper = provider.locateMapper(Cat.class, MediaType.APPLICATION_JSON_TYPE);
    ObjectMapper clientMapper = new ObjectMapper();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    catMapper.writeValue(out, cat);
    shapes.json.animals.Cat clientCat =
        clientMapper.readValue(
            new ByteArrayInputStream(out.toByteArray()), shapes.json.animals.Cat.class);

    shapes.json.Circle clientFace = clientCat.getFace();
    assertEquals(20, clientFace.getRadius());
    assertEquals(2, clientCat.getEars().size());
    shapes.json.Triangle[] clientEars =
        (shapes.json.Triangle[]) clientCat.getEars().toArray(new shapes.json.Triangle[2]);
    assertNotSame(
        "referential integrity should NOT have been preserved since Jackson doesn't support it yet",
        clientEars[0],
        clientEars[1]);
    assertEquals(5, clientEars[0].getBase());
    assertEquals(10, clientEars[0].getHeight());
    assertEquals("earId", clientEars[0].getId());
    assertEquals(5, clientEars[1].getBase());
    assertEquals(10, clientEars[1].getHeight());
    assertEquals("earId", clientEars[1].getId());

    shapes.json.Triangle[] clientEyes = clientCat.getEyes();
    assertEquals(2, clientEyes.length);
    assertNotSame(clientEyes[0], clientEyes[1]);
    assertEquals(5, clientEyes[0].getBase());
    assertEquals(10, clientEyes[0].getHeight());
    assertEquals("earId", clientEyes[0].getId());
    assertEquals(5, clientEyes[1].getBase());
    assertEquals(10, clientEyes[1].getHeight());
    assertEquals("earId", clientEyes[1].getId());
    assertFalse(
        "The ears should NOT be the same object as one of the eyes since Jackson doesn't support referential integrity.",
        clientEars[0] == clientEyes[0] || clientEars[0] == clientEyes[1]);

    shapes.json.Line clientNose = clientCat.getNose();
    assertEquals("noseId", clientNose.getId());
    shapes.json.Line clientMouth = clientCat.getMouth();
    assertEquals("mouthLine", clientMouth.getId());
    assertFalse(
        "The nose line should NOT also be one of the whiskers since Jackson doesn't support referential integrity.",
        clientCat.getWhiskers().contains(clientNose));
    assertFalse(
        "The mouth line should NOT also be one of the whiskers since Jackson doesn't support referential integrity.",
        clientCat.getWhiskers().contains(clientMouth));

    out = new ByteArrayOutputStream();
    clientMapper.writeValue(out, clientCat);
    cat = catMapper.readValue(new ByteArrayInputStream(out.toByteArray()), Cat.class);

    face = cat.getFace();
    assertEquals(20, face.getRadius());
    assertEquals(2, cat.getEars().size());
    Triangle[] ears = cat.getEars().toArray(new Triangle[2]);
    assertNotSame(
        "referential integrity should NOT have been preserved since Jackson doesn't support referential integrity.",
        ears[0],
        ears[1]);
    assertEquals(5, ears[0].getBase());
    assertEquals(10, ears[0].getHeight());
    assertEquals("earId", ears[0].getId());

    Triangle[] eyes = cat.getEyes();
    assertEquals(2, eyes.length);
    assertNotSame(eyes[0], eyes[1]);
    assertEquals(5, eyes[0].getBase());
    assertEquals(10, eyes[0].getHeight());
    assertEquals("earId", eyes[0].getId());
    assertEquals(5, eyes[1].getBase());
    assertEquals(10, eyes[1].getHeight());
    assertEquals("earId", eyes[1].getId());
    assertFalse(
        "The ears should NOT be the same object as one of the eyes since Jackson doesn't support referential integrity.",
        ears[0] == eyes[0] || ears[0] == eyes[1]);

    Line nose = cat.getNose();
    assertEquals("noseId", nose.getId());
    Line mouth = cat.getMouth();
    assertEquals("mouthLine", mouth.getId());
    assertFalse(
        "The nose line should also be one of the whiskers since Jackson doesn't support referential integrity.",
        cat.getWhiskers().contains(nose));
    assertFalse(
        "The mouth line should also be one of the whiskers since Jackson doesn't support referential integrity.",
        cat.getWhiskers().contains(mouth));
  }
Пример #11
0
  public void renderNotes(GLAutoDrawable gLDrawable, double dt) {
    // RENDER NOTES////////////////////////

    /*  OLD CODE TO CHECK/UPDATE TIME
    long songTime = song.getTime();
    long milliTime = System.currentTimeMillis();
    if(firstTime)
    {
    	time = songTime;
    	firstTime = false;
    }
    else
    {
    	if(songTime == oldSongTime)
    	{
    		updateTime += milliTime-oldTime;
    		System.out.println("update time: "+updateTime);

    	}
    	else
    	{
    		if (songTime == oldSongTime + updateTime)
    			System.out.println("WINWINWINWIWNWINWIWNWIN");
    		else
    			System.out.println("Difference: "+(songTime-oldSongTime - updateTime));


    		updateTime = 0;
    		System.out.println("New Time: "+time);
    	}
    	time = songTime + updateTime;
    }//end else

    	oldSongTime = songTime;
    	oldTime = milliTime;*/
    time = song.getTime();
    for (int i = lowestNoteToProcess; i < lines.size(); i++) {
      Line line = lines.get(i);
      if (line.getTime() - noteErrorDuration > time) break;
      if (line.getState() == 0) // not pressed
      {
        if (time > line.getTime() + noteErrorDuration) // missed line
        {
          // System.out.println("missed line");
          line.setState(3);
          score -= 1;
          lowestNoteToProcess++;
        }
      } // code below takes care of this
    } // end for

    // find closest line in bounds to be pressed
    // if a line exists
    // see if correct key combo was pressed
    // do the thing
    // else
    // play a bad line sound
    // if it doesnt exist
    // play a bad line sound
    Line closest = null;
    long closestDistance = 1000000;
    for (int i = lowestNoteToProcess; i < lines.size(); i++) {
      Line n = lines.get(i);
      if (n.getTime() - noteErrorDuration > time) break;
      if (n.getState()
          == 1) // user is holding down this line, so it is the only one that can be processed
      {
        closest = n;
        break;
      }
      if (Math.abs(time - n.getTime()) <= closestDistance
          && time >= n.getTime() - noteErrorDuration
          && time <= n.getTime() + noteErrorDuration) {
        closest = n;
        closestDistance = (long) Math.abs(time - n.getTime());
      }
    }
    if (closest != null) {
      if (closest.getState() == 0) // not pressed
      {
        boolean seq = true;
        for (int x = 0; x < 5; x++)
          if (key[x] != closest.getNotes()[x]) {
            seq = false;
            break;
          }
        if (seq) {
          // System.out.println("pressed button");
          closest.setState(2); // pressed button
          lowestNoteToProcess++;
        }
        score += 1;
      } else {
        // play bad line sound
      }
    }
    /*else if(closest.getState() == 1)
    { //holding and strummed, cant do that
    	closest.getState() = 2;
    	System.out.println("you interrupted the holding");
    	lowestNoteToProcess++;
    	//play bad line sound
    }*/
    // }
    else // (if closest == null)
    {
      // play bad line sound
    }

    // Part 2
    for (int i = lowestNoteToRender; i < lines.size(); i++) {
      Line line = lines.get(i);
      float posz =
          (line.getTime() + -targetPos / length * fretDuration - time)
              / fretDuration
              * length; // head
      if (posz > length) break; // not rendered yet
      float posz2 =
          (line.getTime() + -targetPos / length * fretDuration - time)
              / fretDuration
              * length; // tail
      if (posz2 <= 1) // will never be rendered again
      {
        lowestNoteToRender++;
        continue;
      }
      if (posz <= length)
        for (int x = 0; x < 5; x++) {
          if (!line.getNotes()[x]) continue;
          if (line.getState() == 2) continue; // pressed

          if (line.getState() == 3) // missed
          noteToDraw = new Note(127f, 127f, 127f);
          else noteToDraw = new Note(colors[x][0], colors[x][1], colors[x][2]);
          if (x < 4) noteToDraw.draw(gLDrawable, -3 + (1.5f * x), -4, -posz);
          else noteToDraw.drawBar(gLDrawable, -posz, false);
        }
    }
    // }//end if songIsPlaying
  }