public class Game extends JPanel implements KeyListener {
Image cardImage;
Deck deck;
Card[] communityCards;
public Card[][] playerCards;
int cardsDealt;
public Game() {
addKeyListener(this); // Tells Game object to listen for keyboard input
}
public void startGame() { // Main game loop
deck = new Deck(); <----------------- If I initialize Deck and Card[] here, paintComponent returns nonsense results (like dozens of cards being printed on the screen randomly)
communityCards = new Card[0];
while(cardsDealt >= 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException x) { }
//cardsDealt++;
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("" + deck.cards[0].rank, 200, 500);
communityCards = ERS.dealCards(communityCards, deck, cardsDealt);
paintCards(g, communityCards, 50, 50);
}
public Card[] dealCards(Card[] cards, Deck deck, int num) { // 'num' is number of cards to deal
for (int i = 0; i < num; i++) { // Deals x number of random cards
int rand = (int)(Math.random() * (deck.cards.length - i));
cards = ArrayHelper.addCard(cards, deck.cards[rand]);
deck.cards = ArrayHelper.deleteCard(deck.cards, deck.cards[rand]);
}
return cards;
}
public void paintCards(Graphics g, Card[] cards, int x, int y) {
Toolkit tool = Toolkit.getDefaultToolkit();
for (int i = 0; i < cards.length; i++) { // Draws the dealt cards
String filename = "card" + cards[i].imageNum + ".png";
cardImage = tool.getImage(filename);
g.drawImage(cardImage, x + 80 * i, y, this);
}
}
public void keyReleased(KeyEvent evt) { } // Keyboard events
public void keyPressed(KeyEvent evt) { // Keyboard events
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
//cardsDealt++;
repaint();
}
}
public void keyTyped(KeyEvent evt) { } // Keyboard events
}
While the program works if I do something like this:
public void paintComponent(Graphics g) {
deck = new Deck(); <----------------- If I initialize it here instead, it works fine
communityCards = new Card[0];
super.paintComponent(g);
g.drawString("" + deck.cards[0].rank, 200, 500);
communityCards = ERS.dealCards(communityCards, deck, cardsDealt);
paintCards(g, communityCards, 50, 50);
}
It's not an optimal solution, because every time I call repaint() it creates an entirely new deck. I need the same deck to last for the whole game. I'm a pretty new programmer so I'm still trying to wrap my head fully around OOP and how scope works. Thanks for your help!


Sign In
Create Account

Back to top









