简体   繁体   中英

How to link images to numbers and descriptions?

I'm having trouble trying with a card game program that I'm writing. The game is basically like War with 4 players, each player gets a card and the highest card wins. The cards are supposed to be arranged from 2-Ace and the rank of the suits goes: clubs, diamonds, hearts, and the spades. I have an algorithm here for the game, I also have a folder that holds the cards. The issue I'm having is trying to connect each of the cards with a number in an arraylist so that when the user presses the deal button, it will deal them each a card and then compare them and print out the winner of the round. Here is my code. Right now I have the UI opening up and the random cards appear in each player box. The issue I'm having again is trying to link those cards to a specific number, and description, and to get the deal button to deal 4 new cards each time. Please help! PS I know I have very messy code and a lot of stuff is not being used, these are just things that I have been trying.

    import java.io.File;
    import java.util.ArrayList;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import java.util.Collections;
    import java.util.EnumSet;
    import java.util.List;
    import javafx.application.Application;
    import javafx.event.*;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.stage.Stage;
    import javafx.scene.layout.*;
    import javafx.scene.control.Label;
    import javafx.geometry.*;
    import java.util.*;

    import javafx.scene.Node;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.paint.Color;

    import javax.swing.*;

 public class War extends Application {
public static void main(String[] args) {
    launch(args);
}

List<Integer> deck;
ArrayList<ImageView> imager = new ArrayList<ImageView>();
private int roundCounter;
JButton button = new JButton();

@Override
public void start(Stage primaryStage) {
    loadDeck();
    loadCards();
    //Panes
    BorderPane bPain = new BorderPane();
    VBox vBox = new VBox(100);
    vBox.setPadding(new Insets(5, 5, 5, 5));
    HBox buttonBox = new HBox(100);
    buttonBox.setPadding(new Insets(25, 25, 25, 75));
    buttonBox.setStyle("-fx-background-color: blue");

    bPain.setLeft(new P1Pane("PLayer 1"));
    bPain.setRight(new P2Pane("PLayer 2"));
    BorderPane bPain2 = new BorderPane();
    bPain2.setRight(new P3Pane("PLayer 4"));
    bPain2.setLeft(new P4Pane("PLayer 3"));

    //VBox vBox2 = new VBox(100);
    //vBox2.setPadding(new Insets(5, 5, 5, 5));


    BorderPane bPain3 = new BorderPane();
    DeckPane dPane = new DeckPane("Deck");


    bPain3.setCenter(dPane);
    bPain3.setMargin(dPane, new Insets(5, 5, 5, 5));
    bPain3.setCenter(dPane);

    //Buttons
    Button pBtn = new Button("PLAY");
    Button dBtn = new Button("DEAL");
    Button endBtn = new Button("END GAME");
    buttonBox.getChildren().addAll(pBtn, dBtn , endBtn);

    //vBox.getChildren().add(buttonBox);
    vBox.getChildren().addAll(buttonBox, bPain, bPain3, bPain2);
    //vBox2.getChildren().add(bPain3);
    //vBox.getChildren().add(vBox2);
  /*
    pBtn.setOnAction(
            p -> {System.out.println("Play pressed");});

    dBtn.setOnAction(
            d -> {
                //deals remaining cards
                int[] wins=new int[4];
                wins[0]=0;wins[1]=0;
                wins[2]=0;wins[3]=0;

                System.out.println("Round: "+(roundCounter++));
                int prev=-1;
                int winner=1;
                for(int j=0;j<4;j++)
                {
                    System.out.println("Player "+(j+1)+" card: "+deck.get(0));
                    if(prev<deck.get(0))
                    {
                        winner=j+1;
                        prev=deck.get(0);
                    }
                    deck.remove(deck.get(0));
                }
                System.out.println("Winner is player: " +winner);
                System.out.println();
                wins[winner-1]++;
                //shuffle after each round


                //only enabled after play button and there are cards left
                System.out.println("Deal pressed");
            });

    endBtn.setOnAction(
            e -> {
                //when pressed, popup asks if sure
                //disabled after
                //resets number of wins
                System.out.println("End pressed");
            });
 */


    //Stage set
    primaryStage.setTitle("WAR!!!");
    //primaryStage.setScene(new Scene(vBox2, 100, 100));
    primaryStage.setScene(new Scene(vBox, 500, 500));

    primaryStage.show();
}

public void loadCards() {

    String path = "/users/ebrovski/Desktop/card";
    String files;
    File folder = new File(path);
    Image[] images = new Image[100];
    File[] listOfFiles = folder.listFiles();
    int j = 0;
    for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].getName().endsWith("png")) {
            System.out.println(listOfFiles[i].getAbsolutePath());

            files = "file:" + listOfFiles[i].getAbsolutePath();
            System.out.println(files);

            images[j] = new Image(files, 200, 200, true, true);

            j++;
        }
    }

    for(int k = 0; k < deck.size(); k++) {
        imager.add(new ImageView(images[deck.get(k)]));

    }
}



public void loadDeck() {
    deck = new ArrayList<Integer>();
    for(int i =0; i < 52; i++) {
        deck.add(i);
    }
    Collections.shuffle(deck);
}


//Player Panes
class P1Pane extends Pane {
    public P1Pane(String player) {
        Label playerTitle = new Label(player);
        getChildren().add(playerTitle);
        setStyle("-fx-border-color: black");
        //setStyle("-fx-background-color: green");
        setPadding(new Insets(75, 1, 1, 1));
        getChildren().add(imager.get(10));

    }
}

class P2Pane extends Pane {
    public P2Pane(String player) {
        Label playerTitle = new Label(player);
        getChildren().add(playerTitle);
        setStyle("-fx-border-color: black");
        //setStyle("-fx-background-color: green");
        setPadding(new Insets(75, 1, 1, 1));
        getChildren().add(imager.get(20));
    }
}
class P3Pane extends Pane {
    public P3Pane(String player) {
        Label playerTitle = new Label(player);
        getChildren().add(playerTitle);
        setStyle("-fx-border-color: black");
        //setStyle("-fx-background-color: green");
        setPadding(new Insets(75, 3, 3, 3));
        getChildren().add(imager.get(40));

    }
}

class P4Pane extends Pane {
    public P4Pane(String player) {
        Label playerTitle = new Label(player);
        getChildren().add(playerTitle);
        setStyle("-fx-border-color: black");
        //setStyle("-fx-background-color: green");
        setPadding(new Insets(75, 3, 3, 3));
        getChildren().add(imager.get(30));
    }
}


//Deck Pane
class DeckPane extends Pane {
    public DeckPane(String deckName) {
        Label deckTitle = new Label(deckName);
        getChildren().add(deckTitle);

        setStyle("-fx-border-color: black");
        //setStyle("-fx-background-color: forestgreen");
        setPadding(new Insets(75, 3, 3, 3));

    }
}
    /*
    public enum Suit {

SPADES(Color.BLACK, "\u2660"),
HEARTS(Color.RED, "\u2665"),
CLUBS(Color.BLACK, "\u2663"),
DIAMONDS(Color.RED, "\u2666"),
;

Color color;
String name;

Suit( Color color, String name) {
    this.color = color;
    this.name = name;
}

public Color getColor() {
    return color;
}

public String getName() {
    return name;
}
  }

     public enum Rank {

ACE( "A"),
_2( "2"),
_3("3"),
_4("4"),
_5("5"),
_6("6"),
_7("7"),
_8("8"),
_9("9"),
_10("10"),
JACK("J"),
QUEEN("Q"),
KING("K")
;

String name;

Rank( String name) {
    this.name = name;
}

public String getName() {
    return name;
}
 }

    class Card extends Pane {



Node frontFace;
Node backFace;

boolean isFaceUp;

double w = 60;
double h = 90;

Suit suit;
Rank rank;

public Card( Suit suit, Rank rank) {

    this.suit = suit;
    this.rank = rank;

    Image image = new Image("http://upload.wikimedia.org/wikipedia/commons/thumb/0/03/King_of_spades_fr.svg/123px-King_of_spades_fr.svg.png");
    ImageView iv1 = new ImageView();
     iv1.setImage(image);
     ImageView iv2 = new ImageView();
     iv2.setImage(image);
    frontFace = iv1;
    backFace = iv2;

    getChildren().addAll( frontFace, backFace);

    setFaceDown();
}

public void setFaceUp() {

    frontFace.setVisible(true);
    backFace.setVisible(false);

    isFaceUp = true;
}

public void setFaceDown() {

    frontFace.setVisible(false);
    backFace.setVisible(true);

    isFaceUp = false;
}

public boolean isFaceUp() {
    return isFaceUp;
}

public Suit getSuit() {
    return suit;
}

public Rank getRank() {
    return rank;
}


public String toString() {
    return suit + " " + rank;
}
*/

 }

There are many solutions for this. As example, I'll give you two of them.

  1. Create own class Card that include cardId variable and image variable.

    class Card() {

    int cardId; Image cardImage;

    }

    Add constructor, getters, setters.

  2. Extend Image class as CardImage

    class CardImage extends Image { int cardId; }

    Add constructor, call super constructor if needed, add getters and setters.

Here my examples. Main idea is to create Abstract CardItem with common methods, and then extend it for any type of cards. Then after I load all cards in Deck class, all my programm works with CardItem objects with. Each object has own image and rank number that assigned in the loading.

Class CardItem:

package classes;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;

@SuppressWarnings("serial")
public abstract class CardItem extends JButton implements Comparable<CardItem> {

    private int rank;
    ImageIcon cardIcon;
    ImageIcon coverIcon;

    public CardItem() {
        this.rank = 0;
    }

    /** Constructor, create card by image file */
    public CardItem(String fileName)
    {
        this();

        // Load images for two sides from resources
        URL url = ClassLoader.getSystemClassLoader().getResource(fileName);

        BufferedImage bi = null;
        try {
            bi = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Image resizedImage = bi.getScaledInstance(128, 186, 0);

        cardIcon = new ImageIcon(resizedImage);     

        setSize(cardIcon.getImage().getWidth(null), cardIcon.getImage().getHeight(null));
        setPreferredSize(new Dimension(128, 186));
        setIcon(cardIcon);
        setMargin(new Insets(0,0,0,0));
        setIconTextGap(0);
        setBorderPainted(false);
        setBorder(null);
        setText(null);

        /* Load cover */
        url = ClassLoader.getSystemClassLoader().getResource("cover.png");

        bi = null;
        try {
            bi = ImageIO.read(url);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        resizedImage = bi.getScaledInstance(128, 186, 0);

        coverIcon = new ImageIcon(resizedImage);        
    }

    /**
     *  Constructor. Create card by image file and rank
     * @param fileName as string
     * @param rank as integer
     */
    public CardItem(String fileName, int rank)
    {
        this(fileName);

        // Set rank
        this.rank = rank;
    }

    /**
     * Get card's rank
     * @return rank as integer
     */
    public int getRank()
    {
        return this.rank;
    }

    /**
     * Set card's rank
     * @param rank
     */
    public void setRank(int rank)
    {
        this.rank = rank;
    }

    /**
     * Compare two cards by it's rank
     */
    @Override
    public int compareTo(CardItem other) {
        return this.getRank() - other.getRank();
    }

    /**
     * Define which suit is the card 
     * @return rank as string
     */
    public abstract int getSuitValue();

    @Override
    public String toString() {
        return ("Suit: " + this.getSuitValue() + "; " +
        "Rank: " + this.getRank());
    }

    /**
     * Show card's cover side
     */
    public void showCover()
    {
        setSize(coverIcon.getImage().getWidth(null), coverIcon.getImage().getHeight(null));
        setPreferredSize(new Dimension(128, 186));
        setIcon(coverIcon);
        setMargin(new Insets(0,0,0,0));
        setIconTextGap(0);
        setBorderPainted(false);
        setBorder(null);
        setText(null);
    }

    /**
     * Show card's shape side
     */
    public void showCard()
    {
        setIcon(cardIcon);
    }
}

Class CardClubs:

package classes;

@SuppressWarnings("serial")
public class CardClubs extends CardItem {

    private final static int  SUIT_VALUE = 3;

    public CardClubs(String fileName) {
        super(fileName);
    }

    public CardClubs(String fileName, int i) {
        super(fileName, i);
    }

    /**
     * @return the SUIT_VALUE
     */
    @Override
    public int getSuitValue() {
        return SUIT_VALUE;
    }
}

Class CardDiamonds

package classes;

@SuppressWarnings("serial")
public class CardDiamonds extends CardItem {

    private final static int  SUIT_VALUE = 1;

    public CardDiamonds(String fileName) {
        super(fileName);
    }

    public CardDiamonds(String fileName, int i) {
        super(fileName, i);
    }

    /**
     * @return the SUIT_VALUE
     */
    @Override
    public int getSuitValue() {
        return SUIT_VALUE;
    }
}

Class Deck:

package classes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Deck {

    List<CardItem> cards;
    int cardsUsed;

    /**
     * Fill the deck with graphics cards
     */

    public Deck() {     
        this.cards = new ArrayList<CardItem>();
        this.cardsUsed = 0;

        // Fill Hearts
        for (int i = 2; i < 11; i++)
        {
            this.cards.add(new CardHearts(i+"_of_hearts.png", i));
        }

        // Fill clubs
        for (int i = 2; i < 11; i++)
        {
            this.cards.add(new CardClubs(i+"_of_clubs.png", i));
        }

        // Deck fill spades
        for (int i = 2; i < 11; i++)
        {
            this.cards.add(new CardSpades(i+"_of_spades.png", i));
        }

        // Fill diamonds
        for (int i = 2; i < 11; i++)
        {
            this.cards.add(new CardDiamonds(i+"_of_diamonds.png", i));
        }

        // Fill others cards
        String tp = "diamonds";
        this.cards.add(new CardDiamonds("king_of_"+tp.toString()+".png", 13));
        this.cards.add(new CardDiamonds("queen_of_"+tp.toString()+".png", 12));
        this.cards.add(new CardDiamonds("jack_of_"+tp.toString()+".png", 11));
        this.cards.add(new CardDiamonds("ace_of_"+tp.toString()+".png", 14));

        tp = "hearts";
        this.cards.add(new CardHearts("king_of_"+tp.toString()+".png", 13));
        this.cards.add(new CardHearts("queen_of_"+tp.toString()+".png", 12));
        this.cards.add(new CardHearts("jack_of_"+tp.toString()+".png", 11));
        this.cards.add(new CardHearts("ace_of_"+tp.toString()+".png", 14));

        tp = "clubs";
        this.cards.add(new CardClubs("king_of_"+tp.toString()+".png", 13));
        this.cards.add(new CardClubs("queen_of_"+tp.toString()+".png", 12));
        this.cards.add(new CardClubs("jack_of_"+tp.toString()+".png", 11));
        this.cards.add(new CardClubs("ace_of_"+tp.toString()+".png", 14));

        tp = "spades";
        this.cards.add(new CardSpades("king_of_"+tp.toString()+".png", 13));
        this.cards.add(new CardSpades("queen_of_"+tp.toString()+".png", 12));
        this.cards.add(new CardSpades("jack_of_"+tp.toString()+".png", 11));
        this.cards.add(new CardSpades("ace_of_"+tp.toString()+".png", 14));
    }

    /**
     * Shuffle all cards
     */
    public void shuffle()
    {
        Collections.shuffle(this.cards);
    }

    public int cardsLeft()
    {
        return this.cards.size();

    }

    public List<CardItem> getCards()
    {
        return this.cards;
    }

    /**
     * Remove random card
     * @return card as CardItem
     */
    public CardItem dealCard()
    {
        shuffle();

        CardItem dealCard = this.cards.get(this.cards.size()-1);

        this.cards.remove(dealCard);

        this.cardsUsed++;

        return dealCard;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM