-3

I'm writing my first own chess game in Java.

My code already works for two players, manually playing from the keyboard, and I would like to expand it to a player against the computer game.

My problem is that I've never dealt with random actions. The method which is moving a piece on the board, needs to receive 4 inputs: two integers for the piece location, and two integers for the destination on the board.

Choosing the wrong inputs is OK since the movePiece method already checks if the integers are not out of the board's bounds, that they really reach a piece of the current player's color, that there's a piece in the coordination and its not empty, etc.

But how do I get these 4 integerss randomly? And how do I make them as closest as possible to "real" inputs (so I don't spend a lot of time disqualifying bad inputs)?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Jjang
  • 11,250
  • 11
  • 51
  • 87
  • 5
    Hmmm.. strange approach here. Chess should not be random moving pieces in the board. There are a lot of chess game libraries. Why do you not try to use one of them in your game? – Averroes Feb 18 '13 at 13:06
  • Yes as Averroes said, You must make the computer think as if a human will do. – Govind Balaji Feb 18 '13 at 13:09
  • I need random actions in order to simulate "computer" playing against a player, but I dont need a sophisticated algorithm. just something that moves pieces. – Jjang Feb 18 '13 at 13:16

3 Answers3

2

Java provides at least two options to generate random values:

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#random()

E.g. to get random int values bounded by 4:

int x = new Random().nextInt(4);
int y = (int) (Math.random() * 4);

System.out.println(x + " " + y);

>> 2 3
Raman
  • 887
  • 4
  • 12
  • 28
1

If you really would like to create a computer player who just moves about randomly, I think it would be better to do it it like this:

  1. Randomly select one of the existing chess pieces on the board
  2. Compute all legal destinations to which that chess piece could move
  3. If there are no legal destinations, choose a new piece amongst the previously not selected pieces
  4. Randomly select one of the computed legal destinations

However, letting a computer player move about randomly is rather silly. A computer player would need to have some form of logic to compare which out of two moves is better. Implementing such logic is probably rather complex, and you're probably better off using a chess library as someone suggested in the comments.

Alderath
  • 3,761
  • 1
  • 25
  • 43
0

You don't need 4 ints. You only need 1.

A way of doing this:

  1. Iterate the pieces on the board.
  2. For each piece, determine its available moves and stick all the available moves in a list.
  3. Pick one move from the list at random (or at non-random, if you feel so-inclined).
Boann
  • 48,794
  • 16
  • 117
  • 146