Im trying to make a PlantsVSZombies game. The player has initially 50 suns in order to buy plants. I want to make a counter which decreases whenever I buy plants but also increases continously if I have sunflowers present. Any ideas how I could do it? And thank you.
In pseudocode:
int counter = 50;
if(....)
...
counter--;
else if (....)
...
counter++;
It would be easier for us if you displayed what code you have tried and what issues you encountered.
For the next time, try to add some information about your classes and how you are planning to write all your code. For this question and with this information you can try to just manage that with one Integer value:
int suns = 50;
public sunsCounter(bool increase){
if(increase){
this.suns +=1
}else{
this.suns -=1
}
I'ts just an idea and it's so basic, obviously, you have to create some classes to manage that and operate with this class objects.
Related
I have an app that I have made for friends to randomize races for a board game, such that a player gets a randomly selected species every time. I want to include a feature in an update that will allow for a blacklist so that certain races cannot be chosen. What would be the best way to go about this? I'll take any and all advice. Much thanks in advance.
Of note: The array consists of strings of names, and I'd like for this to be persistent for as long as they have the app installed or until they change it.
Edit: Apologies for my lack of clarity. I know generally how I need to do it, but what about saving the settings from the settings menu so that upon closing and reopening, blacklisted races are persistent? Even when the app is closed, upon reopening I'd like for the settings to stay the same. That way next time they play the game (weeks later), assuming their tastes haven't changed, they can go to clicking without blacklisting again.
Without any code, it's hard to say for sure how to go about this, because I don't know how you're implementing the rest of the app.
One way I can think of doing this is if you associate an integer with each race, e.g. by using constants:
public static final GIRAFFE = 1;
public static final GOOSE = 2;
Then you could generate random integers to randomly pick each race. If you created a method for the random integer generation, you could then pass certain numbers that would be excluded. You could keep generating a random integer while the integer generated was one of the excluded numbers.
E.g. (Since it's Android I'll code in Java)
// assume min = smallest integer assigned to an animal,
// and max = largest integer assigned to an animal
public static int randomNumber(int ... exclude)
{
int random = min + (int)(Math.random() * ((max - min) + 1));
for (int i = 0; i < exclude.length; i++)
{
if (exclude[i] == random)
random = Min + (int)(Math.random() * ((Max - Min) + 1));
}
return random;
}
I'm a little new to StackOverflow, so let me know if this helps.
What you need to do is persist data. You can use two solutions:
1) The SharedPreferences framework for saving key-value pairs without any effort. See here to see how to save a list Store a List or Set in SharedPreferences
2) use SQL database. (custom solution)
In case 1 you would persist the blacklisted strings and in case 2 you would be best to create a table with all strings and have a boolean as to whether its blacklisted or not.
I recommend the shared preferences one since it should take you 5 min to do whereas, unless you are familiar with databases, the database solution will take you a while to work out.
I am trying to write code for a command like game of Farkle (greed). This is an Intro to computer science class. In a nutshell, you roll 6 die, and scores are based off of what you roll. Then you are required to remove the die that were used -> display score from that roll -> display total score -> ask if they would like to roll again. First player to a score determined by the user is the winner.
I have a bunch of code written for the model, and I am working on the view. I am struggling with the view, which makes it harder to advance on my model code. We are required to use the Die and Player classes (we were given those). I use the Die quickly, not quite sure how to apply the Player class.
When I try to run my command line, I am getting out of bounds errors on my rollCheck() array and other issues in my model that were not coming up when I simply was testing in main. I apologize for the amount of code posted, but I figure seeing everything makes it easier to solve (goes without saying really).
If anyone can give me pushes in the right direction to solving and making my program work, that would be great! Thank you.
Without being able to run the program to be sure its hard to be certain (I need the top of GreedGame) but i'd be fairly confident its the following:
in rollDie die is set to an array of ints on size remainingDie
this.die = new int [remainingDie];
later, within rollCheck the contents of the die array up to and including remainingDie, going over the array by 1
for (int i = 0; i <= remainingDie; i++) { // Count up quantity of die (6 set to remaining die)
if (die[i] == 1) {
this.numFreq[0] += 1;
}
....
....
}
So in short I believe i <= remainingDie; should be i < remainingDie; because an array with 6 entries has "boxes" 0,1,2,3,4,5
I created a checkress game and I would like the computer to calculate the most optimal move.
Here is what I've done so far:
public BoardS calcNextMove(BoardS bs)
{
ArrayList<BoardS>options = calcPossibleOptions(bs);
int max = -1;
int temp;
int bestMove = 0;
for(int k=0;k<options.size();k++)
{
temp = calculateNextMove2(options.get(k));
if(max<temp)
{
max = temp;
bestMove = k;
}
}
return options.get(bestMove);
}
public int calculateNextMove2(BoardS bs)
{
int res = soWhoWon(bs);
if(res == 2) //pc won(which is good so we return 1)
return 1;
if(res == 1)
return 0;
ArrayList<BoardS>options = calcPossibleOptions(bs);
int sum = 0;
for(int k=0;k<options.size();k++)
{
sum += calculateNextMove2(options.get(k));
}
return sum;
}
I keep getting
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
calcPossibleOptions works good, it's a function that returns an array of all the possible options.
BoardS is a clas that represent a game board.
I guess I have to make it more efficient, how?
The recursion on "calculateNextMove2()" will run too deep and this is why you get a StackOverFlow. If you expect the game to run to the end (unless relatively close to an actual win) this may take a very long time indeed. Like with chess e.g. (which I have more experience with) an engine will go maybe 20 moves deep before you will likely go with what it's found thus far. If you ran it from the start of a chess game... it can run for 100s of years on current technology (and still not really be able to say what the winning first move is). Maybe just try 10 or 20 moves deep? (which would still beat most humans - and would still probably classify as "best move"). As with chess you will have the difficulty of assessing a position as good or bad for this to work (often calculated as a combination of material advantage and positional advantage). That is the tricky part. Note: Project Chinook has done what you're looking to achieve - it has "defeated" the game of Checkers (no such thing exists yet for chess EDIT: Magnus Carslen has "deafeted" the game for all intents and purposes :D).
see: Alpha-beta pruning
(it may help somewhat)
Also here is an (oldish) paper I saw on the subject:
Graham Owen 1997 Search Algorithms and Game Playing
(it may be useful)
Also note that returning the first move that results in a "win" is 'naive' - because it may be a totally improbably line of moves where the opponent will gain an advantage if they don't play in a very particular win - e.g. Playing for Fools Mate or Scholars Mate in chess... (quick but very punishable)
You're going to need to find an alternative to MinMax, even with alpha-beta pruning most likely, as the board is too large making too many possible moves, and counter moves. This leads to the stack overflow.
I was fairly surprised to see that making the full decision tree for Tic-Tac-Toe didn't overflow myself, but I'm afraid I don't know enough about AI planning, or another algorithm for doing these problems, to help you beyond that.
This is about my assignment so I would appreciate generic answers with explanation.
I have a for-loop which I have to make for an online ordering system. The for-loop and ordering all works fine but if the same item is put in twice, then it forgets the previous order for the same item and only remembers the latest one. I am required to use simple arrays and for-loops so I would appreciate if the solution/help was also of this basic level.
My code looks something like this (NOTE: The following is just an example of what part of the loop looks like--this is not a complete program):
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
int price = quantity[i] + itemcode;
}
}
To explain further, this loop and the if statement work perfectly if a certain item is only ordered once. But if the user enters, say, an order for a computer once and then after 3 more orders, orders another computer, then the output does not add the previous order in the new order but only remembers the latest one.
I would appreciate any work around suggested for this but again, since this is for my studies, I would appreciate explanations rather than direct solutions.
Please ask me questions in case this is not clear.
"Forgets" suggests that you are overwriting something in your code rather than, say, just incrementing. Go through your code, see what parts of it gets reset when you place a new order. For instance, if you are doing
quantity[1] = getNumberFromUser("How many apples?");
then this would obviously erase the old value each time. If you want to merely increment the number of apples, do something like
quantity[1] += getNumberFromUser("How many apples?");
Another general advice is to use print statements to debug your code. That way you can see for yourself what really happens. Learning to use a real debugger would also be of great benefit.
if you have two or more typres of products and want to calculate the price for all the orders together then you can try the following code,, i think thats very simple,,
int price=0;
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
price += quantity[i] + itemcode; //use the previous value of price
}
}
or else if you want to have history for each product separately then you have to try the same with a array of price for each product type..
If you cant get the answer then comment here,,
was wondering if you could help me out:
I have a method called initializeAll:
public final void initializeAll() {
//other stuff........
rand = new Random(353);
}
So I run the project and a GUI pops up, and some operations are carried out. When I press the "reset" button in my GUI, intializeAll is called again on the same class object. However, the operations that are carried out now are not the same as before, although they should be, since both times, a seed of 353 is being used on the newly created Random object. Why this difference? Am I doing something wrong?
EDIT: sorry, its not "some operations are carried out". its that some initialization of agent population takes place. and each time, the initialization is different, although the same seed is used.
private static int [][] initializePop(Random rand) {
int[][] temp = new int[ROWS][COLS];
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
temp[row][col] = rand.nextInt(12) - 5;
}
}
return temp;
}
SOLUTION:
sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. i'm redesigning the code now. so thanks again, and sorry for wasting your time.
Am I doing something wrong?
Yes, it seems so. The Random(long) should reset the seed to the provided value. What ever the error is, it will be impossible for us to help you without an SSCCE or at least more code.
Random rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
Output:
7
5
5
7
5
5
sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. so thanks again, and sorry for wasting your time.