public void onResult(QuestionAdResult questionAdResult) {
if (questionAdResult.wasCorrect()) {
// Additional Exp +5
// Additional HP +5
Hero.instance.earnExp(5);
Hero.instance.earnHP(5);
//
} else {
// Stuff
}
}
So I'm building a game and it has 2 methods.
Hero.instance.earnExp(5);
Hero.instance.earnHP(5);
I can uncomment either one for whichever specific action, but I'd like the actions to be random so it does either or, instead of having to comment one out. How would I go about it?
import java.util.Random;
public void onResult(QuestionAdResult questionAdResult) {
Random random = new Random();
int expOrHealth = random.nextInt(2);
if (questionAdResult.wasCorrect()) {
if (expOrHealth == 0)
{
// Additional Exp +5
}
if (expOrHealth == 1)
{
// Additional HP +5
}
Hero.instance.earnExp(5);
Hero.instance.earnHP(5);
//
} else {
// Stuff
}
}
Related
I am working on my first java project, one that simulates the behaviour of a neutrophil catching a bacterium (So random/semirandom particle behaviour). At the beginning of this program I have several variables (such as the radii of the organisms, etc) and right now they are fixed to the value I hardcoded in there. I want to create a user interface so that before the program starts, a screen pops up in which you can type in the values you want to use, and it uses those to run to program. Now I have used a swing script to create such a window and that looks a bit like this:
Now I'm wondering how I could implement it such that I can take the values used in those text boxes and assign them to my variables in my program.
This is the program I am referring to:
package nanocourse;
import java.awt.Color;
import nano.*;
import java.util.Random;
import prescreen.PreScreen;
public class Exercise3_final {
public Exercise3_final() {
int xSize = 1000;
int ySize = 800;
Canvas myScreen = new Canvas(xSize, ySize);
Pen myPen = new Pen(myScreen);
Random random = new Random();
int frame=0; //how many frames have passed since start program
//properties bacterium
int xPosBacterium=random.nextInt(xSize); //random starting position of bacterium
int yPosBacterium=random.nextInt(ySize);
int K=1000; //how many points used to draw bacterium
double [] xValueBacterium = new double[K]; //
double [] yValueBacterium = new double[K];
double bacteriumRadiusInput=20;
double bacteriumRadius=bacteriumRadiusInput; //radius of bacterium
boolean bacteriumAlive=true;
//properties biomolecules
int amountBio=30000;
boolean [] bioExist = new boolean[amountBio];
int [] xPosBio = new int [amountBio];
int [] yPosBio = new int [amountBio];
int [] dXBio = new int [amountBio];
int [] dYBio = new int [amountBio];
int [] lifetimeBio = new int [amountBio];
double chanceDegrade=0.1; //chance that a biomolecule gets degraded per frame
double chanceSynthesize=100; //chance that a biomolecule gets synthesized per frame
for(int i=0;i<amountBio;i++)
{
bioExist[i]=false; //setting existing state to false
}
//properties Neutrophil
int xPosNeutrophil=random.nextInt(xSize);
int yPosNeutrophil=random.nextInt(ySize);
int L=1000;
double [] xValueNeutrophil= new double[L];
double [] yValueNeutrophil= new double[L];
double neutrophilRadius=40;
double xVector, yVector, xNormVector,yNormVector,magnitude,xSumVector,ySumVector;
double aggressiveness=1;
while(bacteriumAlive==true) //while program is running
{
frame++;
//1. Simulating a moving Bacterium
int dXBacterium=random.nextInt(11)-5; //random motion
int dYBacterium=random.nextInt(11)-5;
xPosBacterium=xPosBacterium+dXBacterium;
yPosBacterium=yPosBacterium+dYBacterium;
if(xPosBacterium<(bacteriumRadius/2+2*myPen.getSize())) //boundaries bacterium,accounting for size bacterium
{
xPosBacterium=(int)bacteriumRadius/2+2*myPen.getSize();
}
else if(xPosBacterium>xSize - (bacteriumRadius/2+2*myPen.getSize()))
{
xPosBacterium=xSize - ((int)bacteriumRadius/2+2*myPen.getSize());
}
else if(yPosBacterium<(bacteriumRadius/2+2*myPen.getSize()))
{
yPosBacterium=((int)bacteriumRadius/2+2*myPen.getSize());
}
else if(yPosBacterium>ySize - (bacteriumRadius/2+2*myPen.getSize()))
{
yPosBacterium=ySize - ((int)bacteriumRadius/2+2*myPen.getSize());
}
//2. Simulating synthesis and secretion of biomolecules by the bacterium.
for(int i=0;i<amountBio;i++)
{
double synthesizeNumber=Math.random()*100;
if(synthesizeNumber<chanceSynthesize && i==frame)
{
bioExist[frame]=true; //make the biomolecules exist
}
if(bioExist[i]==true && frame!=1) //if biomolecule exist apply motion
{
dXBio[i]=random.nextInt(41)-20;
dYBio[i]=random.nextInt(41)-20;
xPosBio[i]=xPosBio[i]+dXBio[i];
yPosBio[i]=yPosBio[i]+dYBio[i];
}
else //if biomolecule doesn't exist, make position equal bacterium position
{
xPosBio[i]=xPosBacterium;
yPosBio[i]=yPosBacterium;
}
if(xPosBio[i]>xSize) //boundaries biomolecules
{
xPosBio[i]=xSize;
}
if(xPosBio[i]<0)
{
xPosBio[i]=0;
}
if(yPosBio[i]>ySize)
{
yPosBio[i]=ySize;
}
if(yPosBio[i]<0)
{
yPosBio[i]=0;
}
if(bioExist[i]==true)
{
lifetimeBio[i]++;
double degradationNumber=Math.random()*100;
if(degradationNumber<chanceDegrade)
{
bioExist[i]=false;
}
}
if(bioExist[i]==true && lifetimeBio[i]<=100) //if biomolecule lives shorter than 100 frames==>green
{
myPen.setColor(Color.GREEN); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && (lifetimeBio[i]>100 && lifetimeBio[i]<=500)) //if biomolecule lives 101-500 frames==>green
{
myPen.setColor(Color.yellow); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && (lifetimeBio[i]>500 && lifetimeBio[i]<=1000)) //if biomolecule lives 501-1000 frames==>orange
{
myPen.setColor(Color.ORANGE); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && (lifetimeBio[i]>1000 && lifetimeBio[i]<=1500)) //if biomolecule lives 1001-1500 frames==>red
{
myPen.setColor(Color.RED); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true && lifetimeBio[i]>1500) //if biomolecule lives 2001+ frames==>magenta
{
myPen.setColor(Color.magenta); //drawing biomolecules
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
}
if(bioExist[i]==true)
{
myPen.draw(xPosBio[i],yPosBio[i]);
}
if(Math.sqrt(Math.pow(Math.abs(xPosBio[i]-xPosNeutrophil),2)+Math.pow(Math.abs(yPosBio[i]-yPosNeutrophil), 2))<neutrophilRadius)
{
bioExist[i]=false; //degrade if inside neutrophil
}
}
if(bacteriumAlive==true)
{
for(int i = 0; i <K ; i++) //defining circle, drawing points, placed here because it needs to be on top
{
xValueBacterium[i] = bacteriumRadius*Math.cos(2*Math.PI*i/K);
yValueBacterium[i] = bacteriumRadius*Math.sin(2*Math.PI*i/K);
myPen.setColor(Color.red);
myPen.setShape(Shape.CIRCLE);
myPen.setSize(5);
myPen.draw((int)xValueBacterium[i]+xPosBacterium,(int)yValueBacterium[i]+yPosBacterium);
}
}
//5. Simulating the neutrophil eating the bacteriun
xSumVector=0;
ySumVector=0;
for(int i=0;i<amountBio;i++)
{
if(Math.abs(xPosBio[i]-xPosNeutrophil)<(30+neutrophilRadius) && Math.abs(yPosBio[i]-yPosNeutrophil)<(30+neutrophilRadius) && bioExist[i]==true)
{
xVector=xPosBio[i]-xPosNeutrophil;
yVector=yPosBio[i]-yPosNeutrophil;
magnitude=Math.sqrt(Math.pow(xVector, 2)+Math.pow(yVector, 2));
xNormVector=xVector/magnitude;
yNormVector=yVector/magnitude;
xSumVector=xSumVector+xNormVector;
ySumVector=ySumVector+yNormVector;
}
}
//3. Simulating a moving neutrophil
int dXNeutrophil=random.nextInt(11)-5+(int)aggressiveness*(int)xSumVector; //random motion
int dYNeutrophil=random.nextInt(11)-5+(int)aggressiveness*(int)ySumVector;
xPosNeutrophil=xPosNeutrophil+dXNeutrophil;
yPosNeutrophil=yPosNeutrophil+dYNeutrophil;
myPen.setSize(8);
if(xPosNeutrophil<(neutrophilRadius/2+2*myPen.getSize())) //boundaries neutrophil
{
xPosNeutrophil=(int)neutrophilRadius/2+2*myPen.getSize();
}
else if(xPosNeutrophil>xSize - (neutrophilRadius/2+2*myPen.getSize()))
{
xPosNeutrophil=xSize - ((int)neutrophilRadius/2+2*myPen.getSize());
}
else if(yPosNeutrophil<(neutrophilRadius/2+2*myPen.getSize()))
{
yPosNeutrophil=((int)neutrophilRadius/2+2*myPen.getSize());
}
else if(yPosNeutrophil>ySize - (neutrophilRadius/2+2*myPen.getSize()))
{
yPosNeutrophil=ySize - ((int)neutrophilRadius/2+2*myPen.getSize());
}
for(int i = 0; i <L ; i++) //defining circle, drawing points, placed here because it needs to be on top
{
xValueNeutrophil[i] = neutrophilRadius*Math.cos(2*Math.PI*i/L);
yValueNeutrophil[i] = neutrophilRadius*Math.sin(2*Math.PI*i/L);
myPen.setColor(Color.blue);
myPen.setShape(Shape.CIRCLE);
myPen.draw((int)xValueNeutrophil[i]+xPosNeutrophil,(int)yValueNeutrophil[i]+yPosNeutrophil);
}
if(Math.abs(xPosNeutrophil-xPosBacterium)<2*bacteriumRadiusInput && Math.abs(yPosNeutrophil-yPosBacterium)<2*bacteriumRadiusInput && bacteriumRadius >=0)
{
bacteriumRadius=bacteriumRadius-1;
if(bacteriumRadius==0)
{
bacteriumAlive=false;
}
}
if(bacteriumAlive==false)
{
bacteriumAlive=true;
xPosBacterium=random.nextInt(xSize); //random starting position of bacterium
yPosBacterium=random.nextInt(ySize);
bacteriumRadius=bacteriumRadiusInput;
}
myScreen.update(); //updating/refreshing screen
myScreen.pause(10);
myScreen.clear();
}
}
public static void main(String[] args) {
Exercise3_final e = new Exercise3_final();
}
}
Any help would be appreciated!
Sounds like you need an action listener on the "Run!" button from your dialog:
_run.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// set the variables here by getting the text from the inputs
field1Var = Integer.parseInt(field1Input.getText());
field2Var = Integer.parseInt(field2Input.getText());
...
}
});
I would suggest creating a singleton class to save all the values that are captured from the first screen (options menu screen).
You can get the instance of this class anywhere in the application later on and use it.
Advantages would be:
- You will not have to carry forward the values everywhere in the application.
- The values captured will the persisted till the application is shut down.
Note: Make sure to add validations while fetching values from the options menu so that incorrect values are not set.
// ************************************************************
// ELEVATOR.java
//
// ELEVAOTR SIMULATION
// PROBLEM: NEED TO FIND A WAY TO AMKE IT SO THAT THE PROGRAM KEEPS RNNING AFTER USER INPUTS
// THIER FIRST DESIRED FLOOR.
// ************************************************************
import java.util.*;
public class Elevator_Simulation {
public static void main (String[] args) {
Person User = new Person();
Floor floors = new Floor();
floors.moveElevator(User.getDesiredFloor());
}
}
class Elevator { //NEEDS SETTER & GETTER METHODS
private int mass=0;
private int capcity=0;
private String name="";
private String color="";
}
class Floor {
ArrayList<Object> floorLevel = new ArrayList<Object>();
Elevator Lift = new Elevator();
Person Man = new Person();
Floor() { //Floors 0-9
floorLevel.add(Lift); //0
floorLevel.add(null); //1
floorLevel.add(null); //2
floorLevel.add(null); //3
floorLevel.add(null); //4
floorLevel.add(null); //5
floorLevel.add(null); //6
floorLevel.add(null); //7
floorLevel.add(null); //8
floorLevel.add(null); //9
}
System.out.println("Elevator is at Floor: " + floorLevel.indexOf(Lift) );
public void moveElevator (int chosenFloor) {
if (chosenFloor > 9) {
System.out.println("Woooooah Buddy! You can only choose 0-9!");
return;
}
if (chosenFloor == floorLevel.indexOf(Lift)) {
System.out.println("Bro you're already on that floor...");
}
while (floorLevel.indexOf(Lift)>chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)-1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
while (floorLevel.indexOf(Lift)<chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)+1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
}
}
class Person {
Scanner scan = new Scanner(System.in);
public int getDesiredFloor() {
int desiredFloor = scan.nextInt();
return desiredFloor;
}
}
Above is an Elevator Simulator Code (before I attempt to make one with a GUI) and my only problem, aside from the obvious beginner flaws, is that I'm having trouble of finding a way to make it so that the program doesn't just end once the user inputs one floor. I at least want the program to run until the user ends it with a command. I'm thinking of using a while loop somewhere but where? Please help and point out anything I should improve in this code.
You can put the while loop around the line
floors.moveElevator(User.getDesiredFloor());
Just add an input check for a value that represents exiting.
I am completing an assignment and am having a hard time figuring out the logic need to make the program work. I do not want a direct answer but could someone point me in the right direction?
Assignment:
Define a class named UnfairCandyDistributor. An UnfairCandyDistributor object represents a mean big brother who is going to divide a set of candies between himself and his hungry little brother. This will be done unfairly: for every candy given to the sibling, the big brother takes for himself a number of additional candies equal to the younger sibling's total. Each UnfairCandyDistributor object should have the same method:
public void nextCandy()
Each time nextCandy is called, the method prints a message about who gets a candy. Each call to nextCandy produces a single line of output. This time the output is the following:
public class TestCandy2 {
public static void main(String[] args) {
UnfairCandyDistributor mean = new UnfairCandyDistributor();
mean.nextCandy(); // 1 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for me.
Here The class I have made so far:
public class UnfairCandyDistributor {
private int you;
private int me;
private int extra;
public void nextCandy()
{
if (you != me || extra != you - 1)
{
me++;
System.out.println(me + " for me");
}
else
{
you++;
System.out.println(you + " for you");
extra = 0;
}
}
}
Can't you just add a boolean variable that tells you who to dole out candy to?
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
for (int i=0; i<you; i++) {
System.out.println("one for me");
me++;
}
else
{
System.out.println("one for you");
you++;
}
candyToMe = !candyToMe;
}
}
or
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
System.out.println(you + " for me");
me += you;
}
else
{
System.out.println("1 for you");
you++;
}
candyToMe = !candyToMe;
}
}
..depending on whether you want the candies doled out one at a time or in hand-fulls where appropriate.
i have a problem with one thing. I have a map of 10 cities and a civilian. I want the civilian to be walking from city to city randomly. But the problem is that the city is beeing chosen on and on so the civilian is changing the destination before he reachs it. This is my part of a code of a Jpanel where everything is drawn:
#Override
public void run() {
while (running) {
update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
}
}
}
private void update() {
if (game != null && running == true) {
c.goTo(cities); // c is civilian
}
}
and this is part of code for civilian
private boolean set = true;
public void move(int x, int y) {
if (this.location.x != x || this.location.y != y) {
if (this.location.x > x) {
this.location.x -= 1;
} else {
this.location.x += 1;
}
if (this.location.y > y) {
this.location.y -= 1;
} else {
this.location.y += 1;
}
}
}
public void goTo(ArrayList<City> cities) {
City city;
if (set) {
city = cities.get(rand());
move(city.location.x, city.location.y);
set = false;
} else {
set = true;
}
}
public int rand() {
int i;
Random rand = new Random();
i = rand.nextInt(10);
return i;
}
How to solve it ?
So, your problem is here:
while (running) {
update();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
}
}
You're calling update every 17 milliseconds which in turn is causing your civilian to move to a new city every 17 milliseconds. You could make a separate statement that calls update while another boolean statement is false so that you travel only when he is in a city.
For example:
boolean travelling = //whatever you go about to configure this
while(travelling == false){
update();
}
This will cause him to only travel when he is not in a city. Here is some very rough code (you will have to configure it to your liking):
//civilian x //civilian y
if(this.location.x == //randomed city.x && this.location.y == //randomed city.y){
travelling = false;
}
This will most likely need to be within the run() method in your first set of code, so it can be checked over and over. But let me explain what the above code is doing:
First, you have a thread or something keeping it running checking if your civilian's x and y correspond to the most recently randomed city's x and y, obviously when they're the same, the civilian is at the city.
Second, when the x and y's are the same, the statement makes travelling false
Third, When travelling is false, your custom update method is called, picking a new city, at random and putting your civilian back on the move.
Hey im trying to create a random way to pick a team of 4 from a linkedlist and am wondering if this code will work.
heres an example code
public static void enterGame(Client c) {
int n = teamSize;
boolean startNewGame = false;
if(waitingPlayers.size() <= 3) {
return; // not enough players
}
startNewGame = true;
if(startNewGame) {
System.out.println("Starting new game");
for(int i=0; i<n; i++) {
Collections.shuffle(waitingPlayers);
System.out.println("Picking random player");
waitingPlayers.remove(c);
System.out.println("removing from random player list");
players.add(c);
System.out.println("adding player to ingame list");
}
}
}
I would use Collections.shuffle() and a sublist. In order to know if your code works why don't you test it (unit test or just some try)?
Also, this part:
boolean startNewGame = false;
if(waitingPlayers.size() > 3) {
startNewGame = true;
} else {
startNewGame = false;
return;
}
if(startNewGame) {
is over complicated, I would replace it by:
if(waitingPlayers.size() <= 3) {
return; // not enough players
}
Full code:
public static void enterGame(final Client c) {
if(waitingPlayers.size() <= 3) {
return; // not enough players
}
System.out.println("Starting new game");
Collections.shuffle(waitingPlayers);
System.out.println("Picking random players");
// ? to be replaced by the real type of objects inside waitingPlayers
final List<?> picked = waitingPlayers.subList(0, 3);
players.addAll(picked);
waitingPlayers.removeAll(picked);
}
You have a bug - you are picking a number from 0 to n. If n is selected, you will get an out of bounds exception. Other fhan that it seems fine.