Created
February 23, 2017 22:09
-
-
Save bug-assassin/2748d0605dede4ef4e6a9d96037e9888 to your computer and use it in GitHub Desktop.
StackMachine implementation using this tutorial: http://gameprogrammingpatterns.com/bytecode.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
/* Based on http://gameprogrammingpatterns.com/bytecode.html */ | |
public class StackMachine | |
{ | |
public final int INST_LITERAL = 0; | |
public final int SET_HEALTH = 1; | |
public final int INST_GET_HEALTH = 2; | |
private static final int INST_ADD = 3; | |
public Stack<Integer> stack; | |
/* | |
LITERAL 0 [0] # Wizard index | |
LITERAL 0 [0, 0] # Wizard index | |
GET_HEALTH [0, 45] # getHealth() | |
LITERAL 5 [0, 45, 5] # Add bonus health amount | |
ADD [0, 50] # Add bonus health (5) to health | |
SET_HEALTH [] # Set health to result | |
*/ | |
public int[] instructions = { INST_LITERAL, 0, INST_LITERAL, 0, INST_GET_HEALTH, INST_LITERAL, 5, INST_ADD, SET_HEALTH}; | |
private int pointer; | |
public void run() | |
{ | |
stack = new Stack(); | |
pointer = -1; | |
while (pointer < instructions.length - 1) | |
{ | |
handleInstruction(instructions[++pointer]); | |
} | |
} | |
private void handleInstruction(int command) | |
{ | |
switch (command) | |
{ | |
case INST_LITERAL: | |
int value = instructions[++pointer]; | |
stack.push(value); | |
break; | |
case INST_GET_HEALTH: | |
{ | |
int wizard = stack.pop(); | |
stack.push(getHealth(wizard)); | |
break; | |
} | |
case SET_HEALTH: | |
int health = stack.pop(); | |
int wizard = stack.pop(); | |
setHealth(wizard, health); | |
break; | |
case INST_ADD: | |
int b = stack.pop(); | |
int a = stack.pop(); | |
stack.push(a + b); | |
break; | |
} | |
} | |
private Integer getHealth(int wizard) { | |
return 45; | |
} | |
private void setHealth(int wizard, int health) | |
{ | |
System.out.println("Wizard " + wizard + " health set to " + health); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment