Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 AI in Java for a card game
Index -> Programming, Java -> Java Help
Goto page 1, 2  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
yanko




PostPosted: 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
Sponsor
sponsor
DemonWasp




PostPosted: 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




PostPosted: 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/>.                         //////
//////===========================================================//////

// Best viewed in Notepad++

import java.awt.*;
import javax.swing.*;

/////////////////////////////////////////////////////////////////////////// Card
class Card {
    //=================================================================== fields
    private ImageIcon   _image;
        private int         _suit;
        private int         _face;
        private boolean         _moveable;
        private boolean         _display;
    private int   _x;
    private int                 _y;
   
    //============================================================== constructor
    public Card(ImageIcon image, int suit, int face, boolean moveable, boolean display) {
        _image    = image;
                _suit      = suit;
                _face      = face;
                _moveable       = moveable;
                _display        = display;
    }
       
        //=================================================================== setImg
    public void setImg(ImageIcon image) {
        _image = image;
    }
   
    //=================================================================== moveTo
    public void moveTo(int x, int y) {
        _x = x;
        _y = y;
    }
   
    //================================================================= contains
    public boolean contains(int x, int y) {
        return (x > _x && x < (_x + getWidth()) &&
                y > _y && y < (_y + getHeight()));
    }
   
    //================================================================= getWidth
    public int getWidth() {
        return _image.getIconWidth();
    }
   
    //================================================================ getHeight
    public int getHeight() {
        return _image.getIconHeight();
    }
   
    //===================================================================== getX
    public int getX() {
        return _x;
    }
   
    //===================================================================== getY
    public int getY() {
        return _y;
    }
       
        //===================================================================== getSuit
        public int getSuit() {
        return _suit;
    }
       
        //===================================================================== getFace
        public int getFace() {
        return _face;
    }
       
        //===================================================================== setMoveable
        public void setMoveable(boolean moveable) {
        _moveable = moveable;
    }
       
       
        //===================================================================== isMoveable
        public boolean isMoveable() {
        return _moveable;
    }
       
        //===================================================================== shouldDisplay
        public boolean shouldDisplay() {
        return _display;
    }
   
    //===================================================================== draw
    public void draw(Graphics g, Component c) {
        _image.paintIcon(c, g, _x, _y);
    }
}


////////////////////////////
//////////  EOF   //////////
////////////////////////////




Edit: Code tag
code:
[syntax="java"]code here[/syntax]
yanko




PostPosted: 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/>.                         //////
//////===========================================================//////

// Best viewed in Notepad++

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.URL;
import java.util.Random;

////////////////////////////////////////////////////////////////////// CardTable
public class CardTable extends JComponent implements MouseListener, MouseMotionListener {
   
    //================================================================ constants
    private final Color BACK = Color.BLACK;          // Used for redraw.
    private final int   TABLE_SIZE = 550;              // Window width and height. *** CAUTION *** Changing this will screw up some stuff!
   

       
    //=================================================================== variables
    //------- Initial image coords.
    private int _initX     = 0;                           // x coord - set from drag.
    private int _initY     = 0;                           // y coord - set from drag.
   
       
    //------- Position in image of mouse press to make dragging look better
    private int _dragFromX = 0;     // Displacement inside image of mouse press.
        private int _dragFromY = 0;                         // Displacement inside image of mouse press.

               
        //------- Array location variables
        private int _cardPlace = 0;                         // Place in the array of the current card.
        private int _discardPlace = 0;        // Place in the array of the current discard.
       
               
        //------- X, Y Positions
        private int n = 0;                                  // Which card in the array (array position).
        private int xPos = 0, yPos = 0;    // Where it should be placed initially.
        private int _oldX = 0, _oldY = 0;                     // Used for snapping the card back into place.
        private int _X1, _X2, _Y1, _Y2;    // For placing the rearranged cards.
       
       
        //------- Deck Initialization Variables
        private String suits = "shdc";        // Holds all the suits in a string (each one char long).
        private String faces = "a23456789tjqk";  // Holds all the face values in a string (each one char long).
        private int _suitval;                  // Used to plug into the Card creator for returning a value later (checkDajm method).
        private int _faceval;                  // Used to plug into the Card creator for returning a value later (checkDajm method).
        private String _prompt = "new";    // Which text do we display at the bottom of the screen? It's a string to limit confusion.
        private boolean _chip = false;        // Is this the first time for the current round that we are painting the dealer chip?
        private int _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.
        private int[] _rearrangePlace = new int[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.
        private boolean _yourTurn = false;                  // Can you (the player) do anything? If true, then yes.
        private int[] _numSuits = new int[4];      // Used when checking for Dajm... Aligned with the suits string. (shdc)
        private int[] _numFaces = new int[13];    // Used when checking for Dajm... Aligned with the faces string. (a23456789tjqk)
        private int _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.
        private Random rand = new Random();               // Random number generator. Used for dealing cards randomly from the organized deck.
        private int randomdeal = 0;                         // Position in the deck to get the card from.
        private String imagePath;                                   // Relative path to images.
        private URL imageURL;                  // Variable to plug into the class loader.
        private ImageIcon img;            // The actual image that we use to draw to the screen (using a method).
       
   
       
    //============================================================== constructor
    public CardTable() {
        //... Initialize graphics
        setPreferredSize(new Dimension(TABLE_SIZE, TABLE_SIZE));
       
        //... Add mouse listeners.
        addMouseListener(this);
        addMouseMotionListener(this);
    }
       
        //=========================================================== resetCheckDajmVars();
        public void resetCheckDajmVars() {
               
                // THIS FUNCTION IS INCOMPLETE!
               
                _numSuits[0] = 0;
                _numSuits[1] = 0;
                _numSuits[2] = 0;
                _numSuits[3] = 0;
                _numFaces[0] = 0;
                _numFaces[1] = 0;
                _numFaces[2] = 0;
                _numFaces[3] = 0;
                _numFaces[4] = 0;
                _numFaces[5] = 0;
                _numFaces[6] = 0;
                _numFaces[7] = 0;
                _numFaces[8] = 0;
                _numFaces[9] = 0;
                _numFaces[10] = 0;
                _numFaces[11] = 0;
                _numFaces[12] = 0;
                _numWilds = 0;
        }
       
        //=========================================================== checkDajm
        public void checkDajm() {
               
                // THIS FUNCTION IS INCOMPLETE!
               
                resetCheckDajmVars();
               
                for (int x = 0; x < _round; x++) {
                        if (_handp1[x].getSuit() != 5)
                                _numSuits[_handp1[x].getSuit()]++;
                        if (_handp1[x].getFace() != 14 && _handp1[x].getFace() != _round)
                                _numFaces[_handp1[x].getFace()-1]++;
                        else
                                _numWilds++;
                       
                        if (_handp1[x].getFace() != 14 && _handp1[x].getSuit() != 5 && _handp1[x].getFace() == _round)
                                _numSuits[_handp1[x].getSuit()]--;
                }
               
                for (int x = 0; x < 4; x++) {
                        if (_numSuits[x] == _round || _numSuits[x] == 13) {
                                callDajm();
                                break;
                        }
                        else if (_numSuits[x] > 2 && _numWilds > 0) {
                                callDajm();
                                break;
                        }
                }
                for (int x = 0; x < 13; x++) {
                        if (_numFaces[x] == 4) {
                                callDajm();
                                break;
                        }
                        else if (_numFaces[x] > 2 && _numWilds > 0) {
                                callDajm();
                                break;
                        }
                }
        }
       
        //=========================================================== callDajm
        public void callDajm() {
               
                // THIS FUNCTION IS INCOMPLETE!
               
                System.out.println("DAJM!");
                nextRound();
        }
       
        //=========================================================== newGame
        public void newGame() {
                _yourTurn = true;
                _round = 3;
                _chip = false;
                nextRound();
        }
       
        //=========================================================== nextRound
        public void nextRound() {
                _round++;
                resetVars();
                setupMainDeck();
                setupSecDecks();
                dealPlayer(_round);
                dealComputer(_round);
                _chip = true;
        }
       
        //=========================================================== resetVars
        public void resetVars() {
                n = 0;
                _prompt = "draw";
               
                for (int x = 0; x < 54; x++) {
                        _deck[x] = null;
                        _discard[x] = null;
                }
                for (int x = 0; x < 14; x++) {
                        _handp1[x] = null;
                        _handc1[x] = null;
                }
        }
       
        //=========================================================== setupMainDeck
        public void setupMainDeck() {
                for (int suit=0; suit < suits.length(); suit++) {
                        for (int face=0; face < faces.length(); face++) {
                                //... Get the image from the images subdirectory.
                                imagePath = "img/" + suits.charAt(suit) +
                                                        faces.charAt(face) + ".png";
                                imageURL = cldr.getResource(imagePath);
                                img = new ImageIcon(imageURL);
                               
                                _suitval = suit;
                                _faceval = face;
                               
                                //... Create a card and add it to the deck.
                                Card card = new Card(img, _suitval, _faceval+1, true, true);
                                _deck[n] = card;

                                n++;
                        }
        }
               
               
                // Blue Joker.
                imagePath = "img/jb.png";
        imageURL = cldr.getResource(imagePath);
                img = new ImageIcon(imageURL);
                Card joker1 = new Card(img, 5, 14, true, true);
                _deck[n] = joker1;
                n++;
               
                // Red Joker.
                imagePath = "img/jr.png";
        imageURL = cldr.getResource(imagePath);
                img = new ImageIcon(imageURL);
                Card joker2 = new Card(img, 5, 14, true, true);
                _deck[n] = joker2;
        }
       
        //=========================================================== setupSecDecks
        public void setupSecDecks() {
               
                //Discard pile outline.
                imagePath = "img/outline.png";
        imageURL = cldr.getResource(imagePath);
                img = new ImageIcon(imageURL);
                Card outline = new Card(img, -1, -1, false, true);
        outline.moveTo(150, 210);
                _misc[0] = outline;
               
                // Deck you draw from.
                imagePath = "img/pile.png";
        imageURL = cldr.getResource(imagePath);
                img = new ImageIcon(imageURL);
                Card pile = new Card(img, -1, -1, false, true);
        pile.moveTo(325, 205);
                _misc[1] = pile;
               
                // Red deck back (for displaying the computer's cards on screen).
                imagePath = "img/b.png";
        imageURL = cldr.getResource(imagePath);
                img = new ImageIcon(imageURL);
                Card discard = new Card(img, -1, -1, false, false);
                _misc[2] = discard;
        }
       
        //=========================================================== dealPlayer
        public void dealPlayer(int cards) {
                xPos = 120;
                yPos = 388;
                               
                for (int x = 0; x < cards; x++) {
                        while (true) {
                                randomdeal = rand.nextInt(54);
                               
                                if (_deck[randomdeal] != null) {
                                        _handp1[x] = _deck[randomdeal];
                                        _handp1[x].moveTo(xPos, yPos);
                                        _deck[randomdeal] = null;
                                        break;
                                }
                        }
                        xPos += 20;
                }
               
                // Flip a card over onto the discard pile
                while (true) {
                        randomdeal = rand.nextInt(54);
                       
                        if (_deck[randomdeal] != null) {
                                _discard[0] = _deck[randomdeal];
                                _discard[0].moveTo(150, 210);
                                _deck[randomdeal] = null;
                                break;
                        }
                }
        }
       
        //=========================================================== dealComputer
        public void dealComputer(int cards) {
                xPos = 120;
                yPos = 30;
                               
                for (int x = 0; x < cards; x++) {
                        while (true) {
                                randomdeal = rand.nextInt(54);
                               
                                if (_deck[randomdeal] != null) {
                                        _handc1[x] = _deck[randomdeal];
                                        _handc1[x].moveTo(xPos, yPos);
                                       
                                        imagePath = "img/b.png";
                                        imageURL = cldr.getResource(imagePath);
                                        img = new ImageIcon(imageURL);
                                        _handc1[x].setImg(img);
                                        _deck[randomdeal] = null;
                                        break;
                                }
                        }
                        xPos += 20;
                }
        }
       
        //=========================================================== drawCard
        public void drawCard() {
                while (true) {
                        randomdeal = rand.nextInt(54);
                       
                        if (_deck[randomdeal] != null) {
                                _handp1[_round] = _deck[randomdeal];
                                _handp1[_round].moveTo(_handp1[_round-1].getX() + 20, _handp1[_round-1].getY());
                                _deck[randomdeal] = null;
                                break;
                        }
                }              
                _prompt = "discard";

                this.repaint();
               
        }
       
        //=========================================================== drawDiscard
        public void drawDiscard() {
                for (int crd=_discard.length-1; crd>=0; crd--) {
                        if (_discard[crd] != null) {
                                Card testCard = _discard[crd];
                                _discard[crd] = null;
                                //... Found, remember this card for dragging.
                                _handp1[_round] = testCard;  // Remember what we're dragging.
                                _handp1[_round].moveTo(_handp1[_round-1].getX() + 20, _handp1[_round-1].getY());
                                _discardPlace = crd;
                                _prompt = "discard";
                                this.repaint();
                                break;        // Stop when we find the first match.
                        }
                }
               
        }
       
        //=========================================================== paintPrompt
    public void paintPrompt(Graphics g) {
               
                // Draw a little helper text at the bottom telling the
                // player what stage of their turn they are in.
                if (_prompt == "computer") {
                        imagePath = "img/prmpt-computer.png";
                        checkDajm();
                }
                else if (_prompt == "discard") {
                        imagePath = "img/prmpt-discard.png";
                }
                else if (_prompt == "draw") {
                        imagePath = "img/prmpt-draw.png";
                }
                else if (_prompt == "new") {
                        imagePath = "img/prmpt-new.png";
                }
        imageURL = cldr.getResource(imagePath);
                img = new ImageIcon(imageURL);
                img.paintIcon(this, g, (getWidth() / 2 - img.getIconWidth() / 2), (getHeight() - 40));
    }
       
        //=========================================================== paintChip
    public void paintChip(Graphics g) {  
                // Dealer chip
                imagePath = "img/d.png";
        imageURL = cldr.getResource(imagePath);
                img = new ImageIcon(imageURL);
               
                // 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);
                }
    }
       
    //=========================================================== paintComponent
    @Override
    public void paintComponent(Graphics g) {
        // Paint background.
        int width = getWidth();
        int height = getHeight();
        g.setColor(BACK);
        g.fillRect(0, 0, width, height);
               
                // 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 = new ImageIcon(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);
                        }
                       
                        for (Card d : _discard) {
                                if (d != null && d.shouldDisplay())
                                        d.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
    public void 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;
                               
                        for (int crd=_round; crd>=0; crd--) {
                                if (_handp1[crd] != null) {
                                        Card testCard = _handp1[crd];
                                        if (testCard.contains(x, y)) {
                                                _dragging = testCard;
                                                _handp1[crd] = null;
                                               
                                                // 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.
                                        }
                                }
                        }
                       
                        if (_misc[1].contains(x, y) && _handp1[_round] == null) {
                                drawCard();
                        }
                        else if (_misc[0].contains(x, y)) {
                                drawDiscard();
                        }
                }
               
    }
   
    //============================================================= mouseDragged
    public void 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
        public void 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);
                                       
                                        for (int crd = 0; crd <= _round; crd++) {
                                                if (_discard[crd] == null) {
                                                        _discard[crd] = _dragging;
                                                        break;
                                                }
                                        }
                                       
                                        // 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
        public void 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?
                        else if (_misc[0].contains(x, y)) {
                                drawDiscard();
                        }
                        // Rearranging cards.
                        else if (_currentCard != null && _currentCard.getY() > 385) {
                                _oldX = _currentCard.getX();
                                _oldY = _currentCard.getY();
                                _currentCard.moveTo(_currentCard.getX(), _currentCard.getY() - 20);
                                _currentCard.setMoveable(false);
                               
                                if (_rearrange[0] == null) {
                                        _rearrange[0] = _handp1[_cardPlace];
                                        _rearrangePlace[0] = _cardPlace;
                                }
                                else if ( _rearrange[1] == null) {
                                        _rearrange[1] = _handp1[_cardPlace];
                                        _rearrangePlace[1] = _cardPlace;
                                }                                   
                                if (_rearrange[0] != null && _rearrange[1] != null) {
                                        _X1 = _rearrange[0].getX();
                                        _Y1 = _rearrange[0].getY();
                                        _X2 = _rearrange[1].getX();
                                        _Y2 = _rearrange[1].getY();
                                       
                                        _handp1[_rearrangePlace[0]] = _rearrange[1];
                                        _handp1[_rearrangePlace[0]].moveTo(_X1, _Y1 + 20);
                                       
                                        _handp1[_rearrangePlace[1]] = _rearrange[0];
                                        _handp1[_rearrangePlace[1]].moveTo(_X2, _Y2 + 20);
                                       
                                        _currentCard.setMoveable(true);
                                        _handp1[_rearrangePlace[0]].setMoveable(true);
                                        _handp1[_rearrangePlace[1]].setMoveable(true);
                                       
                                        _rearrangePlace[0] = -1;
                                        _rearrangePlace[1] = -1;
                                        _rearrange[0] = null;
                                        _rearrange[1] = null;
                                        _currentCard = null;
                                }
                                this.repaint(); // Repaint because position changed.
                        }
                        // Rearranging cards.
                        else if (_currentCard != null && _currentCard.getY() < 390) {
                                _oldX = _currentCard.getX();
                                _oldY = _currentCard.getY();
                                if (_rearrange[0] != null) {
                                        _rearrange[0] = null;
                                        _rearrangePlace[0] = -1;
                                }
                                else if ( _rearrange[1] != null) {
                                        _rearrange[1] = null;
                                        _rearrangePlace[1] = -1;
                                }
                                _currentCard.moveTo(_currentCard.getX(), _currentCard.getY() + 20);
                                _currentCard.setMoveable(true);
                                this.repaint(); // Repaint because position changed.
                        }
                }
        }
   
    //=============================================== Ignore other mouse events.
    public void mouseEntered(MouseEvent e) {}   // ignore these events
        public void mouseExited(MouseEvent e) {}        // ignore these events
        public void mouseMoved (MouseEvent e) {}        // ignore these events
       
}


////////////////////////////
//////////  EOF   //////////
////////////////////////////


yanko




PostPosted: 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/>.                         //////
//////===========================================================//////

// Best viewed in Notepad++


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;

////////////////////////////////////////////////////////////// class Dajm
class Dajm extends JFrame {
       
        public static String _progVersion = "Pre-Alpha";                        // Alpha? Beta? RC1? RC2? etc...
        public static double _buildVersion = 0.41;                              // Basic version
        public static String _buildDate = "January 11, 2009";      // Build date
        public static CardTable table;
        public static JFrame _about;                                // About dialog
        public static JFrame _main;                                             // Main window
        public static JMenuBar _menuBar;                                                        // The menu bar itself
        public static JMenu _menu;                                                      // The actual menus (reused)
        public static JMenuItem _newMenu;                                                 // The new menu item
        public static JMenuItem _exitMenu;                                          // The exit menu item
        public static JMenuItem _aboutMenu;                                   // The about menu item
        public static ClassLoader cldr = Dajm.class.getClassLoader();   // ClassLoader is used to get images from a jar file.
        public static URL imageURL;                                             // Variable to plug into the class loader.
       
    //===================================================================== main
    public static void main(String[] args) {
                createMainFrame();
                createAboutFrame();
    }
       
        //===================================================================== createMainFrame
        public static void createMainFrame() {
                // Create our frame
        _main = new JFrame();
                _main.setTitle("Dajm");
        _main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               
                // 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
        public static void createAboutFrame() {
                imageURL = cldr.getResource("img/logo.png");
                JLabel logoImg = new JLabel(new ImageIcon(imageURL));
                JLabel version = new JLabel(" v" + _buildVersion + " " + _progVersion + "  -  " + _buildDate + " build");
                imageURL = cldr.getResource("img/gnugpl.png");
                JLabel gnugplImg = new JLabel(new ImageIcon(imageURL));
                JLabel copyright = new JLabel("Copyright 2008-2009 Drew Burden, Yanko Petrovic");
                JButton ok = new JButton("Close");
                ok.setActionCommand("close");
                ok.addActionListener(actionListener);
                JTextArea gnu = new JTextArea("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(new Insets(5,5,5,5));
                gnu.setLineWrap(true);
                gnu.setWrapStyleWord(true);
                gnu.setEditable(false);
               
                JScrollPane scroll = new JScrollPane(gnu);
                scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
               
                // Create our frame
        _about = new JFrame();
        _about.setTitle("About");
                _about.setPreferredSize(new Dimension(400, 250));
                JPanel panel = new JPanel();
                panel.setLayout(null);

                logoImg.setBounds((400 / 2 - 160 / 2), 10, 160, 33);
                version.setBounds(80, 30, 300, 50);
                copyright.setBounds(50, 50, 300, 50);
                gnugplImg.setBounds(250, 95, 127, 51);
                ok.setBounds(275, 160, 75, 35);
                scroll.setBounds(20, 95, 218, 110);
               
                _about.getRootPane().setDefaultButton(ok);
               
                panel.add(logoImg);
                panel.add(version);
                panel.add(copyright);
                panel.add(gnugplImg);
                panel.add(ok);
                panel.add(scroll);
                _about.add(panel);

                // Essentially, this all displays the window
        _about.pack();
        _about.setLocationRelativeTo(null);
                _about.setResizable(false);
        _about.setVisible(false);
        }
       
        public static ActionListener actionListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                        if ("close".equals(e.getActionCommand())) {
                                _about.setVisible(false);
                        }
                        else {
                                JOptionPane.showMessageDialog(null, "\nERROR!\n\n");
                        }
                }
        };
       
        //===================================================================== createMenu
        public static void createMenu() {
                // Create the menu bar.
                _menuBar = new JMenuBar();

                // Create File Menu
                _menu = new JMenu("File");
                _menu.setMnemonic(KeyEvent.VK_F);
                _menuBar.add(_menu);

                // Create File Menu item
                _newMenu = new JMenuItem("New Game");
                _newMenu.setMnemonic(KeyEvent.VK_N);
                _menu.add(_newMenu);
                _newMenu.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                table.newGame();
                                _main.setContentPane(table);
            }
        });
               
                // Create Exit Menu item
                _exitMenu = new JMenuItem("Exit");
                _exitMenu.setMnemonic(KeyEvent.VK_X);
                _menu.add(_exitMenu);
                _exitMenu.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });

                // Create the Help Menu
                _menu = new JMenu("Help");
                _menu.setMnemonic(KeyEvent.VK_H);
                _menuBar.add(_menu);
               
                // Create the About Menu item
                _aboutMenu = new JMenuItem("About");
                _aboutMenu.setMnemonic(KeyEvent.VK_A);
                _menu.add(_aboutMenu);
                _aboutMenu.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                _about.setVisible(true);
            }
        });
        }
}


////////////////////////////
//////////  EOF   //////////
////////////////////////////
yanko




PostPosted: Wed Jan 21, 2009 8:32 am   Post subject: RE:AI in Java for a card game

no one has an idea?
DemonWasp




PostPosted: 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




PostPosted: 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
Sponsor
sponsor
A.J




PostPosted: 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




PostPosted: 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




PostPosted: 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' Very Happy
yanko




PostPosted: 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




PostPosted: 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




PostPosted: 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




PostPosted: 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 Very Happy
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 2  [ 17 Posts ]
Goto page 1, 2  Next
Jump to:   


Style:  
Search: