Java - farkle (greed) game (die and player arrays, multiple classes) - java

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

Related

How to make battleship boat spawner in java?

Essentially, it is my big grade 12 code project in java to make a battleship. I have most of the mechanics finished I just am struggling with a random boat generator. It seems to almost work sometimes with variation in sizes, however, I often find random clumps that do not resemble the boats I want. Basically, each spot on a 2d grid is an object that has an int variable named status. If status=0, it is a water spot. if status=1, it is a boat spot. Any errors in my code or is there possibly a better way? Thank you for the help I really appreciate it :)
Haven't done any other method because nothing else has come to my head.
void addBoat(int x) {
int c=floor(random(4));//picks a random direction
int tx, ty;//target location in array
tx=floor(random(xs));//xs is x size of the array
ty=floor(random(ys));//ys is the y size of the array
for (int i=0; i<x; i++) {
//paramaters for conditions
if (c==0 && tx>=x-1 && sqr[tx-i][ty].status==0) {
sqr[tx-i][ty].status=1; //to the left of the target block, status is whether it is water or boat. water is status=0, boat is status=1.
} else if (c==1 && tx<=xs-x && sqr[tx+i][ty].status==0) {
sqr[tx+i][ty].status=1; //to the right of the target block
} else if (c==2 && ty>=x-1 && sqr[tx][ty-i].status==0) {
sqr[tx][ty-i].status=1; //above the target block
} else if (c==3 && ty<=ys-x && sqr[tx][ty+i].status==0) {
sqr[tx][ty+i].status=1; //below the target block
} else {
c=floor(random(4));
i=0;
//if position is not possible, run again
}
}
}
void makeBoat() {
addBoat(2);
addBoat(3);
addBoat(3);
addBoat(4);
addBoat(5);
}
I want boats to be the proper size and either vertical or horizontal, however I usually just get strange clumps.
It seems to me like you are placing your boat pieces before checking whether your boat can be fully placed. The moment it detects it can't properly place the boat it starts over without deleting the already generated pieces. Another thing is that you don't seem to have anything in place for the case that it is impossible to place a boat at a chosen starting position, at which point it probably runs into an infinite loop.
All in all, I'd recommend you to first generate a set of a position, a direction and a length, then check whether this is a valid boat placement and only then place it (or generate a new set), i.e. split it up into three methods. There's still a slim chance of infinite loops if boats are generated such that it is impossible to place the next one so you may want to have some checks in place to prevent that (maybe deleting the state completely and starting over if it does >10,000 attempts for a single boat or something).
You should also use enums instead of integers for your states/directions to make it more readable. You could also use boolean values for your states if they only store whether there's water or a boat.

A counter that increases and decreases depending on other elements

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.

How to reverse a SoundSample array?

I have to reverse the order of an array called myWordArray that plays from a thisisatest.wav file. It should play "test a is this" instead of "this is a test."
public void playReverseOrder(int pause) throws InterruptedException {
Sound orig = new Sound();
int length = myWordArray.length;
for (int i = 0, source = length - 1; i < length && source > 0; i++, source--) {
myWordArray[i].setSampleValueAt(i, orig.getSampleValueAt(source));
myWordArray[i].blockingPlay();
Thread.sleep(pause);
}
}
My logic is that I create a new sound, then use the length to increment the index i forward as the original source decrements. It plays forward, however I cannot get the words to reverse. I've thought of retrieving the samples of the myWordArray within new Sound (myWordArray.getSamples()); however that does not work, and I would try to access the file within the parameters, but we select the file manually within the test harness.
I am assuming, you meant test a is this. This is a harder problem and discussed below. If you want to make it sound like tset a si siht, you can simply arrange the content of the array in reverse order. Please note that, this sound wont be intelligible.
myWordArray[i].blockingPlay();
Thread.sleep(pause);
In your code, I guess you don't need this.
If you are interested in test a is this, the process would be something like this:
Find number of words in the sound file, requires little knowledge of audio signal processing
Mark their boundaries
Now, half of the work is done. Only remaining part is playing back the sounds of words in reverse order.
Create another Sound, fill the samples array with all segmented pieces of words, but in reverse order. Done.

Can't access my array

My programme is to create a Train Route Finder using Java, first off as a command line programme then convert into a GUI. That's the least of my worries for now. I am currently stuck on one functionality of my system and that is to display the list of stops between two stations that the user previously input.
Now, I have been able to prompt the user to choose their stops (lines 3,149 - 3,171 in my code):
if(deptChoice == 1 && arrChoice == 2){
List<String> stopList1_2 = new ArrayList<String>();
Scanner stopPick = new Scanner(System.in);
stopPick.useDelimiter(System.getProperty("line.separator"));
do {
System.out.println("\nCurrent list of stops between Leicester to Loughborough is:\n\n" + stopList1_2);
System.out.println("\nWould you like to add a new stop? (Please enter 'Yes' or 'No')\n");
if (stopPick.next().startsWith("Yes")) {
System.out.println("\nPlease type in the stop you wish to add to the route:\n");
stopList1_2.add(stopPick.next());
}
else {
break;
}
} while (true);
String[] stopArr1_2 = stopList1_2.toArray(new String[0]);
System.out.println("\nCurrent stops between Leicester to Loughborough is:\n\n" + Arrays.toString(stopArr1_2));
}
and the stops they type in are added to an array. When they are satisfied with the amount stops between the stations there are then the loop ends and it displays the array of stops between Station X and Station Y.
However, here comes the problem:
I want to then gain access to this previously created array with all the exact stops further up my code. In this "if" statement, if it is satisfied, then I want the array (stopArr1_2) to be displayed (in lines 3,019 - 3,021):
if(deptChoice == 1 && arrChoice == 2){
System.out.println(""); //this should be where I call the array back to display itself
}
as those stops would correspond with the users choice of deptChoice == 1 (Station 1 = Leicester) to arrChoice == 2 (Station 2 = Loughborough).
I hope this is clear:
I basically want the array of stops inputted by the user to reappear when they choose Train Routes.
Here his my full code I made in Notepad++ I thought it would be better for you lot to see all of my code rather than small segments and it is commented.
Furthermore, to comprehend my problem run my programme. To understand my problem do this:
1) Compile Train.java (javac Train.java)
2) Run programme (java Train)
3) Pick Admin Menu (Number 5)
4) Pick Input Menu (Number 1)
5) Pick any two stations
6) Enter a couple of stops until you're happy
7) When it shows the final stops array for those two stations the programme seems to end so hopefully that is not an issue
8) Run programme again (java Train)
9) Pick Train Routes (Number 3)
10) Pick the SAME stations in the same order as you did before so it would find the array you just made
11) Now nothing will come up because, well, that's my problem. I don't know how to regain that array I just made for it.
Download link to my Train.java file (and Train.txt file if needed):
https://www.dropbox.com/s/7dy0pp9vyykwhrk/TrainJava.rar
Any suggestions?
Whats the location of your second block of code ? ( The code where you said you need access to the List<String> stopList1_2 ) ?
1 If its in the same class but in a different method , then
Move this declaration
List<String> stopList1_2 = new ArrayList<String>(); ( currently in your first block of code ) to a class field.
BUT
2 If its in the same class and also in the same method as your first block of code, then
Move this declaration
List<String> stopList1_2 = new ArrayList<String>(); ( currently within the if statement of code ) to outside the if condition .
but treat this as a quick recipe for you problem at hand. More importantly - please read the variable scoping rule and access specifiers in java.

Calculating the optimal move in checkers

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.

Categories

Resources