예제 #1
0
파일: Snake.java 프로젝트: szamani20/Snake
  private void play() {
    if (isReload) reloadGame();
    if (isEnd || isPause) return;

    addFeed();
    doesEatFeed();
    addRegime();
    doesEatRegime();
    crossBorder();

    head = blocks.peekFirst();

    Block newHead = new Block(head.getX() + dx[inputDirection], head.getY() + dy[inputDirection]);
    Rectangle headRect = new Rectangle(head.getX(), head.getY(), 10, 10);

    if (isEnd(newHead)) {
      isEnd = true;
      //            Image image = new Image(this.getClass().getResourceAsStream("/gameOver.png"));
      //            ImageView imageView = new ImageView(image);
      //            group.getChildren().add(imageView);
      //            scene.setOnKeyPressed(null);
      saveRecord();
      showRecord();
      return;
    } else {
      blocks.push(newHead);
      rectangles.push(headRect);

      blocks.pollLast();

      updateGui();
    }
  }
    @Test
    public void nemesisBlockIsVerifiable() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      Assert.assertThat(block.verify(), IsEqual.equalTo(true));
    }
    @Test
    public void generationHashConstantIsConsistentWithNemesisBlock() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      Assert.assertThat(
          block.getGenerationHash(), IsEqual.equalTo(NEMESIS_BLOCK_INFO.getGenerationHash()));
    }
    @Test
    public void nemesisTransactionsAreVerifiable() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      for (final Transaction transaction : block.getTransactions()) {
        Assert.assertThat(transaction.verify(), IsEqual.equalTo(true));
      }
    }
    @Test
    public void addressConstantIsConsistentWithNemesisBlock() {
      // Arrange:
      final Block block = this.loadNemesisBlock();
      final Address blockAddress = block.getSigner().getAddress();

      // Assert:
      Assert.assertThat(blockAddress, IsEqual.equalTo(NEMESIS_BLOCK_INFO.getAddress()));
      Assert.assertThat(
          blockAddress.getPublicKey(),
          IsEqual.equalTo(NEMESIS_BLOCK_INFO.getAddress().getPublicKey()));
      Assert.assertThat(blockAddress.getPublicKey(), IsNull.notNullValue());
    }
    @Test
    public void nemesisTransactionsHaveCorrectFees() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Assert:
      for (final Transaction transaction : block.getTransactions()) {
        final Amount expectedFee =
            TransactionTypes.TRANSFER == transaction.getType()
                ? Amount.ZERO
                : NemGlobals.getTransactionFeeCalculator().calculateMinimumFee(transaction);
        Assert.assertThat(transaction.getFee(), IsEqual.equalTo(expectedFee));
      }
    }
    @Test
    public void amountConstantIsConsistentWithNemesisBlock() {
      // Act:
      Amount totalAmount = Amount.ZERO;
      final Block block = this.loadNemesisBlock();
      for (final Transaction transaction : block.getTransactions()) {
        if (transaction instanceof TransferTransaction) {
          totalAmount = totalAmount.add(((TransferTransaction) transaction).getAmount());
        }
      }

      // Assert:
      Assert.assertThat(totalAmount, IsEqual.equalTo(NEMESIS_BLOCK_INFO.getAmount()));
    }
예제 #8
0
 private void initNewStore(NetworkParameters params) throws Exception {
   byte[] header;
   header = HEADER_MAGIC.getBytes("US-ASCII");
   buffer.put(header);
   // Insert the genesis block.
   lock.lock();
   try {
     setRingCursor(buffer, FILE_PROLOGUE_BYTES);
   } finally {
     lock.unlock();
   }
   Block genesis = params.getGenesisBlock().cloneAsHeader();
   StoredBlock storedGenesis = new StoredBlock(genesis, genesis.getWork(), 0);
   put(storedGenesis);
   setChainHead(storedGenesis);
 }
예제 #9
0
 /**
  * Creates a new StoredBlock, calculating the additional fields by adding to the values in this
  * block.
  */
 public StoredBlock build(Block block) throws VerificationException {
   // Stored blocks track total work done in this chain, because the canonical chain is the one
   // that represents
   // the largest amount of work done not the tallest.
   BigInteger chainWork = this.chainWork.add(block.getWork());
   int height = this.height + 1;
   return new StoredBlock(block, chainWork, height);
 }
    @Test
    public void nemesisAddressesAreValid() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Act:
      final Set<Address> allAddresses =
          block
              .getTransactions()
              .stream()
              .flatMap(t -> t.getAccounts().stream().map(Account::getAddress))
              .collect(Collectors.toSet());

      // Assert:
      for (final Address address : allAddresses) {
        Assert.assertThat(address.toString(), address.isValid(), IsEqual.equalTo(true));
      }
    }
    @Test
    public void nemesisTransactionSignersHavePublicKeys() {
      // Arrange:
      final Block block = this.loadNemesisBlock();

      // Act:
      final Set<Address> signerAddresses =
          block
              .getTransactions()
              .stream()
              .map(t -> t.getSigner().getAddress())
              .collect(Collectors.toSet());

      // Assert:
      for (final Address address : signerAddresses) {
        Assert.assertThat(address.getPublicKey(), IsNull.notNullValue());
      }
    }
예제 #12
0
 @Override
 public boolean equals(Object o) {
   if (this == o) return true;
   if (o == null || getClass() != o.getClass()) return false;
   StoredBlock other = (StoredBlock) o;
   return header.equals(other.header)
       && chainWork.equals(other.chainWork)
       && height == other.height;
 }
예제 #13
0
파일: Snake.java 프로젝트: szamani20/Snake
  private void doesEatFeed() {
    if (isEnd) return;

    if (Math.abs(blocks.peekFirst().getX() - feedRectangle.getX()) < 10
        && Math.abs(blocks.peekFirst().getY() - feedRectangle.getY()) < 10) {
      feedRectangle.setX(1200);
      isFeed = false;
      ++feedCounter2;
      ++score;
      scoreLabel.setText(String.valueOf(score));

      head = blocks.peekFirst();
      Block newHead = new Block(head.getX() + dx[inputDirection], head.getY() + dy[inputDirection]);
      Rectangle headRect = new Rectangle(head.getX(), head.getY(), 10, 10);
      blocks.push(newHead);
      rectangles.push(headRect);
    }
  }
예제 #14
0
파일: Snake.java 프로젝트: szamani20/Snake
  private void reloadGame() {
    if (!isReload) return;

    score = 0;
    isReload = false;
    isEnd = false;
    feedCounter1 = 0;
    feedCounter2 = 0;

    List<Rectangle> rectangleList = new ArrayList<>(rectangles);
    for (Rectangle r : rectangleList) group.getChildren().remove(r);

    regimeRectangle.setX(-20);

    Deque<Block> blocksTemp = new ArrayDeque<>();
    Deque<Rectangle> rectanglesTemp = new ArrayDeque<>();

    head = new Block(100, 150);
    tale = new Block(90, 150);

    if (inputDirection != 3) {
      blocksTemp.push(tale);
      blocksTemp.push(head);

      rectanglesTemp.push(new Rectangle(tale.getX(), tale.getY(), 10, 10));
      rectanglesTemp.push(new Rectangle(head.getX(), head.getY(), 10, 10));
    } else {
      blocksTemp.push(head);
      blocksTemp.push(tale);

      rectanglesTemp.push(new Rectangle(head.getX(), head.getY(), 10, 10));
      rectanglesTemp.push(new Rectangle(tale.getX(), tale.getY(), 10, 10));
    }

    blocks = blocksTemp;
    rectangles = rectanglesTemp;

    group.getChildren().add(rectangles.getFirst());
    group.getChildren().add(rectangles.getLast());

    timer.cancel();
    timer = null;
    timer = new Timer();

    timer.schedule(
        new TimerTask() {
          @Override
          public void run() {
            Platform.runLater(() -> play());
          }
        },
        1,
        100);
  }
  // ******@Uses: This is a small visitor created to extract variable name and
  // count****************//
  // *********************** from a given try block ********************************************//
  // ***********************************************************************************************//
  public void VariableVisitor_try(String content) {
    ASTParser metparse = ASTParser.newParser(AST.JLS3);
    metparse.setSource(content.toCharArray());
    metparse.setKind(ASTParser.K_STATEMENTS);
    Block block = (Block) metparse.createAST(null);

    block.accept(
        new ASTVisitor() {
          public boolean visit(VariableDeclarationFragment var) {
            // debug("met.var", var.getName().getFullyQualifiedName());
            variables_in_try = variables_in_try + " " + var.getName().getFullyQualifiedName();
            variables_count_try = variables_count_try + 1;

            System.out.println("Vriables in try:" + variables_in_try);
            // interupt();
            return true;
          }
        });
  }
예제 #16
0
 ///////////////////////////////////////////
 // Writable
 ///////////////////////////////////////////
 public void write(DataOutput out) throws IOException {
   blockToken.write(out);
   out.writeBoolean(corrupt);
   out.writeLong(offset);
   b.write(out);
   out.writeInt(locs.length);
   for (int i = 0; i < locs.length; i++) {
     locs[i].write(out);
   }
 }
예제 #17
0
 private void renderMenuBlock(Block block, float f, RenderBlocks renderblocks) {
   int i = block.getRenderType();
   renderblocks.setRenderBoundsFromBlock(block);
   Tessellator tessellator = Tessellator.instance;
   if (i == 0) {
     block.setBlockBoundsForItemRender();
     GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
     float f1 = 0.5F;
     float f2 = 1.0F;
     float f3 = 0.8F;
     float f4 = 0.6F;
     tessellator.startDrawingQuads();
     tessellator.setColorRGBA_F(f2, f2, f2, f);
     renderblocks.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getBlockTextureFromSide(0));
     tessellator.setColorRGBA_F(f1, f1, f1, f);
     renderblocks.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getBlockTextureFromSide(1));
     tessellator.setColorRGBA_F(f3, f3, f3, f);
     renderblocks.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getBlockTextureFromSide(2));
     renderblocks.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getBlockTextureFromSide(3));
     tessellator.setColorRGBA_F(f4, f4, f4, f);
     renderblocks.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getBlockTextureFromSide(4));
     renderblocks.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getBlockTextureFromSide(5));
     tessellator.draw();
     GL11.glTranslatef(0.5F, 0.5F, 0.5F);
   }
 }
예제 #18
0
 public void readFields(DataInput in) throws IOException {
   blockToken.readFields(in);
   this.corrupt = in.readBoolean();
   offset = in.readLong();
   this.b = new Block();
   b.readFields(in);
   int count = in.readInt();
   this.locs = new DatanodeInfo[count];
   for (int i = 0; i < locs.length; i++) {
     locs[i] = new DatanodeInfo();
     locs[i].readFields(in);
   }
 }
예제 #19
0
파일: Snake.java 프로젝트: szamani20/Snake
  private void crossBorder() {
    if (isEnd) return;

    List<Block> blockTemp = new ArrayList<>(blocks);
    switch (inputDirection) {
      case 0:
        for (int i = 0; i < blockTemp.size(); i++)
          if (blockTemp.get(i).getY() >= 460) {
            Block temp = blockTemp.get(i);
            temp.setY(0);
            blockTemp.set(i, temp);
          }
        break;

      case 1:
        for (int i = 0; i < blockTemp.size(); i++)
          if (blockTemp.get(i).getX() >= 490) {
            Block temp = blockTemp.get(i);
            temp.setX(0);
            blockTemp.set(i, temp);
          }
        break;

      case 2:
        for (int i = 0; i < blockTemp.size(); i++)
          if (blockTemp.get(i).getY() <= 0) {
            Block temp = blockTemp.get(i);
            temp.setY(450);
            blockTemp.set(i, temp);
          }
        break;

      case 3:
        for (int i = 0; i < blockTemp.size(); i++)
          if (blockTemp.get(i).getX() <= 0) {
            Block temp = blockTemp.get(i);
            temp.setX(480);
            blockTemp.set(i, temp);
          }
        break;
    }

    Deque<Block> blocksTemp = new ArrayDeque<>();

    for (int i = blockTemp.size() - 1; i >= 0; i--) blocksTemp.push(blockTemp.get(i));

    blocks = blocksTemp;
  }
예제 #20
0
  private Block readCodeBlock(int numInputs) throws IOException {
    Block block = new Block(numInputs);
    int nCodes = input.read_uv();
    HashMap<Integer, Code.Label> labels = new HashMap<Integer, Code.Label>();

    for (int i = 0; i != nCodes; ++i) {
      Code code = readCode(i, labels);
      block.append(code);
    }

    // NOTE: we must go up to nCodes+1 because of the possibility of a label
    // occurring after the very last bytecode instruction.
    for (int i = 0, j = 0; i != nCodes + 1; ++i, ++j) {
      Code.Label label = labels.get(i);
      if (label != null) {
        block.insert(j++, label);
      }
    }

    input.pad_u8(); // necessary

    return block;
  }
예제 #21
0
 private void createNewStore(NetworkParameters params, File file) throws BlockStoreException {
   // Create a new block store if the file wasn't found or anything went wrong whilst reading.
   blockMap.clear();
   try {
     stream = new FileOutputStream(file, false); // Do not append, create fresh.
     stream.write(1); // Version.
   } catch (IOException e1) {
     // We could not load a block store nor could we create a new one!
     throw new BlockStoreException(e1);
   }
   try {
     // Set up the genesis block. When we start out fresh, it is by definition the top of the
     // chain.
     Block genesis = params.genesisBlock.cloneAsHeader();
     StoredBlock storedGenesis = new StoredBlock(genesis, genesis.getWork(), 0);
     this.chainHead = storedGenesis.getHeader().getHash();
     stream.write(this.chainHead.getBytes());
     put(storedGenesis);
   } catch (VerificationException e1) {
     throw new RuntimeException(e1); // Cannot happen.
   } catch (IOException e) {
     throw new BlockStoreException(e);
   }
 }
예제 #22
0
파일: Board.java 프로젝트: ankeshs/hex
  void place(int mx, int my) {
    if (drme) {
      drme = false;
      return;
    }

    int n = data.a.length;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        if (((mx - data.a[i][j].x) * (mx - data.a[i][j].x)
                    + (my - data.a[i][j].y) * (my - data.a[i][j].y)
                < bst.scale * bst.scale * .75)
            && data.a[i][j].getState() == 0) {
          if (count == 1 && gst.swap) {
            int ch =
                JOptionPane.showConfirmDialog(
                    this, "Swap moves?", "Swap", JOptionPane.YES_NO_OPTION);
            if (ch == JOptionPane.YES_OPTION) {
              lmv.setState(cst);
              switch (cst) {
                case 1:
                  data.a[i][j].setState(2);
                  break;
                case 2:
                  data.a[i][j].setState(1);
                  break;
              }
              repaint(
                  (int) (lmv.x - 0.8 * bst.scale),
                  (int) (lmv.y - 0.8 * bst.scale),
                  (int) (1.6 * bst.scale),
                  (int) (1.6 * bst.scale));
              if (AIMethods.gameOver(this, lmv.i, lmv.j, count)) {
                newGame();
              }
              if (gst.ai != null) gst.ai.updateAI(lmv.i, lmv.j, lmv.getState(), count);

            } else data.a[i][j].setState(cst);

          } else data.a[i][j].setState(cst);
          lmv = data.a[i][j];
          repaint(
              (int) (data.a[i][j].x - 0.8 * bst.scale),
              (int) (data.a[i][j].y - 0.8 * bst.scale),
              (int) (1.6 * bst.scale),
              (int) (1.6 * bst.scale));
          switch (cst) {
            case 1:
              cst = 2;
              break;
            case 2:
              cst = 1;
              break;
          }

          if (AIMethods.gameOver(this, lmv.i, lmv.j, count)) {
            System.out.println("Game Over");
            firstrun = true;
            String win = "";
            if (lmv.getState() == Block.RED_BEAD) {
              switch (gst.theme) {
                case 0:
                  win = "Red";
                  break;
                case 1:
                  win = "Black";
                  break;
                case 2:
                  win = "Gold";
                  break;
              }

            } else {
              switch (gst.theme) {
                case 0:
                  win = "Blue";
                  break;
                case 1:
                  win = "Green";
                  break;
                case 2:
                  win = "Silver";
                  break;
              }
            }
            if (gst.audio) AePlayWave.play(AePlayWave.END);
            JOptionPane.showMessageDialog(
                this, win + " wins", "Game Over", JOptionPane.INFORMATION_MESSAGE);
            newGame();
            return;
          }

          if (gst.audio) {
            if (gst.ai == null) AePlayWave.play(AePlayWave.PLACE);
            else if (userMove) AePlayWave.play(AePlayWave.AIMOVE);
          }
          count++;
          if (gst.ai != null && userMove) {
            userMove = false;
            gst.ai.nextMove(lmv.i, lmv.j, lmv.getState(), count);
          } else userMove = true;
          return;
        }
      }
    }
    if (gst.audio) AePlayWave.play(AePlayWave.BLOCK);
  }
예제 #23
0
 PerformResult perform() throws WorldEditorException {
   if (dontRollback.contains(replaced)) return PerformResult.BLACKLISTED;
   final Block block = loc.getBlock();
   if (replaced == 0 && block.getTypeId() == 0) return PerformResult.NO_ACTION;
   final BlockState state = block.getState();
   if (!world.isChunkLoaded(block.getChunk())) world.loadChunk(block.getChunk());
   if (type == replaced) {
     if (type == 0) {
       if (!block.setTypeId(0))
         throw new WorldEditorException(block.getTypeId(), 0, block.getLocation());
     } else if (ca != null && (type == 23 || type == 54 || type == 61 || type == 62)) {
       int leftover = 0;
       try {
         leftover =
             modifyContainer(
                 state, new ItemStack(ca.itemType, -ca.itemAmount, (short) 0, ca.itemData));
         if (leftover > 0)
           for (final BlockFace face :
               new BlockFace[] {
                 BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST
               })
             if (block.getRelative(face).getTypeId() == 54)
               leftover =
                   modifyContainer(
                       block.getRelative(face).getState(),
                       new ItemStack(
                           ca.itemType,
                           ca.itemAmount < 0 ? leftover : -leftover,
                           (short) 0,
                           ca.itemData));
       } catch (final Exception ex) {
         throw new WorldEditorException(ex.getMessage(), block.getLocation());
       }
       if (!state.update())
         throw new WorldEditorException(
             "Failed to update inventory of " + materialName(block.getTypeId()),
             block.getLocation());
       if (leftover > 0 && ca.itemAmount < 0)
         throw new WorldEditorException(
             "Not enough space left in " + materialName(block.getTypeId()), block.getLocation());
     } else return PerformResult.NO_ACTION;
     return PerformResult.SUCCESS;
   }
   if (!(equalTypes(block.getTypeId(), type) || replaceAnyway.contains(block.getTypeId())))
     return PerformResult.NO_ACTION;
   if (state instanceof InventoryHolder) {
     ((InventoryHolder) state).getInventory().clear();
     state.update();
   }
   if (block.getTypeId() == replaced) {
     if (block.getData() != (type == 0 ? data : (byte) 0))
       block.setData(type == 0 ? data : (byte) 0, true);
     else return PerformResult.NO_ACTION;
   } else if (!block.setTypeIdAndData(replaced, type == 0 ? data : (byte) 0, true))
     throw new WorldEditorException(block.getTypeId(), replaced, block.getLocation());
   final int curtype = block.getTypeId();
   if (signtext != null && (curtype == 63 || curtype == 68)) {
     final Sign sign = (Sign) block.getState();
     final String[] lines = signtext.split("\0", 4);
     if (lines.length < 4) return PerformResult.NO_ACTION;
     for (int i = 0; i < 4; i++) sign.setLine(i, lines[i]);
     if (!sign.update())
       throw new WorldEditorException(
           "Failed to update signtext of " + materialName(block.getTypeId()),
           block.getLocation());
   } else if (curtype == 26) {
     final Bed bed = (Bed) block.getState().getData();
     final Block secBlock =
         bed.isHeadOfBed()
             ? block.getRelative(bed.getFacing().getOppositeFace())
             : block.getRelative(bed.getFacing());
     if (secBlock.getTypeId() == 0
         && !secBlock.setTypeIdAndData(26, (byte) (bed.getData() | 8), true))
       throw new WorldEditorException(secBlock.getTypeId(), 26, secBlock.getLocation());
   } else if (curtype == 64 || curtype == 71) {
     final byte blockData = block.getData();
     final Block secBlock =
         (blockData & 8) == 8
             ? block.getRelative(BlockFace.DOWN)
             : block.getRelative(BlockFace.UP);
     if (secBlock.getTypeId() == 0
         && !secBlock.setTypeIdAndData(curtype, (byte) (blockData | 8), true))
       throw new WorldEditorException(secBlock.getTypeId(), curtype, secBlock.getLocation());
   } else if ((curtype == 29 || curtype == 33) && (block.getData() & 8) > 0) {
     final PistonBaseMaterial piston = (PistonBaseMaterial) block.getState().getData();
     final Block secBlock = block.getRelative(piston.getFacing());
     if (secBlock.getTypeId() == 0
         && !secBlock.setTypeIdAndData(
             34,
             curtype == 29 ? (byte) (block.getData() | 8) : (byte) (block.getData() & ~8),
             true))
       throw new WorldEditorException(secBlock.getTypeId(), 34, secBlock.getLocation());
   } else if (curtype == 34) {
     final PistonExtensionMaterial piston = (PistonExtensionMaterial) block.getState().getData();
     final Block secBlock = block.getRelative(piston.getFacing().getOppositeFace());
     if (secBlock.getTypeId() == 0
         && !secBlock.setTypeIdAndData(
             piston.isSticky() ? 29 : 33, (byte) (block.getData() | 8), true))
       throw new WorldEditorException(
           secBlock.getTypeId(), piston.isSticky() ? 29 : 33, secBlock.getLocation());
   } else if (curtype == 18 && (block.getData() & 8) > 0)
     block.setData((byte) (block.getData() & 0xF7));
   return PerformResult.SUCCESS;
 }
예제 #24
0
파일: Snake.java 프로젝트: szamani20/Snake
  private boolean isEnd(Block newHead) {
    List<Block> blockTemp = new ArrayList<>(blocks);

    for (int i = 0; i < blockTemp.size(); i++)
      if (blockTemp.get(i).getX() == newHead.getX() && blockTemp.get(i).getY() == newHead.getY())
        return true;

    if (newHead.getX() >= obstacle1.getX()
        && newHead.getX() <= obstacle1.getX() + 150
        && ((newHead.getY() >= obstacle1.getY() && newHead.getY() <= obstacle1.getY() + 5)
            || (newHead.getY() <= obstacle1.getY() && newHead.getY() >= obstacle1.getY() - 5)))
      return true;

    if (newHead.getY() >= obstacle2.getY()
        && newHead.getY() <= obstacle2.getY() + 150
        && ((newHead.getX() >= obstacle2.getX() && newHead.getX() <= obstacle2.getX() + 5)
            || (newHead.getX() <= obstacle2.getX() && newHead.getX() >= obstacle2.getX() - 5)))
      return true;

    return false;
  }
  public void methodVisitor(String content) {
    ASTParser metparse = ASTParser.newParser(AST.JLS3);
    metparse.setSource(content.toCharArray());
    metparse.setKind(ASTParser.K_STATEMENTS);
    Block block = (Block) metparse.createAST(null);

    block.accept(
        new ASTVisitor() {
          public boolean visit(VariableDeclarationFragment var) {
            // debug("met.var", var.getName().getFullyQualifiedName());
            // System.out.println("dec");
            return true;
          }

          public boolean visit(SimpleName node) {
            // System.out.println(" Simple Node="+node.toString());
            // System.out.println("Node");
            return true;
          }

          public boolean visit(ForStatement myfor) {
            // System.out.println("myfor="+myfor.toString());
            // System.out.println("for");
            return true;
          }

          public boolean visit(SwitchStatement myswitch) {
            // System.out.println("myswitch="+myswitch.toString());
            return true;
          }

          public boolean visit(DoStatement mydo) {
            // System.out.println("mydo="+mydo.toString());
            return true;
          }

          public boolean visit(WhileStatement mywhile) {
            // System.out.println("mywhile="+mywhile.toString());
            return true;
          }

          public boolean visit(IfStatement myif) {

            return true;
          }

          public boolean visit(TryStatement mytry) {
            reset_try_flags();
            util3_met utm = new util3_met();
            log_level_interface tli = new log_level_interface();
            method_name_and_count mnc_try = new method_name_and_count();
            operator_and_operator_count oaoc_try = new operator_and_operator_count();

            // object for method
            method_name_and_count mnc_till_try = new method_name_and_count();
            operator_and_operator_count oaoc_till_try = new operator_and_operator_count();
            log_level_interface tli_till_try = new log_level_interface();

            try_id++;
            catch_id = 0;

            // Contextualfeaturess
            is_method_have_param = utm.check_method_parameter(method_parameter);
            method_param_as_string_original = method_parameter.toString();
            method_param_as_string_original =
                utm.replace_quotes_string(method_param_as_string_original);
            method_param_as_string = method_param_as_string_original;
            method_param_as_string = utm.clean_method_params(method_param_as_string);
            method_param_count = utm.get_param_count(method_parameter);

            method_param_type = utm.get_method_param_type(method_parameter);
            method_param_type = utm.clean_method_params(method_param_type);

            method_param_name = utm.get_method_param_name(method_parameter);
            method_param_name = utm.clean_method_params(method_param_name);

            String try_con = mytry.getBody().toString();
            /*try_con = try_con.replace("\"", "\\\"");
            try_con= try_con.replace("\'", " ");
            try_con = try_con.replace("\\\\", " ");*/

            /*try_con = try_con.replace("\"", " ");
            try_con= try_con.replace("\'", " ");
            try_con = try_con.replace("\\", " "); */
            System.out.println("Content of Try Block=" + try_con.toString());

            //	try_loc = utm.get_try_loc_count(try_con);// old method @not comment
            try_loc = utm.get_new_try_sloc(try_con);

            tli = utm.find_and_set_logging_level(try_con, tli);
            is_try_logged = tli.logged;
            try_log_count = tli.log_count;
            try_log_levels = tli.log_levels_combined;
            is_return_in_try = utm.check_return(try_con);
            is_thread_sleep_try = utm.check_thread_sleep(try_con);
            throw_throws_try = utm.check_thorw_throws(try_con);
            if_in_try = utm.check_if(try_con);
            if_count_in_try = utm.get_if_count(try_con);
            is_assert_try = utm.check_assert(try_con);

            mnc_try = utm.get_method_call_name(try_con, mnc_try);
            method_call_names_try = mnc_try.method_names;
            method_call_count_try = mnc_try.method_count;

            oaoc_try = utm.get_operators_and_count(try_con, oaoc_try);
            operators_in_try = oaoc_try.operator;
            operators_count_try = oaoc_try.operator_count;

            // @Uses: This function will use to count the variable names in the try block
            // *** This will set following varibels in the block  //
            // *** Variables_in_try =
            // **  variables_count_try =           //
            VariableVisitor_try(try_con);

            // @******Features between method and try************@//

            // interupt();
            int try_pos = mytry.getStartPosition();

            String method_try_between_con = method_content.substring(0, try_pos);
            method_try_between_con = method_try_between_con.trim();
            method_try_between_con = utm.balance_closing_braces(method_try_between_con);

            // System.out.println("method  con:"+ method_content);

            // System.out.println("method between try con:"+ method_try_between_con);

            String modified_con_for_method_call_ext =
                utm.get_modified_con_for_method_cal_extraction(method_content, try_pos);
            mnc_till_try = utm.get_method_call_name(modified_con_for_method_call_ext, mnc_till_try);
            method_call_names_till_try = mnc_till_try.method_names;
            method_call_count_till_try = mnc_till_try.method_count;

            oaoc_till_try = utm.get_operators_and_count(method_try_between_con, oaoc_till_try);
            operators_till_try = oaoc_till_try.operator;
            operators_count_till_try = oaoc_till_try.operator_count;

            // @Uses: This function will use to count the variable names in the given block between
            // method and try
            // *** This will set following varibels in the block  //
            // *** Variables_till_try =
            // **  variables_count_till_try =           //
            VariableVisitor_method_try_between_con(method_try_between_con);

            loc_till_try = utm.get_loc(method_try_between_con);
            tli_till_try = utm.find_and_set_logging_level(method_try_between_con, tli_till_try);
            is_till_try_logged = tli_till_try.logged;
            till_try_log_count = tli_till_try.log_count;
            till_try_log_levels = tli_till_try.log_levels_combined;
            is_return_till_try = utm.check_return(method_try_between_con);
            throw_throws_till_try = utm.check_thorw_throws(method_try_between_con);
            if_in_till_try = utm.check_if(method_try_between_con);
            if_count_in_till_try = utm.get_if_count(method_try_between_con);
            is_assert_till_try = utm.check_assert(method_try_between_con);

            String previous_catch_as_string = "";
            List all_catches = mytry.catchClauses();
            Iterator itr = all_catches.iterator();

            int count = 0;

            while (itr.hasNext()) {

              log_level_interface catch_li = new log_level_interface();
              catch_id++;
              reset_catch_flags();
              CatchClause mycatch = (CatchClause) all_catches.get(count);

              String catch_exp = mycatch.getException().getType().toString();
              catch_exp = catch_exp.replace("\"", "\\\"");
              catch_exp = catch_exp.replace("\'", " ");
              catch_exp = catch_exp.replace("\\\\", " ");
              catch_exp = utm.find_final_catch_exp(catch_exp);

              String catch_exp_with_obj = mycatch.getException().toString();

              String catch_con = mycatch.getBody().toString();
              // catch_con = catch_con.replace("\"", "\\\"");
              // catch_con = catch_con.replace("\'", "\\\'");
              // catch_con = catch_con.replace("\\\\", " ");

              System.out.println("---------Set Flags----------------------");
              catch_li = utm.find_and_set_logging_level(catch_con, catch_li);
              is_catch_logged = catch_li.logged;
              catch_log_count = catch_li.log_count;
              catch_log_levels = catch_li.log_levels_combined;
              have_previous_catches = utm.contains_previous_catches(count);
              previous_catches_logged =
                  utm.are_previous_catches_logged(previous_catch_as_string, count);
              previous_catches_log_count = utm.get_log_count(previous_catch_as_string);
              is_return_in_catch = utm.check_return(catch_con);
              catch_depth = utm.get_catch_depth(count);
              is_catch_object_ignore = utm.check_ignore(catch_exp_with_obj);
              is_interrupted_exception = utm.check_interrupted_exception(catch_exp);
              is_throwable_exception = utm.check_throwable_exception(catch_exp);
              throw_throws_catch = utm.check_thorw_throws(catch_con);
              is_assert_catch = utm.check_assert(catch_con);

              System.out.println("Method Name=" + method_name);
              System.out.println("Package Name=" + package_name);
              System.out.println("File Path=" + temp_file_path);
              System.out.println("Catch Exception=" + catch_exp);

              write_in_db(
                  try_id,
                  catch_id,
                  try_con,
                  catch_con,
                  method_try_between_con,
                  catch_exp.toString(),
                  previous_catch_as_string,
                  temp_file_path,
                  package_name,
                  class_name,
                  method_name,
                  try_loc,
                  is_try_logged,
                  try_log_count,
                  try_log_levels,
                  is_catch_logged,
                  catch_log_count,
                  catch_log_levels,
                  have_previous_catches,
                  previous_catches_logged,
                  is_return_in_try,
                  is_return_in_catch,
                  is_catch_object_ignore,
                  is_interrupted_exception,
                  is_thread_sleep_try,
                  throw_throws_try,
                  throw_throws_catch,
                  if_in_try,
                  if_count_in_try,
                  is_assert_try,
                  is_assert_catch,
                  previous_catches_log_count,
                  catch_depth,
                  is_method_have_param,
                  method_param_as_string_original,
                  method_param_as_string,
                  method_param_type,
                  method_param_name,
                  method_param_count,
                  method_call_names_try,
                  method_call_count_try,
                  operators_in_try,
                  operators_count_try,
                  variables_in_try,
                  variables_count_try,
                  method_call_names_till_try,
                  method_call_count_till_try,
                  operators_till_try,
                  operators_count_till_try,
                  variables_till_try,
                  variables_count_till_try,
                  loc_till_try,
                  is_till_try_logged,
                  till_try_log_count,
                  till_try_log_levels,
                  is_return_till_try,
                  throw_throws_till_try,
                  if_in_till_try,
                  if_count_in_till_try,
                  is_assert_till_try);

              write_in_file(
                  catch_con,
                  catch_exp.toLowerCase(),
                  try_con,
                  previous_catch_as_string,
                  method_content,
                  catch_log_count,
                  method_param_as_string);

              // not perfect
              String catch_con_with_exp = mycatch.toString();
              catch_con_with_exp = catch_con_with_exp.replace("\"", "\\\\");
              catch_con_with_exp = catch_con_with_exp.replace("\'", " ");
              catch_con_with_exp = catch_con_with_exp.replace("\\\\", " ");
              previous_catch_as_string = previous_catch_as_string + "\n" + catch_con_with_exp;

              System.out.println(
                  "=========================================================================================================================");
              count++;
              itr.next();
            }

            return true;
          }

          public boolean visit(CatchClause mycatch) {
            String catch_train_con = "";
            return true;
          }
        });
  }
예제 #26
0
 @Override
 public int hashCode() {
   // A better hashCode is possible, but this works for now.
   return header.hashCode() ^ chainWork.hashCode() ^ height;
 }
예제 #27
0
 private void load(File file) throws IOException, BlockStoreException {
   log.info("Reading block store from {}", file);
   InputStream input = null;
   try {
     input = new BufferedInputStream(new FileInputStream(file));
     // Read a version byte.
     int version = input.read();
     if (version == -1) {
       // No such file or the file was empty.
       throw new FileNotFoundException(file.getName() + " does not exist or is empty");
     }
     if (version != 1) {
       throw new BlockStoreException("Bad version number: " + version);
     }
     // Chain head pointer is the first thing in the file.
     byte[] chainHeadHash = new byte[32];
     if (input.read(chainHeadHash) < chainHeadHash.length)
       throw new BlockStoreException("Truncated block store: cannot read chain head hash");
     this.chainHead = new Sha256Hash(chainHeadHash);
     log.info("Read chain head from disk: {}", this.chainHead);
     long now = System.currentTimeMillis();
     // Rest of file is raw block headers.
     byte[] headerBytes = new byte[Block.HEADER_SIZE];
     try {
       while (true) {
         // Read a block from disk.
         if (input.read(headerBytes) < 80) {
           // End of file.
           break;
         }
         // Parse it.
         Block b = new Block(params, headerBytes);
         // Look up the previous block it connects to.
         StoredBlock prev = get(b.getPrevBlockHash());
         StoredBlock s;
         if (prev == null) {
           // First block in the stored chain has to be treated specially.
           if (b.equals(params.genesisBlock)) {
             s =
                 new StoredBlock(
                     params.genesisBlock.cloneAsHeader(), params.genesisBlock.getWork(), 0);
           } else {
             throw new BlockStoreException(
                 "Could not connect "
                     + b.getHash().toString()
                     + " to "
                     + b.getPrevBlockHash().toString());
           }
         } else {
           // Don't try to verify the genesis block to avoid upsetting the unit tests.
           b.verifyHeader();
           // Calculate its height and total chain work.
           s = prev.build(b);
         }
         // Save in memory.
         blockMap.put(b.getHash(), s);
       }
     } catch (ProtocolException e) {
       // Corrupted file.
       throw new BlockStoreException(e);
     } catch (VerificationException e) {
       // Should not be able to happen unless the file contains bad blocks.
       throw new BlockStoreException(e);
     }
     long elapsed = System.currentTimeMillis() - now;
     log.info("Block chain read complete in {}ms", elapsed);
   } finally {
     if (input != null) input.close();
   }
 }
예제 #28
0
 public long getBlockSize() {
   return b.getNumBytes();
 }
예제 #29
0
파일: Snake.java 프로젝트: szamani20/Snake
  public Snake(String playerName, String inputDirection, Scene scene, Group group) {
    this.playerName = playerName;
    this.scene = scene;
    this.group = group;

    switch (inputDirection) {
      case "s":
        this.inputDirection = 0;
        break;

      case "d":
        this.inputDirection = 1;
        break;

      case "w":
        this.inputDirection = 2;
        break;

      case "a":
        this.inputDirection = 3;
        break;
    }

    directionsMapping = new HashMap<>();
    directionsMapping.put("S", 0);
    directionsMapping.put("D", 1);
    directionsMapping.put("W", 2);
    directionsMapping.put("A", 3);

    blocks = new ArrayDeque<>();
    rectangles = new ArrayDeque<>();

    head = new Block(100, 150);
    tale = new Block(90, 150);

    if (this.inputDirection != 3) {
      blocks.push(tale);
      blocks.push(head);

      rectangles.push(new Rectangle(tale.getX(), tale.getY(), 10, 10));
      rectangles.push(new Rectangle(head.getX(), head.getY(), 10, 10));
    } else {
      blocks.push(head);
      blocks.push(tale);

      rectangles.push(new Rectangle(head.getX(), head.getY(), 10, 10));
      rectangles.push(new Rectangle(tale.getX(), tale.getY(), 10, 10));
    }

    random = new Random(System.currentTimeMillis());

    isFeed = false;
    isRegime = false;

    scoreLabel = new Label(String.valueOf(score));
    scoreLabel.setLayoutX(240);
    scoreLabel.setLayoutY(0);

    group.getChildren().add(scoreLabel);

    feedRectangle = new Rectangle(10, 10);
    feedRectangle.setFill(Color.RED);
    feedRectangle.setX(-20);
    group.getChildren().add(feedRectangle);

    regimeRectangle = new Rectangle(10, 10);
    regimeRectangle.setFill(Color.GREEN);
    regimeRectangle.setX(-20);
    group.getChildren().add(regimeRectangle);

    obstacle1 = new Rectangle(150, 10);
    obstacle1.setFill(Color.BLUE);
    obstacle1.setY(-20);
    group.getChildren().add(obstacle1);

    obstacle2 = new Rectangle(10, 150);
    obstacle2.setFill(Color.BLUE);
    obstacle2.setX(-20);
    group.getChildren().add(obstacle2);

    setBestPlayer();
    setBoardListener();
    addFeed();

    timer = new Timer();
    timer.schedule(
        new TimerTask() {
          @Override
          public void run() {
            Platform.runLater(() -> play());
          }
        },
        1,
        100);
  }
예제 #30
0
  /** Called when run from the command line. The train module will run (mostly) individually. */
  public static void main(String[] args) {
    try {
      isSolo = true;

      // Get the number of trains.
      if (args.length != 1) {
        System.out.println("Invalid number of arguments.");
        System.exit(1);
      }
      soloNumTrains = Integer.parseInt(args[0], 10);
      if ((soloNumTrains < 1) || (soloNumTrains > 9)) {
        System.out.println(
            "Invalid argument. The number of trains must be greater than 0 and less than 10.");
        System.exit(1);
      }

      // Create the test block loop.
      Block bYard =
          new Block(
              0, "A", "I", 0.0, 0.0, 5.0, true, false, true, false, false, "", false, false, false);
      Block b01 =
          new Block(
              1, "B", "II", 500.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b02 =
          new Block(
              2, "C", "II", 500.0, -22.2, 1.0, true, false, false, false, false, "", false, false,
              false);
      Block b03 =
          new Block(
              3, "D", "II", 50.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b04 =
          new Block(
              4, "E", "II", 500.0, 11.1, 30.0, true, true, false, false, false, "", false, false,
              false);
      Block b05 =
          new Block(
              5, "F", "III", 50.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b06 =
          new Block(
              6, "G", "III", 100.0, 0.0, 5.0, true, false, false, true, false, "Alpha", false,
              false, false);
      Block b07 =
          new Block(
              7, "H", "III", 500.0, -11.1, 30.0, true, false, false, false, false, "", false, false,
              false);
      Block b08 =
          new Block(
              8, "I", "III", 50.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b09 =
          new Block(
              9, "J", "IV", 500.0, 22.2, 1.0, true, false, false, false, false, "", false, false,
              false);
      Block b10 =
          new Block(
              10, "K", "IV", 50.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b11 =
          new Block(
              11, "L", "IV", 100.0, 0.0, 5.0, true, false, false, true, false, "Beta", false, false,
              false);
      Block b12 =
          new Block(
              12, "M", "IV", 50.0, 11.1, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b13 =
          new Block(
              13, "N", "V", 50.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b14 =
          new Block(
              14, "O", "V", 50.0, -11.1, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b15 =
          new Block(
              15, "P", "V", 50.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);
      Block b16 =
          new Block(
              16, "Q", "V", 100.0, 0.0, 5.0, true, false, false, true, false, "Gamma", false, false,
              false);
      Block b17 =
          new Block(
              17, "R", "V", 50.0, 0.0, 15.0, true, false, false, false, false, "", false, false,
              false);

      bYard.connect(b17, b01);
      b01.connect(bYard, b02);
      b02.connect(b01, b03);
      b03.connect(b02, b04);
      b04.connect(b03, b05);
      b05.connect(b04, b06);
      b06.connect(b05, b07);
      b07.connect(b08, b06);
      b08.connect(b09, b07);
      b09.connect(b10, b08);
      b10.connect(b11, b09);
      b11.connect(b12, b10);
      b12.connect(b11, b13);
      b13.connect(b14, b12);
      b14.connect(b13, b15);
      b15.connect(b16, b14);
      b16.connect(b15, b17);
      b17.connect(bYard, b16);

      ArrayList<Block> route = new ArrayList<Block>();
      route.add(bYard);
      route.add(b01);
      route.add(b02);
      route.add(b03);
      route.add(b04);
      route.add(b05);
      route.add(b06);
      route.add(b07);
      route.add(b08);
      route.add(b09);
      route.add(b10);
      route.add(b11);
      route.add(b12);
      route.add(b13);
      route.add(b14);
      route.add(b15);
      route.add(b16);
      route.add(b17);
      route.add(bYard);
      route.add(b01);
      route.add(b02);
      route.add(b03);
      route.add(b04);
      route.add(b05);
      route.add(b06);
      route.add(b07);
      route.add(b08);
      route.add(b09);
      route.add(b10);
      route.add(b11);
      route.add(b12);
      route.add(b13);
      route.add(b14);
      route.add(b15);
      route.add(b16);
      route.add(b17);
      route.add(bYard);

      /*
       * Create the trains.
       * The first will depart at 8:00 AM, the second at 8:30 AM, the third at 9:00 AM, etc.
       * The first will depart at 8:00 AM, the second at 8:15 AM, the third at 8:30 AM, etc.
       * All will have break time set to 4 hours after their departure times.
       */
      trainList = new ArrayList<Train>();
      idArray = new String[soloNumTrains];
      for (int i = 0; i < soloNumTrains; i++) {
        trainList.add(
            new Train(
                i + 1,
                "T" + (i + 1),
                "Test",
                (8 * 60 * 60 + i * 15 * 60) % (24 * 60 * 60),
                route,
                new Engineer(
                    true, false, 0.0, (8 * 60 * 60 + i * 15 * 60 + 5 * 60) % (24 * 60 * 60)),
                bYard));
        idArray[i] = new String("T" + (i + 1));
      }

      // Create the UI.
      TrainModelUI tnmUI = new TrainModelUI();
      tnmUI.setTrainList(trainList);

      // Setup the timer.
      soloTime = 7 * 60 * 60 + 59 * 60 + 55;
      soloDate = new Date(93, 2, 2, 7, 59, 55);
      ActionListener taskPerformer =
          new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
              timeTick(soloDate, soloDelta);
            }
          };
      new javax.swing.Timer(20, taskPerformer).start();

      // Disable all "Toggle" buttons that are associated with a manual entry.
      btnToggleManRecPower.setEnabled(false);
      btnToggleManDesSpdLmt.setEnabled(false);
      btnToggleManLights.setEnabled(false);
      btnToggleManDoors.setEnabled(false);
      btnToggleManTarTemperature.setEnabled(false);

      // Make it so only manual values are used.
      for (int i = 0; i < soloNumTrains; i++) {
        Train t = trainList.get(i);
        t.issetManualPower = true;
        t.issetManualSpeedLimit = true;
        t.issetLightsOnUseManual = true;
        t.issetDoorsOpenUseManual = true;
        t.issetTargetTemperatureManual = true;
      }

      btnPauseResume.setEnabled(true);
      tnmUI.setSelectedId(trainList.get(0).id);
      tnmUI.setIsPaused(tnmUI.getIsPaused());
      tnmUI.setIsVisible(true);
    } catch (Exception e) {
      e.printStackTrace(System.err);
      JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
    }
  }