Posted: Tue Jan 20, 2009 3:44 pm Post subject: AI in Java for a card game
Hey guys, i am still in process of learning java...but this forum rocks, and canada is awesome lol
i kinda need help, We(one of my friends and I) are working on a game called Dajm" you want't find any info about it on the net" we have the hole game working but we Don't know how to make an AI. If you have time and if you want to help us , it would be apritiated ... oh and we are planing to realest it on sourceForge. thanks in advence!!! I could provid the source code and rules !!!!
Sponsor Sponsor
DemonWasp
Posted: Tue Jan 20, 2009 4:01 pm Post subject: RE:AI in Java for a card game
What does your code look like? We don't necessarily need to see your code, but an idea of what objects you have, what the flow-of-control is like, an similar high-level information can help us point you in the right way.
If you are going to post code, use [ syntax = "java" ] [ / syntax ] , minus the spaces, to highlight your code properly.
yanko
Posted: Tue Jan 20, 2009 5:09 pm Post subject: Re: AI in Java for a card game
This is the card class
Java:
//////===========================================================////// ////// DAJM (Dime) ////// //////-----------------------------------------------------------////// ////// Card.java ////// ////// Version 0.41 Pre-Alpha ////// ////// January 11, 2009 Build ////// //////-----------------------------------------------------------////// ////// Copyright 2008-2009 Drew Burden, Yanko Petrovic ////// //////-----------------------------------------------------------////// ////// This file is part of Dajm. ////// ////// ////// ////// Dajm is free software: you can redistribute it and/or ////// ////// modify it under the terms of the GNU General Public ////// ////// License as published by the Free Software Foundation, ////// ////// either version 3 of the License, or (at your option) ////// ////// any later version. ////// ////// ////// ////// Dajm is distributed in the hope that it will be ////// ////// useful, but WITHOUT ANY WARRANTY; without even the ////// ////// implied warranty of MERCHANTABILITY or FITNESS FOR A ////// ////// PARTICULAR PURPOSE. See the GNU General Public ////// ////// License for more details. ////// ////// ////// ////// You should have received a copy of the GNU General ////// ////// Public License along with Dajm. If not, see ////// ////// <http://www.gnu.org/licenses/>. ////// //////===========================================================//////
Posted: Tue Jan 20, 2009 6:45 pm Post subject: Re: AI in Java for a card game
here is the cardTable class
Java:
//////===========================================================////// ////// DAJM (Dime) ////// //////-----------------------------------------------------------////// ////// CardTable.java ////// ////// Version 0.41 Pre-Alpha ////// ////// January 11, 2009 Build ////// //////-----------------------------------------------------------////// ////// Copyright 2008-2009 Drew Burden, Yanko Petrovic ////// //////-----------------------------------------------------------////// ////// This file is part of Dajm. ////// ////// ////// ////// Dajm is free software: you can redistribute it and/or ////// ////// modify it under the terms of the GNU General Public ////// ////// License as published by the Free Software Foundation, ////// ////// either version 3 of the License, or (at your option) ////// ////// any later version. ////// ////// ////// ////// Dajm is distributed in the hope that it will be ////// ////// useful, but WITHOUT ANY WARRANTY; without even the ////// ////// implied warranty of MERCHANTABILITY or FITNESS FOR A ////// ////// PARTICULAR PURPOSE. See the GNU General Public ////// ////// License for more details. ////// ////// ////// ////// You should have received a copy of the GNU General ////// ////// Public License along with Dajm. If not, see ////// ////// <http://www.gnu.org/licenses/>. ////// //////===========================================================//////
//================================================================ constants privatefinalColor BACK = Color.BLACK; // Used for redraw. privatefinalint TABLE_SIZE = 550; // Window width and height. *** CAUTION *** Changing this will screw up some stuff!
//=================================================================== variables //------- Initial image coords. privateint _initX = 0; // x coord - set from drag. privateint _initY = 0; // y coord - set from drag.
//------- Position in image of mouse press to make dragging look better privateint _dragFromX = 0; // Displacement inside image of mouse press. privateint _dragFromY = 0; // Displacement inside image of mouse press.
//------- Array location variables privateint _cardPlace = 0; // Place in the array of the current card. privateint _discardPlace = 0; // Place in the array of the current discard.
//------- X, Y Positions privateint n = 0; // Which card in the array (array position). privateint xPos = 0, yPos = 0; // Where it should be placed initially. privateint _oldX = 0, _oldY = 0; // Used for snapping the card back into place. privateint _X1, _X2, _Y1, _Y2; // For placing the rearranged cards.
//------- Deck Initialization Variables privateString suits = "shdc"; // Holds all the suits in a string (each one char long). privateString faces = "a23456789tjqk"; // Holds all the face values in a string (each one char long). privateint _suitval; // Used to plug into the Card creator for returning a value later (checkDajm method). privateint _faceval; // Used to plug into the Card creator for returning a value later (checkDajm method). privateString _prompt = "new"; // Which text do we display at the bottom of the screen? It's a string to limit confusion. privateboolean _chip = false; // Is this the first time for the current round that we are painting the dealer chip? privateint _round = 3; // Not the round we are in, but rather the amount of cards that each player has... // (it starts at 3 since the dealing function adds one to the variable right at the start.
//------- Setup Various Decks private Card[] _deck = new Card[54]; // Main Deck pefectly organized (not shuffled and never to be shuffled itself!). private Card[] _handp1 = new Card[14]; // Player's hand (14 available cards: 13 for the last round plus 1 extra for drawing from the deck). private Card[] _handc1 = new Card[14]; // Computer's hand (14 available cards: 13 for the last round plus 1 extra for drawing from the deck). private Card[] _misc = new Card[3]; // The miscellaneous cards such as the card backs, the draw pile, and the discard pile outline. private Card[] _rearrange = new Card[2]; // Used to store temporary cards for rearranging. privateint[] _rearrangePlace = newint[2]; // Used to store the place in the array that the card was taken from (for rearranging). private Card[] _discard = new Card[54]; // Contains all cards that are discarded. private Card _temp; // Holds various temporary cards for movement between decks or whatever. private Card _dragging; // Only here so the card that is being dragged is drawn on top of everything else. private Card _currentCard = null; // Used for reference between functions so we know what card is currently being acted upon. private Card _currentDiscard = null; // Used for reference between functions with relation to the discard pile. privateboolean _yourTurn = false; // Can you (the player) do anything? If true, then yes. privateint[] _numSuits = newint[4]; // Used when checking for Dajm... Aligned with the suits string. (shdc) privateint[] _numFaces = newint[13]; // Used when checking for Dajm... Aligned with the faces string. (a23456789tjqk) privateint _numWilds = 0; // Used when checking for Dajm... How many wild cards?
//------- Misc. ClassLoader cldr = this.getClass().getClassLoader(); // ClassLoader is used to get images from a jar file. privateRandom rand = newRandom(); // Random number generator. Used for dealing cards randomly from the organized deck. privateint randomdeal = 0; // Position in the deck to get the card from. privateString imagePath; // Relative path to images. privateURL imageURL; // Variable to plug into the class loader. privateImageIcon img; // The actual image that we use to draw to the screen (using a method).
//============================================================== constructor public CardTable(){ //... Initialize graphics
setPreferredSize(newDimension(TABLE_SIZE, TABLE_SIZE));
// Check to see who the dealer is... // The computer always starts out as the dealer, so this // means if _round is even, the computer is the dealer. if((_round % 2) == 0){ // _round is even if(_chip){
_yourTurn = true;
_prompt = "draw";
_chip = false;
} // Paint the dealer chip by the computer
img.paintIcon(this, g, 50, 65);
} else{ // _round is odd if(_chip){
_yourTurn = false;
_prompt = "computer";
_chip = false;
} // Paint the dealer chip by the player
img.paintIcon(this, g, 50, 420);
} }
// Draw the table background image... // Because we do this, we don't really need the code directly above // this, but I like to have it there just in case the window is sized // differently on different operating systems, that way it makes it look // a little less ugly.
imagePath = "img/back.png";
imageURL = cldr.getResource(imagePath);
img = newImageIcon(imageURL);
img.paintIcon(this, g, (getWidth() / 2 - img.getIconWidth() / 2), (getHeight() / 2 - img.getIconHeight() / 2));
// Have we started the game yet? if(_round > 3){ // Draw all all misc cards (discard outline, draw deck, etc). for(Card m : _misc){ if(m != null && m.shouldDisplay())
m.draw(g, this);
}
// Display the cards, starting with the first array element. // *** The array order defines the z-axis depth. The lower the array number, the closer to the table. *** for(Card c : _handc1){ if(c != null && c.shouldDisplay())
c.draw(g, this);
} for(Card p : _handp1){ if(p != null && p.shouldDisplay())
p.draw(g, this);
}
// Display the current card that is being dragged, if any. if(_dragging != null && _dragging.shouldDisplay())
_dragging.draw(g, this);
// Paint the dealer chip
paintChip(g);
}
// Paint the helper text at the bottom.
paintPrompt(g);
}
//====================================================== method mousePressed publicvoid mousePressed(MouseEvent e){ if(_yourTurn){ int x = e.getX(); // Save the x coord of the click. int y = e.getY(); // Save the y coord of the click.
// Find card image this is in. Check from top down.
_currentCard = null; // Assume not in any image.
_cardPlace = -1;
// Found, remember this card for dragging.
_dragFromX = x - _dragging.getX(); // how far from left.
_dragFromY = y - _dragging.getY(); // how far from top.
_currentCard = _dragging; // Remember what we're dragging.
_oldX = _currentCard.getX();
_oldY = _currentCard.getY();
_cardPlace = crd;
break; // Stop when we find the first match. } } }
//============================================================= mouseDragged publicvoid mouseDragged(MouseEvent e){ // First, we need to make sure it's the player's turn. if(_yourTurn){ if(_currentCard != null && _currentCard.isMoveable()){// Non-null if pressed inside card image.
int newX = e.getX() - _dragFromX;
int newY = e.getY() - _dragFromY;
// Don't move the image off the screen sides
newX = Math.max(newX, 0);
newX = Math.min(newX, getWidth() - _currentCard.getWidth());
// Don't move the image off top or bottom
newY = Math.max(newY, 0);
newY = Math.min(newY, getHeight() - _currentCard.getHeight());
_currentCard.moveTo(newX, newY);
this.repaint(); // Repaint because position changed. (Called rapidly!) } } }
//======================================================= method mouseReleased publicvoid mouseReleased(MouseEvent e){ // Make sure it's the player's turn. if(_yourTurn){ if(_currentCard != null){// Non-null if dragging.
int x = e.getX(); // Save the x coord of the release. int y = e.getY(); // Save the y coord of the release.
// Did we try to discard, and if we did, are we at the discard stage? if(_misc[0].contains(x, y) && _prompt.equals("discard")){
_currentCard.moveTo(150, 210);
// If we discarded, then it must be the computer's turn.
_prompt = "computer";
_yourTurn = false;
_dragging = null;
// Bump all the cards down in the array so they are next to each other on the table. if(_cardPlace != -1){
_handp1[_cardPlace] = null;
for(int crd = _cardPlace; crd <= _handp1.length-2; crd++){ if(_handp1[crd] == null && _handp1[(crd+1)] != null){
_handp1[crd] = _handp1[crd+1];
_handp1[crd+1] = null;
_handp1[crd].moveTo(_handp1[crd].getX()-20, _handp1[crd].getY());
} } } } else{ // Snap the card back to the previous position.
_handp1[_cardPlace] = _dragging;
_handp1[_cardPlace].moveTo(_oldX, _oldY);
_dragging = null;
}
this.repaint(); // Repaint because position changed. } } }
//======================================================= method mouseClicked publicvoid mouseClicked(MouseEvent e){ if(_yourTurn){ int x = e.getX(); // Save the x coord of the click int y = e.getY(); // Save the y coord of the click
// Is the user trying to get a card from the deck? if(_misc[1].contains(x, y) && _handp1[_round] == null){
drawCard();
} // Is the user trying to get a card from the discard pile? elseif(_misc[0].contains(x, y)){
drawDiscard();
} // Rearranging cards. elseif(_currentCard != null && _currentCard.getY() > 385){
_oldX = _currentCard.getX();
_oldY = _currentCard.getY();
_currentCard.moveTo(_currentCard.getX(), _currentCard.getY() - 20);
_currentCard.setMoveable(false);
Posted: Tue Jan 20, 2009 6:48 pm Post subject: Re: AI in Java for a card game
here is the main() Dajm class
Java:
//////===========================================================////// ////// DAJM (Dime) ////// //////-----------------------------------------------------------////// ////// Dajm.java ////// ////// Version 0.41 Pre-Alpha ////// ////// January 11, 2009 Build ////// //////-----------------------------------------------------------////// ////// Copyright 2008-2009 Drew Burden, Yanko Petrovic ////// //////-----------------------------------------------------------////// ////// This file is part of Dajm. ////// ////// ////// ////// Dajm is free software: you can redistribute it and/or ////// ////// modify it under the terms of the GNU General Public ////// ////// License as published by the Free Software Foundation, ////// ////// either version 3 of the License, or (at your option) ////// ////// any later version. ////// ////// ////// ////// Dajm is distributed in the hope that it will be ////// ////// useful, but WITHOUT ANY WARRANTY; without even the ////// ////// implied warranty of MERCHANTABILITY or FITNESS FOR A ////// ////// PARTICULAR PURPOSE. See the GNU General Public ////// ////// License for more details. ////// ////// ////// ////// You should have received a copy of the GNU General ////// ////// Public License along with Dajm. If not, see ////// ////// <http://www.gnu.org/licenses/>. ////// //////===========================================================//////
////////////////////////////////////////////////////////////// class Dajm class Dajm extendsJFrame{
publicstaticString _progVersion = "Pre-Alpha"; // Alpha? Beta? RC1? RC2? etc... publicstaticdouble _buildVersion = 0.41; // Basic version publicstaticString _buildDate = "January 11, 2009"; // Build date publicstatic CardTable table;
publicstaticJFrame _about; // About dialog publicstaticJFrame _main; // Main window publicstaticJMenuBar _menuBar; // The menu bar itself publicstaticJMenu _menu; // The actual menus (reused) publicstaticJMenuItem _newMenu; // The new menu item publicstaticJMenuItem _exitMenu; // The exit menu item publicstaticJMenuItem _aboutMenu; // The about menu item publicstaticClassLoader cldr = Dajm.class.getClassLoader(); // ClassLoader is used to get images from a jar file. publicstaticURL imageURL; // Variable to plug into the class loader.
//===================================================================== main publicstaticvoid main(String[] args){
createMainFrame();
createAboutFrame();
}
// Basically sets up all the cards for the GUI and handles // them the entire length of the program. Most of the // program is run inside the CardTable class.
table = new CardTable();
_main.setContentPane(table);
// Create and add the menu to the frame
createMenu();
_main.setJMenuBar(_menuBar);
// Essentially, this all displays the window
_main.pack();
_main.setLocationRelativeTo(null);
_main.setResizable(false);
_main.setVisible(true);
}
//===================================================================== createAboutFrame publicstaticvoid createAboutFrame(){
imageURL = cldr.getResource("img/logo.png");
JLabel logoImg = newJLabel(newImageIcon(imageURL));
JLabel version = newJLabel(" v" + _buildVersion + " " + _progVersion + " - " + _buildDate + " build");
imageURL = cldr.getResource("img/gnugpl.png");
JLabel gnugplImg = newJLabel(newImageIcon(imageURL));
JLabel copyright = newJLabel("Copyright 2008-2009 Drew Burden, Yanko Petrovic");
JButton ok = newJButton("Close");
ok.setActionCommand("close");
ok.addActionListener(actionListener);
JTextArea gnu = newJTextArea("Dajm is free software: you can redistribute it and/or modify it " +
"under the terms of the GNU General Public License as published by the " +
"Free Software Foundation, either version 3 of the License, or (at your " +
"option) any later version.\n\n" +
"Dajm is distributed in the hope that it will be useful, but WITHOUT ANY " +
"WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS " +
"FOR A PARTICULAR PURPOSE. See the GNU General Public License for more " +
"details.\n\n" +
"You should have received a copy of the GNU General Public License along " +
"with Dajm. If not, see <http://www.gnu.org/licenses/>");
gnu.setMargin(newInsets(5,5,5,5));
gnu.setLineWrap(true);
gnu.setWrapStyleWord(true);
gnu.setEditable(false);
// Essentially, this all displays the window
_about.pack();
_about.setLocationRelativeTo(null);
_about.setResizable(false);
_about.setVisible(false);
}
//===================================================================== createMenu publicstaticvoid createMenu(){ // Create the menu bar.
_menuBar = newJMenuBar();
// Create File Menu
_menu = newJMenu("File");
_menu.setMnemonic(KeyEvent.VK_F);
_menuBar.add(_menu);
Posted: Wed Jan 21, 2009 8:32 am Post subject: RE:AI in Java for a card game
no one has an idea?
DemonWasp
Posted: Wed Jan 21, 2009 9:09 am Post subject: RE:AI in Java for a card game
Keep in mind that most of us are only online during work / school hours.
Your CardTable class appears to be handling both display concerns and game-rules concerns. My brief scan of the code makes it seem like your human player does all their actions by interacting with that, which doesn't lend itself to playing as an AI.
To add an AI, you should probably think about turning user interactions into some kind of Action, which is then immediately issued. The AI could just create the actions itself, on its turn.
I could give a more in-depth discussion if I knew how the game was played.
yanko
Posted: Wed Jan 21, 2009 9:03 pm Post subject: Re: AI in Java for a card game
While i appreciate your suggestion,
by doing what you have suggested, it
will only serve as a convenience, but not really
a necessity when it comes to creating our AI.
Sponsor Sponsor
A.J
Posted: Wed Jan 21, 2009 10:32 pm Post subject: Re: AI in Java for a card game
First of all yanko, please attach your code as an attachment as opposed to posting all of it........
As for making an AI, you should keep in mind 2 main things necessary in building an AI of any sort:
1) Your Artificial Intelligence's brain (i.e. the class in charge of computing the AI's moves) must first be structured.
2) You must then decide what algorithm is to be used by the AI to compute the best possible move given a state of the game. This can either be merely pruning every possible move the AI can make (if this is the case, my suggestion is alpha-beta pruning), or it can be following a specific strategy (like for instance in a game like NIM).
After doing this, then you should start structuring other methods that will aid in the thinking/pruning and the performing of the move in the game by the AI
If you can provide me with a brief description of the game, I'll be glad to help in finding an algorithm that suits this particular game.
yanko
Posted: Thu Jan 22, 2009 6:00 pm Post subject: RE:AI in Java for a card game
If you want me to repost the src file let me know? and here is the rules for the game.....
Dajm(dime)
1. Game starts with 2 players."Players .vs.Pc"
2. The program deals the cards to Pc and to Player
until the Pc and player have each 4 cards, also it
leaves one card uncovered on the discard pile.
Since Pc dealt, the player plays first.
3. 4 cards now has Player (fours of any suit are the wild cards
for the round). Next round is 5 cards. Then the
fives of any suit are the wild cards. The rounds go all the way
up to 13 cards (where the kings are wild).
4. Player has to put together at least 3 cards of the same
face value (depending on what round you're in), or they
can get a straight with all of the same suit.
ex.; H8 H9 H10 -> Ok!
H8 A4 H10 -> ok! (4 of any kind is a wild card)
H8 D9 H10 -> not ok.
5. The player and Pc can draw from the deck or from the discard pile
and then they must discard. For example:
On the round of 4 cards, you draw from the discard pile (one
card is turned up onto the discard at the beginning) and you
now have 5 cards. You must now discard to bring your cards
back down to 4 cards.
6. Lastly, you can call Dajm only before you discard since discarding
signifies the end of your turn.
A.J
Posted: Thu Jan 22, 2009 7:52 pm Post subject: Re: AI in Java for a card game
this is (in my opinion) pretty easy to come up with an algorithm.
all u have to do is take the card on the discard pile and search and see how 'valuable' it is to your current hand
if yes, then take it, if not then use EV (expected value) to calculate the probability of getting a card from the deck that'll help you
so, make an evaluation function that returns how 'valuable' a card given the card you have in you hand
that should make thing a lot easier
so start off by making an evaluation function (which should probably be the most 'challenging' part for you)
If I make am of no use AT ALL to you (which I can be at times....), please ignore me.......
however, if you do need help, it'll be my pleasure in continuing this small 'tutorial'
yanko
Posted: Thu Jan 22, 2009 9:58 pm Post subject: RE:AI in Java for a card game
but how??
how am I supposed to check the player's or computer's hand to see if they have dajm?
and please , put it in a code like way!!??
A.J
Posted: Thu Jan 22, 2009 10:30 pm Post subject: Re: AI in Java for a card game
I am not going to code it out for you........
it is pretty simple, just store the cards in an array (for both the AI and the player alike) and just manually check.
don't check for a Dajm, but rather evaluate your hand and check how valuable a card can be to a particular hand by means of checking how much closer to a dajm you are.
I am saying all of this under the impression that a Dajm is like having some sort of poker hand (like straight or something)
even if i am mistaken, this approach should work
yanko
Posted: Fri Jan 23, 2009 11:51 am Post subject: RE:AI in Java for a card game
Well, thankx for your help, we ll try to...
and if anyone can really help us , please do ! thankx
A.J
Posted: Fri Jan 23, 2009 2:27 pm Post subject: Re: AI in Java for a card game
k, I don't mind helping you, it is just that I have exams now......
I'll try helping you after that though