So I'm currently working on a Card War Game in java. I'm trying to get the GUI screen to print 2 random cards from a set of card images using an arrayList (must use this for assignment). The card image files are named 1.png,2.png,...52.png and stored in a image/card directory. My question is how do I get two cards to appear randomly? Thanks here's my code
Also, just to note, I'm a relatively new programmer
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.paint.Color;
import javafx.scene.text.FontWeight;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import java.util.ArrayList;
public class CardWar extends Application{
public static void main(String args[]){
Application.launch(args);
}
@Override
public void start(Stage primaryStage){
ArrayList<Integer> cardList = new ArrayList<>();
for(int i = 1; i <=52;i++){
cardList.add(i);
}
java.util.Collections.shuffle(cardList);
System.out.println(cardList.get(0));
//Label label1 = new Label ("Welcome to the Card War Game!");
//layout for first scene
StackPane layout1 = new StackPane();
Button welcome = new Button("Click to Play");
Text text1 = new Text(20,20, "Welcome to The Game");
layout1.getChildren().add(welcome);
//layout for second scene
//Button button2 = new Button("You are here!");
Pane layout2 = new HBox (457);
//layout2.getChildren().add(button2);
Image image = new Image("image/card/1.png");
Image image2 = new Image("image/card/2.png");
ImageView imageView2 = new ImageView(image);
imageView2.setFitHeight(100);
imageView2.setFitWidth(100);
layout2.getChildren().add(new ImageView (image));
layout2.getChildren().add(new ImageView (image2));
Scene scene = new Scene (layout1,600,300);
Scene scene2 = new Scene(layout2,600,300);
welcome.setOnAction(e -> primaryStage.setScene(scene2));
primaryStage.setScene(scene);
primaryStage.setTitle("War Game");
primaryStage.show();
}
}
Here's a modified version of your code. This is what you should do:
The code:
You could create a new list like this using .subList(fromIndex, toIndex)
You could use the
Collections.shuffle(...)
method to shuffle theArrayList
.Then just take the first two entries from the
ArrayList
.