ModPE Script Templates
- useItem Template (Hexdro)
- Custom Button Template (Byteandahalf)
- procCmd Template (Arjay07)
- File Writer and Reader Template (PEMapModder)
- Define Mob Template (PEMapModder)
- in Array (PEMapModder)
This is a simple script, which spawns a custom mob, if you tap anywhere with a stick! Feel free to use the code in any of your mods, and customize it all you want.
function useItem (x, y, z,itemId, blockId, side)//useItem Code goes here
{
if(itemId == 280)//If the item used is a stick
{
var custom = Level.spawnMob(x,y+1,z,11,"mob/char.png"); //spawns mob, variable "custom", and uses the skin char
Entity.setRenderType(custom,3); //changes the rendertype of the mob custom to a player
clientMessage("You have now Spawned a Custom Mob! Your code worked!"); //clientmessage sent if item is a stick
}
}
This is a tutorial for adding GUI (Custom Buttons) Into Minecraft Pocket Edition, through the use of ModPE Scripts. You need the Block Launcher 1.5.2 Update, Remember that this code uses Java.
var buttonWindow = null; //A window we haven't yet made
function newLevel() { //As soon as the world loads
var activity = com.mojang.minecraftpe.MainActivity.currentMainActivity.get();
//A variable we'll use later to add the button to the current MCPE activity
activity.runOnUiThread(new java.lang.Runnable({ run: function() {
//This will allow our button to run on the current UI thread of MCPE
try { //Try to create our button
buttonWindow = new android.widget.PopupWindow();
//Make our variable a usable window
var layout = new android.widget.RelativeLayout(activity);
//A layout to put into our window
var button = new android.widget.Button(activity);
//A button to put in our layout
button.setText("Press Me!");
//Write some text upon our button
button.setOnClickListener(new android.view.View.OnClickListener({
//When we press our button
onClick: function(viewarg) { //This lets our button run something
//The function() comes from activity.runOnUiThread()
Level.explode(Player.getX(), Player.getY(), Player.getZ(), 3.0);
clientMessage("This is our button!");
}
}));
layout.addView(button);//Add our button to our layout
buttonWindow.setContentView(layout);//Add our layout to our window
buttonWindow.setWidth(android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonWindow.setHeight(android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
//Make our window the same size as the button within
buttonWindow.setBackgroundDrawable(new
android.graphics.drawable.ColorDrawable(android.graphics.Color.TRANSPARENT));
//The outline of our button's(The window) color
buttonWindow.showAtLocation(activity.getWindow().getDecorView(), android.view.Gravity.RIGHT | android.view.Gravity.BOTTOM, 0, 0);
//The location of our button on the screen, BOTTOM RIGHT
//The 0, 0 is the margin size, use this to push it around along those locations
}catch(problem){
print("Button could not be displayed: " + problem); //Print our error if we failed to make the button
}
}}));
}
function leaveGame() { //Get rid of it when we leave the world
var activity = com.mojang.minecraftpe.MainActivity.currentMainActivity.get();
activity.runOnUiThread(new java.lang.Runnable({ run: function() {
if(buttonWindow != null) { //If our window still exists
buttonWindow.dismiss(); //Remove it from the screen
buttonwindow = null; //Reset it
}
}}));
}
This template allows you to add commands to ModPE. Simply change the myCommand variable to your custom command string! Have fun adding your own commands!
function procCmd(command) {
var cmd = command.split(" ");
var myCommand = "command"; //Change the string to whatever you want! :D
if(cmd[0] == myCommand) {
//Your code here!
}
}
Creates or reads a file. You may use it without any credits.
function saveFile (directory, filename) {
try {
directory = android.os.Environment.getExternalStorageDirectory ().getPath () + "/games/com.mojang/minecraftworlds" + getWorldDir () + "/" + directory; // The file should be saved into the world directory.
var newFile = new java.io.File (directory,filename);
var directory = new java.io.File (directory);
var success = directory.mkdirs (); // creates the directory if not already created
if (!success){ // if not succeeded
throw new java.io.IOException("Directory "+directory+ "cannot be created"); // throws an IOException. new java.io.IOException(String) has a string parameter as a message.
}
/*
newFile.delete();
Add the above if you want to replace the file.
*/
newFile.createNewFile (); // creates a blank new file
var outWrite = new java.io.OutputStreamWriter (new java.io.FileOutputStream (newFile)); // creates the output writer
outWrite.append ("Your content here");
outWrite.close(); // closes the writer; not necessary to close, but better do it
return false; // tells that it succeeds; not necessary to catch, but better do it
}
catch(thrown){ // catches the error in the try block
return thrown.toString(); // returns a human-readable description of the error. The most common one is java.io.IOException that there is no such file
}
}
function readFile (directory, filename, wantBytes) { // wantBytes: true or false
try{
directory = android.os.Environment.getExternalStorageDirectory ().getPath () + "/games/com.mojang/minecraftworlds" + getWorldDir () + "/" + directory;
var inFile = new java.io.File(directory,filename);
if (!inFile.isFile()) return "notfile"; // check if it is a file
var inStream = new java.io.FileReader (inFile);
if (wantBytes) {
inStream.read (bytes); // stores the contents into bytes
var bytes = new Array();
return bytes;
}
var inBuffer = new java.io.BufferedReader (inStream);
var line = "",var returner = "";
while ((line = inBuffer.readLine ()) != null) { // read http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()
returner = returner + line + java.lang.System.getProperty ("line.seperator");
}
return returner;
}
catch(error){
return error.toString();
}
}
This template defines a new mob that spawns every CYCLE_MAX (constant field) = 2 zombies are spawned (deletes one of the zombies), has an initial health of INIT_HEALTH (constant field defined at the beginning of the script) = 100 half-hearts, rendered with the shape of a entityId RENDER_TYPE (constant field) = 33, has the actions of entityId SPAWN_TYPE (cosntant field) = 32, has a texture with file path FILE_PATH (constant field), and drops loots of ids in array DROP_LOOT (constant field) = [267,280] upon death.
/*final*/var INIT_HEALTH=100,FILE_PATH="mobs/newMob.png",DROP_LOOT=[[267,Math.ceil(Math.random()*100),1],[280,0,Math.ceil(Math.random()*4)]],CYCLE_MAX=2,SPAWN_TYPE=32,RENDER_TYPE=33,MSG="A divine CreeperZombie died!";//inits the fields ***** idk if there is final in javascript. Not necessary though
var cycle=0;//inits the zombie cycle
var creeperZombies=[];//inits the creeperZombie memory
function entityAddedHook(e){
if(Entity.getEntityTypeId(e)!=32)return;//only call if it is a zombie spawned
cycle++;//adds 1 to the cycle
if(cycle==CYCLE_MAX)cycle=0;//makes it be in cycle
if(cycle!=0)return;//only call the following if CYCLE_MAX zombies are spawned
var x=Entity.getX(e),y=Entity.getY(e),z=Entity.getZ(e);//record the axes
Entity.setPosition(e,x,0,z);//throw to the void (avoid dropItem)
//e.remove() can also be used
var newMob=Level.spawnMob(x,y,z,SPAWN_TYPE);//spawns the new creeperZombie
Entity.setRenderType(newMob,RENDER_TYPE);//sets the render type of the zobmie to creeper
Entity.setHealth(newMob,INIT_HEALTH);
creeperZombies[creeperZombies.length]=newMob;//adds the new creeperZombie to the end of the array creeperZombies
}
function deathHook(murderer,victim){
var key=inArray(creeperZombies,victim);
if(key.length>1)clientMessage("Tell your app developer that \n there is a bug! \n Tell him/her that \n inArray(creeperZombies,victim) returns multiple values!");//if there are no bugs, there should be one integer returned only
if(key==-1))return;//only call the following when victim is a creeperzombie
preventDefault();
creeperZombies[key]="NaN!";//take victim from creeperZombies array to avoid this function to be called again when the next line runs (by replacing the instance with NaN, representing "Not a Number", and the exclaimation mark added to avoid the value being considered as false or 0 or null etc.)
var x=Entity.getX(victim),y=Entity.getY(victim),z=Entity.getZ(victim);//records the axes
Entity.setPosition(victim,x,0,z);//throw into the void. (my favourite method of removing an entity)
for(var i=0;i<DROP_LOOT.length;i++){
Level.dropItem(x,y,z,1,DROP_LOOT[i][0],DROP_LOOT[i][2],DROP_LOOT[i][1]);
}
if(MSG!=""){
clientMessage(MSG);
}
}
function inArray(array,datum){...}//code below
Tests
Add this to the end of the above script to add the function inArray(), which tests whether the datum datum
is in the array array
.
Returns the sequence(s) of the datum appearance(s) in the array as a new array, or [-1]
if not found. (not null
due to report from arjay_07 that 0
and null
are sometimes mixed up and causes bugs
function inArray(array,datum){
var noResult=[-1];//inits the noResult returner
var result=[];//inits the result array
for(var i=0;i<array.length;i++){
if(array[i]!=datum)continue;//tests if array[i] is an instance of datum (THIS instance of IS NOT EQUAL TO instanceof!!)
result[result.length]=i;//adds this instance of datum at the end of array result[]
}
if(result==[])return noResult;//if there are no instances return -1
return result;//else return the result. else is not used because if result==[] the function is already ended by the token "return"
}