Search in sources :

Example 1 with BlockPos

use of net.minecraft.util.BlockPos in project malmo by Microsoft.

the class ClassroomDecoratorImplementation method buildOnWorld.

@Override
public void buildOnWorld(MissionInit missionInit) throws DecoratorException {
    this.drawContext = new BlockDrawingHelper();
    if (this.buildingWidth == 0) {
        // We are using complexity so these need to be sampled from the Gaussian
        this.buildingWidth = Math.max((int) (rand.nextGaussian() * 2 + this.buildingComplexity * MAX_BUILDING_SIZE + MIN_ROOM_SIZE), MIN_ROOM_SIZE);
        this.buildingLength = Math.max((int) (rand.nextGaussian() * 2 + this.buildingComplexity * MAX_BUILDING_SIZE + MIN_ROOM_SIZE), MIN_ROOM_SIZE);
        this.buildingHeight = Math.max(Math.max(this.buildingWidth, this.buildingLength) * ROOM_HEIGHT / MIN_ROOM_SIZE, ROOM_HEIGHT);
    }
    // create the room grid
    ArrayList<Room> rooms = this.createRooms();
    // randomize the indices used to query different divisions.  This has the effect of making
    // the path to the goal random each time.
    this.shuffleIndices();
    // determine how long the path to the goal should be
    if (this.pathLength == 0) {
        this.pathLength = (int) ((1 - 0.25 * this.pathComplexity) * rooms.size()) - 1;
    } else {
        this.pathLength = Math.min(this.pathLength, rooms.size() - 1);
    }
    // find a path to the goal
    ArrayList<Divider> path = new ArrayList<Divider>();
    Room startRoom, goalRoom;
    if (this.pathLength > 0) {
        for (Room room : rooms) {
            for (Room markRoom : rooms) {
                markRoom.mark = false;
            }
            if (findPath(path, room, this.pathLength)) {
                break;
            }
        }
        if (path.size() < this.pathLength) {
            // error
            throw new DecoratorException("Unable to find path to goal");
        }
        startRoom = path.get(0).getIn();
        goalRoom = path.get(path.size() - 1).getOut();
        for (Divider divider : path) {
            divider.setHint(this.rand.nextDouble() < this.hintLikelihood);
        }
        // create all of the obstacles along the path
        createObstacles(path);
    } else {
        startRoom = goalRoom = rooms.get(0);
        startRoom.isComplete = true;
    }
    // find orphan rooms
    for (Room room : rooms) {
        if (room.isComplete) {
            continue;
        }
        for (Room markRoom : rooms) {
            markRoom.mark = false;
        }
        path.clear();
        if (findPath(path, room, rooms.size())) {
            // portion of the building back to the orphan room.
            for (Divider obstacle : path) {
                obstacle.reverse();
            }
            // create all of the obstacles along the path
            createObstacles(path);
        } else {
            throw new DecoratorException("Unable to join orphan room to goal path");
        }
    }
    // carve out the building
    World world = MinecraftServer.getServer().getEntityWorld();
    this.drawContext.beginDrawing(world);
    for (int x = START_X; x < START_X + this.buildingWidth; x++) {
        for (int y = START_Y; y < START_Y + this.buildingHeight; y++) {
            for (int z = START_Z; z < START_Z + this.buildingLength; z++) {
                world.setBlockToAir(new BlockPos(x, y, z));
            }
        }
    }
    // this should clear all of the torches and levers left over from last time.  It doesn't.
    drawContext.clearEntities(world, START_X - 1, START_Y - 1, START_Z - 1, START_X + this.buildingWidth, START_Y + this.buildingHeight, START_Z + this.buildingLength);
    // draw the rooms
    for (Room room : rooms) {
        room.draw(world, this.rand, this.palette);
    }
    // place goal
    setBlockState(world, new BlockPos(goalRoom.x + this.rand.nextInt(goalRoom.width - 4) + 2, goalRoom.y, goalRoom.z + goalRoom.length - 2), this.palette.goal);
    this.drawContext.endDrawing(world);
    // set the agent positions
    PosAndDirection p2 = new PosAndDirection();
    p2.setX(new BigDecimal(startRoom.x + this.rand.nextInt(goalRoom.width - 2) + 0.5));
    p2.setY(new BigDecimal(1 + startRoom.y));
    p2.setZ(new BigDecimal(startRoom.z + 0.5));
    // TODO - for the moment, force all players to being at the maze start point - but this needs to be optional.
    for (AgentSection as : missionInit.getMission().getAgentSection()) {
        p2.setPitch(as.getAgentStart().getPlacement().getPitch());
        p2.setYaw(as.getAgentStart().getPlacement().getYaw());
        as.getAgentStart().setPlacement(p2);
    }
}
Also used : BlockDrawingHelper(com.microsoft.Malmo.Utils.BlockDrawingHelper) PosAndDirection(com.microsoft.Malmo.Schemas.PosAndDirection) ArrayList(java.util.ArrayList) World(net.minecraft.world.World) BigDecimal(java.math.BigDecimal) AgentSection(com.microsoft.Malmo.Schemas.AgentSection) BlockPos(net.minecraft.util.BlockPos)

Example 2 with BlockPos

use of net.minecraft.util.BlockPos in project malmo by Microsoft.

the class DiscreteMovementCommandsImplementation method onExecute.

@Override
protected boolean onExecute(String verb, String parameter, MissionInit missionInit) {
    boolean handled = false;
    EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
    if (player != null) {
        int z = 0;
        int x = 0;
        int y = 0;
        DiscreteMovementCommand command = verbToCommand(verb);
        if (command == null)
            // Did not recognise this command.
            return false;
        switch(command) {
            case MOVENORTH:
            case JUMPNORTH:
                z = -1;
                break;
            case MOVESOUTH:
            case JUMPSOUTH:
                z = 1;
                break;
            case MOVEEAST:
            case JUMPEAST:
                x = 1;
                break;
            case MOVEWEST:
            case JUMPWEST:
                x = -1;
                break;
            case MOVE:
            case JUMPMOVE:
            case STRAFE:
            case JUMPSTRAFE:
                if (parameter != null && parameter.length() != 0) {
                    float velocity = Float.valueOf(parameter);
                    int offset = (velocity > 0) ? 1 : ((velocity < 0) ? -1 : 0);
                    int direction = getDirectionFromYaw(player.rotationYaw);
                    // For strafing, add one to direction:
                    if (command == DiscreteMovementCommand.STRAFE || command == DiscreteMovementCommand.JUMPSTRAFE)
                        direction = (direction + 1) % 4;
                    switch(direction) {
                        case // North
                        0:
                            z = offset;
                            break;
                        case // East
                        1:
                            x = -offset;
                            break;
                        case // South
                        2:
                            z = -offset;
                            break;
                        case // West
                        3:
                            x = offset;
                            break;
                    }
                    break;
                }
            case TURN:
                if (parameter != null && parameter.length() != 0) {
                    float yawDelta = Float.valueOf(parameter);
                    int direction = getDirectionFromYaw(player.rotationYaw);
                    direction += (yawDelta > 0) ? 1 : ((yawDelta < 0) ? -1 : 0);
                    direction = (direction + 4) % 4;
                    player.rotationYaw = direction * 90;
                    player.onUpdate();
                    // Send a message that the ContinuousMovementCommands can pick up on:
                    Event event = new CommandForWheeledRobotNavigationImplementation.ResetPitchAndYawEvent(true, player.rotationYaw, false, 0);
                    MinecraftForge.EVENT_BUS.post(event);
                    handled = true;
                }
                break;
            case LOOK:
                if (parameter != null && parameter.length() != 0) {
                    float pitchDelta = Float.valueOf(parameter);
                    player.rotationPitch += (pitchDelta < 0) ? -45 : ((pitchDelta > 0) ? 45 : 0);
                    player.onUpdate();
                    // Send a message that the ContinuousMovementCommands can pick up on:
                    Event event = new CommandForWheeledRobotNavigationImplementation.ResetPitchAndYawEvent(false, 0, true, player.rotationPitch);
                    MinecraftForge.EVENT_BUS.post(event);
                    handled = true;
                }
                break;
            case ATTACK:
                {
                    MovingObjectPosition mop = Minecraft.getMinecraft().objectMouseOver;
                    if (mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
                        BlockPos hitPos = mop.getBlockPos();
                        EnumFacing face = mop.sideHit;
                        IBlockState iblockstate = player.worldObj.getBlockState(hitPos);
                        Block block = iblockstate.getBlock();
                        if (block.getMaterial() != Material.air) {
                            MalmoMod.network.sendToServer(new AttackActionMessage(hitPos, face));
                            // Trigger a reward for collecting the block
                            java.util.List<ItemStack> items = block.getDrops(player.worldObj, hitPos, iblockstate, 0);
                            for (ItemStack item : items) {
                                RewardForCollectingItemImplementation.GainItemEvent event = new RewardForCollectingItemImplementation.GainItemEvent(item);
                                MinecraftForge.EVENT_BUS.post(event);
                            }
                        }
                    }
                    handled = true;
                    break;
                }
            case USE:
            case JUMPUSE:
                {
                    MovingObjectPosition mop = getObjectMouseOver(command);
                    if (mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
                        if (player.getCurrentEquippedItem() != null) {
                            ItemStack itemStack = player.getCurrentEquippedItem();
                            Block b = Block.getBlockFromItem(itemStack.getItem());
                            if (b != null) {
                                BlockPos pos = mop.getBlockPos().add(mop.sideHit.getDirectionVec());
                                // Can we place this block here?
                                AxisAlignedBB axisalignedbb = b.getCollisionBoundingBox(player.worldObj, pos, b.getDefaultState());
                                Entity exceptedEntity = (command == DiscreteMovementCommand.USE) ? null : player;
                                // (Not ideal, but needed by jump-use to allow the player to place a block where their feet would be.)
                                if (axisalignedbb == null || player.worldObj.checkNoEntityCollision(axisalignedbb, exceptedEntity)) {
                                    boolean standOnBlockPlaced = (command == DiscreteMovementCommand.JUMPUSE && mop.getBlockPos().equals(new BlockPos(player.posX, player.posY - 1, player.posZ)));
                                    MalmoMod.network.sendToServer(new UseActionMessage(mop.getBlockPos(), itemStack, mop.sideHit, standOnBlockPlaced));
                                }
                            }
                        }
                    }
                    handled = true;
                    break;
                }
            case JUMP:
                // Handled below.
                break;
        }
        // Handle jumping cases:
        if (command == DiscreteMovementCommand.JUMP || command == DiscreteMovementCommand.JUMPNORTH || command == DiscreteMovementCommand.JUMPEAST || command == DiscreteMovementCommand.JUMPSOUTH || command == DiscreteMovementCommand.JUMPWEST || command == DiscreteMovementCommand.JUMPMOVE || command == DiscreteMovementCommand.JUMPUSE || command == DiscreteMovementCommand.JUMPSTRAFE)
            y = 1;
        if (this.params.isAutoJump() && y == 0 && (z != 0 || x != 0)) {
            // Do we need to jump?
            if (!player.worldObj.getCollidingBoundingBoxes(player, player.getEntityBoundingBox().offset(x, 0, z)).isEmpty())
                y = 1;
        }
        if (z != 0 || x != 0 || y != 0) {
            // Attempt to move the entity:
            double oldX = player.posX;
            double oldZ = player.posZ;
            player.moveEntity(x, y, z);
            player.onUpdate();
            if (this.params.isAutoFall()) {
                // Did we step off a block? If so, attempt to fast-forward our fall.
                // Give up after this many attempts
                int bailCountdown = 256;
                // (This is needed because, for example, if the player is caught in a web, the downward movement will have no effect.)
                while (!player.onGround && !player.capabilities.isFlying && bailCountdown > 0) {
                    // Fast-forward downwards.
                    player.moveEntity(0, Math.floor(player.posY - 0.0000001) - player.posY, 0);
                    player.onUpdate();
                    bailCountdown--;
                }
            }
            // Now check where we ended up:
            double newX = player.posX;
            double newZ = player.posZ;
            // Are we still in the centre of a square, or did we get shunted?
            double offsetX = newX - Math.floor(newX);
            double offsetZ = newZ - Math.floor(newZ);
            if (Math.abs(offsetX - 0.5) + Math.abs(offsetZ - 0.5) > 0.01) {
                // We failed to move to the centre of the target square.
                // This might be because the target square was occupied, and we
                // were shunted back into our source square,
                // or it might be that the target square is occupied by something smaller
                // than one block (eg a fence post), and we're in the target square but
                // shunted off-centre.
                // Either way, we can't stay here, so move back to our original position.
                // Before we do that, fire off a message - this will give the TouchingBlockType handlers
                // a chance to react to the current position:
                DiscretePartialMoveEvent event = new DiscretePartialMoveEvent(player.posX, player.posY, player.posZ);
                MinecraftForge.EVENT_BUS.post(event);
                // Now adjust the player:
                player.moveEntity(oldX - newX, 0, oldZ - newZ);
                player.onUpdate();
            }
            // Now set the last tick pos values, to turn off inter-tick positional interpolation:
            player.lastTickPosX = player.posX;
            player.lastTickPosY = player.posY;
            player.lastTickPosZ = player.posZ;
            try {
                MalmoMod.getPropertiesForCurrentThread().put(MOVE_ATTEMPTED_KEY, true);
            } catch (Exception e) {
                // TODO - proper error reporting.
                System.out.println("Failed to access properties for the client thread after discrete movement - reward may be incorrect.");
            }
            handled = true;
        }
    }
    return handled;
}
Also used : AxisAlignedBB(net.minecraft.util.AxisAlignedBB) Entity(net.minecraft.entity.Entity) EnumFacing(net.minecraft.util.EnumFacing) DiscreteMovementCommand(com.microsoft.Malmo.Schemas.DiscreteMovementCommand) BlockPos(net.minecraft.util.BlockPos) IBlockState(net.minecraft.block.state.IBlockState) MovingObjectPosition(net.minecraft.util.MovingObjectPosition) PlayerInteractEvent(net.minecraftforge.event.entity.player.PlayerInteractEvent) Event(net.minecraftforge.fml.common.eventhandler.Event) BlockEvent(net.minecraftforge.event.world.BlockEvent) Block(net.minecraft.block.Block) EntityPlayerSP(net.minecraft.client.entity.EntityPlayerSP) ItemStack(net.minecraft.item.ItemStack)

Example 3 with BlockPos

use of net.minecraft.util.BlockPos in project malmo by Microsoft.

the class RewardForTouchingBlockTypeImplementation method calculateReward.

private void calculateReward(MultidimensionalReward reward) {
    // Determine what blocks we are touching.
    // This code is largely cribbed from Entity, where it is used to fire the Block.onEntityCollidedWithBlock methods.
    EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
    List<BlockPos> touchingBlocks = PositionHelper.getTouchingBlocks(player);
    for (BlockPos pos : touchingBlocks) {
        IBlockState iblockstate = player.worldObj.getBlockState(pos);
        for (BlockMatcher bm : this.matchers) {
            if (bm.applies(pos) && bm.matches(pos, iblockstate)) {
                float reward_value = bm.reward();
                float adjusted_reward = adjustAndDistributeReward(reward_value, this.params.getDimension(), bm.spec.getDistribution());
                reward.add(this.params.getDimension(), adjusted_reward);
            }
        }
    }
}
Also used : IBlockState(net.minecraft.block.state.IBlockState) BlockPos(net.minecraft.util.BlockPos) EntityPlayerSP(net.minecraft.client.entity.EntityPlayerSP)

Example 4 with BlockPos

use of net.minecraft.util.BlockPos in project malmo by Microsoft.

the class SnakeDecoratorImplementation method updatePath.

private void updatePath() {
    this.pendingBlock = true;
    this.timeSinceLastBuild = 0;
    // Update block position:
    this.buildX += ((this.buildDirection % 2) == 0) ? this.buildDirection - 1 : 0;
    this.buildZ += ((this.buildDirection % 2) == 1) ? this.buildDirection - 2 : 0;
    // We can add a gap, unless we've already added one, or we are going up:
    boolean addGap = (this.consecutiveGaps == 0 && this.stairs <= 0 && this.randomBuilder.nextFloat() < chanceOfGap);
    // Update the Y position:
    if (this.stairs > 0) {
        this.buildY++;
        this.stairs--;
    } else if (this.stairs < 0) {
        this.buildY--;
        this.stairs++;
    }
    // Clamp Y:
    this.buildY = (this.buildY < this.minYPos) ? this.minYPos : (this.buildY > this.maxYPos) ? this.maxYPos : this.buildY;
    // Add the block to our path:
    BlockPos bp = new BlockPos(this.buildX, this.buildY, this.buildZ);
    this.path.add(bp);
    if (!addGap) {
        this.consecutiveGaps = 0;
        // Update the deltas randomly:
        scrambleDirections();
    } else {
        this.consecutiveGaps++;
    }
}
Also used : BlockPos(net.minecraft.util.BlockPos)

Example 5 with BlockPos

use of net.minecraft.util.BlockPos in project malmo by Microsoft.

the class MovingTargetDecoratorImplementation method parseParameters.

@Override
public boolean parseParameters(Object params) {
    if (params == null || !(params instanceof MovingTargetDecorator))
        return false;
    this.targetParams = (MovingTargetDecorator) params;
    this.arenaBounds = this.targetParams.getArenaBounds();
    DrawBlockBasedObjectType targetBlock = this.targetParams.getBlockType();
    this.blockType = (targetBlock != null) ? new XMLBlockState(targetBlock.getType(), targetBlock.getColour(), targetBlock.getFace(), targetBlock.getVariant()) : null;
    Pos pos = this.targetParams.getStartPos();
    int xPos = pos.getX().intValue();
    int yPos = pos.getY().intValue();
    int zPos = pos.getZ().intValue();
    // Check start pos lies within arena:
    xPos = Math.min(this.arenaBounds.getMax().getX(), Math.max(this.arenaBounds.getMin().getX(), xPos));
    yPos = Math.min(this.arenaBounds.getMax().getY(), Math.max(this.arenaBounds.getMin().getY(), yPos));
    zPos = Math.min(this.arenaBounds.getMax().getZ(), Math.max(this.arenaBounds.getMin().getZ(), zPos));
    this.startPos = new BlockPos(xPos, yPos, zPos);
    if (this.targetParams.getUpdateSpeed() == null || this.targetParams.getUpdateSpeed().equals("turnbased")) {
        this.mustWaitTurn = true;
    } else {
        this.speedInTicks = Integer.parseInt(this.targetParams.getUpdateSpeed());
    }
    createRNG();
    return true;
}
Also used : BlockPos(net.minecraft.util.BlockPos) Pos(com.microsoft.Malmo.Schemas.Pos) DrawBlockBasedObjectType(com.microsoft.Malmo.Schemas.DrawBlockBasedObjectType) BlockPos(net.minecraft.util.BlockPos) MovingTargetDecorator(com.microsoft.Malmo.Schemas.MovingTargetDecorator) XMLBlockState(com.microsoft.Malmo.Utils.BlockDrawingHelper.XMLBlockState)

Aggregations

BlockPos (net.minecraft.util.BlockPos)30 IBlockState (net.minecraft.block.state.IBlockState)11 EntityPlayerSP (net.minecraft.client.entity.EntityPlayerSP)6 Entity (net.minecraft.entity.Entity)5 BlockDrawingHelper (com.microsoft.Malmo.Utils.BlockDrawingHelper)4 XMLBlockState (com.microsoft.Malmo.Utils.BlockDrawingHelper.XMLBlockState)4 ArrayList (java.util.ArrayList)4 ItemStack (net.minecraft.item.ItemStack)4 AxisAlignedBB (net.minecraft.util.AxisAlignedBB)3 EntityTypes (com.microsoft.Malmo.Schemas.EntityTypes)2 HashMap (java.util.HashMap)2 Block (net.minecraft.block.Block)2 EntityPlayer (net.minecraft.entity.player.EntityPlayer)2 MovingObjectPosition (net.minecraft.util.MovingObjectPosition)2 Vec3 (net.minecraft.util.Vec3)2 World (net.minecraft.world.World)2 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 JsonPrimitive (com.google.gson.JsonPrimitive)1