Untitled
unknown
plain_text
10 months ago
3.6 kB
4
Indexable
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class LudoGame extends JFrame {
private static final int BOARD_SIZE = 15; // 15x15 grid board
private int currentPlayer = 0; // Player 0 is red, 1 is green, etc.
private int[] playerPositions = new int[4]; // Player positions (assuming 4 players)
private final Color[] playerColors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
private JButton rollButton;
private JLabel statusLabel;
public LudoGame() {
setTitle("Ludo Game");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
// Create Board Panel
JPanel boardPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawBoard(g);
}
};
boardPanel.setPreferredSize(new Dimension(400, 400));
add(boardPanel, BorderLayout.CENTER);
// Create Status and Roll Button Panel
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BorderLayout());
statusLabel = new JLabel("Player 1's Turn (Red)", JLabel.CENTER);
controlPanel.add(statusLabel, BorderLayout.NORTH);
rollButton = new JButton("Roll Dice");
rollButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
rollDice();
}
});
controlPanel.add(rollButton, BorderLayout.SOUTH);
add(controlPanel, BorderLayout.SOUTH);
}
private void drawBoard(Graphics g) {
int gridSize = 30; // Cell size in pixels
g.setColor(Color.LIGHT_GRAY);
// Draw a 15x15 grid
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col < BOARD_SIZE; col++) {
g.drawRect(col * gridSize, row * gridSize, gridSize, gridSize);
}
}
// Draw player tokens (simplified - only show positions)
for (int i = 0; i < 4; i++) {
int x = playerPositions[i] % BOARD_SIZE;
int y = playerPositions[i] / BOARD_SIZE;
g.setColor(playerColors[i]);
g.fillOval(x * gridSize + 5, y * gridSize + 5, gridSize - 10, gridSize - 10);
}
}
private void rollDice() {
Random rand = new Random();
int diceRoll = rand.nextInt(6) + 1; // Generate dice roll between 1 and 6
statusLabel.setText("Player " + (currentPlayer + 1) + " rolled: " + diceRoll);
// Move the current player's token
playerPositions[currentPlayer] += diceRoll;
// Check if player has finished (we assume 100 is the finish line for simplicity)
if (playerPositions[currentPlayer] >= 100) {
playerPositions[currentPlayer] = 100; // Cap it to 100
statusLabel.setText("Player " + (currentPlayer + 1) + " Wins!");
} else {
// Change turn to the next player
currentPlayer = (currentPlayer + 1) % 4;
}
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
LudoGame game = new LudoGame();
game.setVisible(true);
}
});
}
}
Editor is loading...
Leave a Comment