我目前正在嘗試創(chuàng)建一款戰(zhàn)艦游戲。我遇到問(wèn)題的部分是當(dāng)我選擇“隨機(jī)”按鈕時(shí),我希望它將船只放置在網(wǎng)格的隨機(jī)部分。例如,航母將覆蓋陣列內(nèi)的 5 個(gè) JButton。如何在數(shù)組中隨機(jī)選擇 5 個(gè)彼此相鄰的 JButton?import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JButton;import java.util.Random;public class View{ private JFrame frame; private JPanel panel1; private JPanel panel2; private JButton grid1[][]; private JButton randomize; private String[] alphabet = { "", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" }; private String[] numbers = { "", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; public View() { configureFrame(); configurePanels(); configureComponents(); frame.setVisible(true); } private void configureFrame() { frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(900, 600); frame.setResizable(false); frame.setLocationRelativeTo(null); } private void configurePanels() { panel1 = new JPanel(); panel1.setLayout(new GridLayout(11, 11)); frame.getContentPane().add(panel1, BorderLayout.WEST); panel2 = new JPanel(); panel2.setSize(frame.getWidth(), frame.getHeight()); panel2.setLayout(null); frame.getContentPane().add(panel2); } private void configureComponents() { grid1 = new JButton[11][11]; for(int i = 0; i < grid1.length; i++) { for(int j = 0; j < grid1[i].length; j++) { grid1[i][j] = new JButton(); panel1.add(grid1[i][j]); } }我對(duì) Java 很陌生,所以如果我沒(méi)有任何意義,我提前道歉。
1 回答

呼啦一陣風(fēng)
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
如何在數(shù)組中隨機(jī)選擇 5 個(gè)彼此相鄰的 JButton?
您生成第一個(gè)坐標(biāo)
隨機(jī)決定是垂直放置還是水平放置
然后沿該方向添加 +4(當(dāng)前單元格和 4 個(gè)額外單元格)。
如果要放置的 5 個(gè)新單元格中的任何一個(gè)已經(jīng)包含一艘船,請(qǐng)重復(fù)此過(guò)程。
添加回答
舉報(bào)
0/150
提交
取消