I'm trying to do my school project "Tron". I'm newbie when it comes to programming... I did some collisions with arraylist and they are working fine.But I can't do collision snake with other object ... I'm using this:
snake1x and snake1y are coordinates of first snake and obstacleX is arraylist that contains coordinates of other object.
for(int l=0;l<obstacleX.size();l++) {
if((snake1x == obstacleX.get(l)) && (snake1y == obstacleY.get(l))) {
running = false;
}
}
I have the object already drawn in my game but snake will just pass throught it ... :(
the weird thing is that I did this with similiar method on collision between snakes and it works fine :)
My second problem is with combobox and choosing a color for snake..
if (snake1 = true) {
for (int p = 0; p < pathx1.size(); p++) {
g.setColor(Color.white);
g.fillRect(pathx1.get(p), pathy1.get(p), width, height);
I could simply give it colour like this but I need to choose it from the combobox
and that where I am lost :)
I will appreciate any help or anything that could improve my work like adding other things and something like that thanks~~ :-)
import java.util.*;
public class AutoBoxingTest
{
public static void main(String[] args) {
int i = 1;
Integer intObj = 1;
ArrayList<Integer> intArray = new ArrayList<>();
intArray.add(new Integer(1)); // Forcefully create a new Integer object
intArray.add(1);
if(i==intArray.get(0))
System.out.println("Equals");
else
System.out.println("Not Equals");
if(intObj==intArray.get(0))
System.out.println("Equals");
else
System.out.println("Not Equals");
if(intObj==intArray.get(1))
System.out.println("Equals");
else
System.out.println("Not Equals");
}
}
When you run this program, you get the result
Equals
Not Equals
Equals
Notice the difference between intArray.get(0) and intArray.get(1). Even though both are 1, they are different objects.
Related
I've a little problem.
Myself and a few friends were playing poker yesterday but we didn't have chips so I decided to start writing a program for that [Without Cards, just Chips].
In my code I have two main variables in the Game Object.
private int id;
private long bank;
I have a different file called Aside in which I can do different calculations.
In the code below I am trying to compare all instance bank variables to see if all the banks matched [In this case this will mean a new card can be drawn, otherwise users will have to keep to either raise or fold].
Is there a way of writing this in an easier term:
package poker;
import java.util.ArrayList;
public class Aside
{
public boolean compareBanks(ArrayList<Game> x)
{
ArrayList<Game> players = new ArrayList(x);
if(players.get(0).getBank() == players.get(1).getBank() && players.get(0).getBank() == players.get(2).getBank()
&& players.get(1).getBank() == players.get(2).getBank())
{
return true;
}
return false;
}
}
Later I use this here:
while(aside.compareBanks(players))
But the loop keeps going.
I'm fairly intermediate in programming so go easy on me with mistakes.
Thank you for your time.
P.S: This is NOT a code dump.
while(aside.compareBanks(players))
{
for(Game x : players)
{
if(x.hasPayedBid() == true)
{
System.out.println("Player : " + x.getName() + " [Call, Raise, Fold]:");
action = in.nextLine();
if(action.equalsIgnoreCase("call"))
{
break;
}else if(action.equalsIgnoreCase("raise"))
{
System.out.println("How much are you raising? $");
int raise = in.nextInt();
table += raise;
x.raise(raise);
}else
{
x.fold();
}
}
}
in.nextLine();
for(Game x : players)
{
System.out.println(x.toString() + "\n");
}
}//End While
You can do it using java-8 Stream API something like this
return players.stream().allMatch(p -> p.getBlank().equals( players.get(0).getBalnk()))
However if you will use while(aside.compareBanks(players)) and all elements of the list have equal blank value, your while loop will never stop. It is the same as while(true). So in this case you probably need to use if(aside.compareBanks(players)) or in case of equal blank values change them.
Try this
long bankValue=0;
For(Game player: players){
bankValue+=player.getBank();
}
if(bankValue==(players.get(0).getBank()*players.size)){
return true;}
else return false;
I have x,y coordinates stored in a Point2D.Double type.
Code:
private Point2D[] block1 = new Point2D[99]
block1[0] = new Point2D.Double(12,14);
block1[1] = new Point2D.Double(15,16);
block1[2] = new Point2D.Double(20,20)
//etc all to 99.
//this can run about 10 times creating 10 different sets of x,y coordinates.
Want to iterate through all the arrays see if a specific coordinate is already there. If it is return true. Not sure on the best way to do it.
So I know that I will need a for/if loop.
Example: I want to check to see if (15,16) is there:
for(Point2D block[] : block1){
if(block.getX() == 15 && block.getY() == 16){
System.out.println("This is true");
}
}
So I want it to search through all the arrays to see if there is a (15,16). I can image this syntax is along the right lines but it is not right.
This approach will gets as close as possible to your desired syntax:
Point2D target = new Point2D.Double(15, 16);
for(Point2D block : block1){
if(target.equals(block)){
System.out.println("This is true");
}
}
By the way, you mentioned you want 10 times 10 different sets of coordinates, so you need to change the 99 to 100, otherwise you will crash the array:
Point2D[] block1 = new Point2D[100];
There's an error in this line:
for(Point2D block[] : block1){
if 'block1' is an array, while iterating 'block's type should be of the array's type. Namely, just Point2D - rather than Point2D[].
As a first step, try this snippet out:
for (Point2D block : block1) {
if (block.getX() == 15 && block.getY() == 16) {
System.out.println("Found it");
}
}
Almost there, now just extract that to a method:
public boolean containsPoint(Point2D[] points, int x, int y) {
for(Point2D block : points){
if(block.getX() == x && block.getY() == y){
return true;
}
}
return false;
}
...
/* calling the method */
if(containsPoint(points, 10, 10)) { // do stuff }
In the land of Puzzlevania, Aaron, Bob, and Charlie had an argument over which
one of them was the greatest puzzler of all time.
To end the argument once and
for all, they agreed on a duel to the death.
Aaron was a poor shooter and only hit
his target with a probability of 1>3.
Bob was a bit better and hit his target with a
probability of 1>2.
Charlie was an expert marksman and never missed. A hit means
a kill and the person hit drops out of the duel.
To compensate for the inequities in their marksmanship skills, the three decided
that they would fire in turns, starting with Aaron, followed by Bob, and then by
Charlie. The cycle would repeat until there was one man standing, and that man
would be the Greatest Puzzler of All Time.
An obvious and reasonable strategy is for each man to shoot at the most accurate
shooter still alive, on the grounds that this shooter is the deadliest and has the best
chance of hitting back.Write a program to simulate the duel using this strategy.
Your program should use
random numbers and the probabilities given in the problem to determine whether
a shooter hits the target.
Create a class named Duelist that contains the dueler’s
name and shooting accuracy, a Boolean indicating whether the dueler is still alive,
and a method ShootAtTarget ( Duelist target ) that sets the target to dead if
the dueler hits his target (using a random number and the shooting accuracy) and
does nothing otherwise.
Once you can simulate a single duel, add a loop to your program that simulates
10,000 duels. Count the number of times that each contestant wins and print the
probability of winning for each contestant (e.g., for Aaron your program might
output “Aaron won 3,595>10,000 duels or 35.95%”).
An alternate strategy is for Aaron to intentionally miss on his first shot. Modify the
program to accommodate this new strategy and output the probability of winning
for each contestant.
Which strategy is better for Aaron: to intentionally miss on the
first shot or to try and hit the best shooter? Who has the best chance of winning,
the best shooter or the worst shooter?
Ok so that the problem. Here is my code so far:
public class Duelist {
private String name;
private double probabilityOfHitting;
private boolean alive = true;
//Only declared instance variables. Must created setters and getters
public void setName(String newName){
name = newName;
}
//name setter created
public void setProbabilityOfHitting( double newProbabilityOfHitting){
probabilityOfHitting = newProbabilityOfHitting;
}
//probability of hitting setter created
public void setAlive(boolean newAlive){
alive = newAlive;
}
//name setter created
//now must create getters
public String getName(){
return name;
}
//created the name getter
public double getProbabilityOfHitting(){
return probabilityOfHitting;
}
//created the probability of hitting getter
public boolean getAlive(){
return alive;
}
//created the alive getter
//no constructors created before
public Duelist(String tempName, double tempProbability){
name = tempName;
probabilityOfHitting = tempProbability;
}
//constructor is now created
//need to create a method for the duelists to shoot at each other
public void shootAtTarget(Duelist target){
double randomNum = Math.random();
if (this.probabilityOfHitting ==1){
target.setAlive(false);
target.getAlive();
}
else if (randomNum <= this.probabilityOfHitting){
target.setAlive(false);
target.getAlive();
}
else {
target.getAlive();
}
}
}
public class Tester {
public static void main(String[] args) {
int winsA = 0;
int winsB = 0;
int winsC = 0;
Duelist aaron = new Duelist("Aaron",(1/3));
Duelist bob = new Duelist("Bob", (1/2));
Duelist charlie = new Duelist("Charlie", 1);
if(aaron.getAlive() == true){
if(charlie.getAlive()== true){
aaron.shootAtTarget(charlie);
}
else if(bob.getAlive() == true){
aaron.shootAtTarget(bob);
}
else{
winsA++;
}
}
else if(bob.getAlive() == true){
if(charlie.getAlive() == true){
bob.shootAtTarget(charlie);
}
else if(aaron.getAlive() == true){
bob.shootAtTarget(aaron);
}
else{
winsB++;
}
}
else{
if (bob.getAlive() == true){
charlie.shootAtTarget(bob);
}
else if(aaron.getAlive() == true){
charlie.shootAtTarget(aaron);
}
else{
winsC++;
}
}
System.out.println(winsA);
System.out.println(winsB);
System.out.println(winsC);
}
}
I know I haven't gotten close to finishing the problem yet. What I did in my tester class was to try and simulate one duel and once when I simulated one duel, I would be able to loop it so I can simulate more. The problem I'm having is that the when I run the code, the wins for Aaron, Bob, and Charlie all come up to 0 and I don't know why.
As the last parameter in the constructor calls, you wrote
Duelist aaron = new Duelist("Aaron",(1/3));
There you are dividing an int by another int, and the result will be 0 in this case. This has to be changed to
Duelist aaron = new Duelist("Aaron",(1.0/3.0));
so that double values are used (and the result will be 0.3333, as desired).
Most of your Duelist class does not seem to be "wrong", but the shootAtTarget method could be improved.
A general hint: I'd recommend you to never use Math.random(). This will deliver unpredictable results. Instead, you should use an instance of java.util.Random. This can be initialized with a certain random seed, so that it always provides the same sequence of random numbers. This makes debugging much easier.
Additonally, some tests have been redundant. When the probabilityOfHitting is 1.0, then there is no special test required: The random number will always be less-than-or-equal to 1.0. You are also occasionally calling target.getAlive() for no apparent reason.
So in the end, the method could look like this:
private static Random random = new Random(0);
//need to create a method for the duelists to shoot at each other
public void shootAtTarget(Duelist target)
{
double randomNum = random.nextDouble();
if (randomNum <= this.probabilityOfHitting)
{
target.setAlive(false);
}
}
However, the main problem was in your Test class. I'm not sure about general recommendations here. One could go very far in terms of abstraction. (A Java Enterprise Architect would probably end up with writing a AbstractDuelistStrategyFactory somewhere...). But to put it simply: At the moment, you are doing at most one shot. After one shot, nobody can have won. And you don't know how many shots have to be taken before there is only one duelist remaining.
Much of this could be made more elegant and flexible if you placed the Duelists into a List<Duelist>. But without that, an approach that is "structurally close to what you started" could look like this:
int alive = 3;
while (alive > 1)
{
System.out.println("Status: A:"+aaron.getAlive()+" B:"+bob.getAlive()+" C:"+charlie.getAlive());
if (aaron.getAlive())
{
if(charlie.getAlive())
{
System.out.println("A shoots at C");
aaron.shootAtTarget(charlie);
if (!charlie.getAlive())
{
System.out.println("A killed C");
alive--;
}
}
else if(bob.getAlive())
{
System.out.println("A shoots at B");
aaron.shootAtTarget(bob);
if (!bob.getAlive())
{
System.out.println("A killed B");
alive--;
}
}
}
// Other cases ...
}
if (aaron.getAlive())
{
winsA++;
}
if (bob.getAlive())
{
winsB++;
}
if (charlie.getAlive())
{
winsC++;
}
(Note that there are still cases missing!)
I created two methods for my Bingo Game in Java. One method creates a new board which populates the Bingo Board with integers according to the Bingo rule (1-75). My second method generates random numbers with a range of 1 - 75.
public static int drawNum(){
Random rand = new Random();
int num = rand.nextInt(75)+1;
return num;
}
public static void bingoCard(){
int [][]card=new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
int tmp = 0;
for(int i = 0; i <= 4; i++){
for(int row = 0; row < card.length; row++){
while(!valid){
tmp = (int)(Math.random() * 15) + 1 + 15 * i;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
valid = false;
}
}
card[2][2] = 0;
//create array to make title.
String title []={"B","I","N","G","O"};
for(int i=0;i<title.length;i++){
System.out.print(title[i]+ "\t");
}
System.out.println();
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
System.out.print(card[row][col]+ "\t");
}
System.out.println();
}
}
What I need help with is, how do I check whether or not the drawNum() method corresponds to any values stored inside my bingoCard() array? If so, print out a new array with the integers filled in. If the condition is met for a bingo, then you win.
I hope I don't make it sound like I want you to do it for me, but I am confused as to how to start coding that part. Thank you.
This my recommendation - Learn Object Oriented Programming immediately
I see you are using objects provided in the JDK, so why not learn to make your own?
Make two classes with the following methods (-) and members (+) (PS. This is not a formal way to document code)
BingoCard
+list of numbers on card
-reset() : gets new numbers for this card
-test(BingoDrawer) : Tests to see if this card won on this drawing
-toString() : returns a String representation of this card
BingoDrawer
+list of numbers drawn
-reset() : draws new numbers
-hasNumber(int number) : tests if this number was drawn
-toString() : returns a String representation of this drawing
One more suggestions
Instead of keeping track of what you used, keep track of what you have not used, it will make things much easier because you can just choose stuff from that list randomly. Unlike your current action which is choosing (a logical number) from thin air and hoping (which causes issues) it is not a collision
If you follow my recommendation you can write code like this
public static void main(String[] args) {
BingoCard bc = new BingoCard();
BingoDrawer bd = new BingoDrawer();
while(thePlayerWantsToPlay()) { //function to be defined by you
bc.reset();
bd.reset();
System.out.println(bc);
System.out.println(bd);
System.out.println(bc.test(bd));
}
}
You can take it a step further and make a BingoGame class and do what I did in main there and just create an instance of BingoGame and call some start method on the object.
For checking if you have the number in your board, read through the board in a similar manner as you do for the already_used numbers, except with the number the user just entered.
The conditions for the user to win should be checked after the board has another number guessed.
There are a few ways to do this, a simple one would be to iterate over every possible pattern that could win, checking to see if there are tokens there.
All of this would be in a loop, that goes a little like this:
Set up board via user entering numbers.
Start loop
set either a timer to wait for, or wait for a keypress (so the game doesn't just play really fast)
Get random number
Possibly add to board
Check if winner
if winner, break the loop and do something else.
Print the new board out.
(end of loop)
If they got here, that could mean they won!
Wait to exit
You can just write it out as pseudo-code and fill in the methods after that. It usually helps to work on these things in a top-down fashion. So, for bingo you might have:
board = generateBoard();
while (!bingoFound(board)) {
number = drawNumber();
board = stampNumbers(board, number);
}
If that makes sense, you can go a step deeper and define each method. For example, bingoFound might look like:
public boolean bingoFound(int[][] board) {
boolean wasFound = bingoRowFound(board)
|| bingoColFound(board)
|| bingoDiagonalFound(board);
return wasFound;
}
Again, I've defined everything in (mostly) pseudo-code. If this looks ok, you can move a step deeper. Let's define the bingoRowFound method.
public boolean bingoRowFound(int[][] board) {
for (int row = 0; row < NUM_ROWS; row++) {
boolean rowIsABingo = true;
for (int col = 0; col < NUM_COLS; col++) {
// We have to check that everything up until this point has
// been marked off. I am using -1 to indicate that a spot has
// been marked.
rowIsABingo = rowIsABingo && board[row][col] == -1;
}
if (rowIsABingo) { return rowIsABingo; }
}
return false; // If we didn't find a bingo, return false.
}
Some of the methods (like drawNumber) will be really easy to implement. Others, like looking for a diagonal bingo might be a bit more difficult.
Feb 12 2014 Update:
Retracted code, since this was a college course assignment, and I want to prevent people just copying the code. I almost got in trouble for being accused of sharing code (which is a nono in assignments) when another student lifted my code from my Github repo and sent it in as their own.
There were two classes, one main class and a class to hold my methods and constructors.
BINGOFINAL.java was my main class.
Bingo_Card.java held my constructor and methods.
If you want to run this, make sure you create a new project called BINGOFINAL, and put Bingo_Card.java into that same */src/ extension.
I want to add an image to an ImageButton depending on a number between 0 and 10. My getNumber method is:
public int getNumber(){
// get a random number between 0 and 10
Random randomNumber = new Random();
num = randomNumber.nextInt(10);
return num;
}
I want every image to be unique but the problem I was having was that if numList did contain num it just would leave the button blank. I've tried to call permuteButton again recursively until num is not contained within my list but this does not seem to work.
public void permuteButton(ImageButton btn){
getNumber();
for(int i=0; i<=numList.size(); i++){
//check if the number is already being used
if( numList.contains(num) ){
permuteButton(btn);
}
// else the list doesnt have the number so assign the picture and add number to list
else{
numList.add(num);
assignPictures(btn);
}
}
}
Any help would be appreciated. I'm sorry if this is a simple question.
There are various things wrong with this code:
It would be better to have a single instance of Random instead of creating a new instance on each call to getNumber()
Rather than changing an instance variable within getNumber(), it would be sensible to just return the value and assign that to a local variable in permuteButton
Instead of recursion, you could use a while loop in permuteButton:
int num = getNumber();
while (numList.contains(num)) {
num = getNumber();
}
numList.add(num);
assignPictures(btn); // Presumably you'd now want to pass in num too
It would probably be a better idea to just shuffle the list to start with, create a Queue from it, then you can just take an item from the queue each time you need one. (This would also make it very easy to spot when you've used them all)
My answer is similar to the last suggestion from Jon Skeet.
// might be more than 10 ImageButtons, with only 10 images
for (ImageButton imageButton : imageButtons)
imageButton.putImage(randomImage.next());
...
public class RandomImage {
private final List<Image> shuffledImages;
private int currentIndex;
public RandomImage(List<Image> images) {
shuffledImages = new ArrayList<>(images.size());
shuffledImages.addAll(images);
currentIndex = -1;
}
public Image next() {
currentIndex++;
if (currentIndex % shuffledImages.size() == 0) {
currentIndex = 0;
Collections.shuffle(shuffledImages);
}
return shuffledImages[currentIndex];
}
}