java - 我如何随机执行按钮的动作
问题描述
我对JAVA真的很陌生,我正在制作井字游戏他们的按钮随机出现,但我不知道随机执行操作的代码
我在互联网上搜索了一个小时,但仍然没有结果这是我的代码
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//my code here to set text and background etc
if(jButton3.getActionCommand().equals("X") && jButton1.getActionCommand().equals("") && jButton2.getActionCommand().equals("")){
//this where i wanna random between 2 button action
}
我希望 CPU 在
jButton1ActionPerformed(evt);
jButton2ActionPerformed(evt);
但我真的不知道该怎么做
解决方案
我的理解
我将您的问题解释为如何编写一个函数,在用户执行移动后,用字母“O”随机标记剩余的方块之一。如果我弄错了,请用评论纠正我。
问题方法
因为我不知道代表您的 cpu 播放器的代码的确切性质,所以我将提供一个您可以实施的高级解决方案。
1.首先,在玩家用字母“X”标记方格后,您必须检查哪些方格仍未标记。您可以通过在游戏开始时初始化 1 到 9 的整数 ArrayList 来完成此操作,这些整数代表仍然未标记的正方形(按钮)。
图:编号井字棋盘
2.其次,每次有一个方格被玩家或 CPU 标记时,从列表中删除相应的 Integer。
3.以您当前的方式观察按钮动作事件并添加以下代码。(我们的整数数组列表被命名为 unmarked_boxes)。
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//my code here to set text and background etc
if(jButton3.getActionCommand().equals("X") && jButton1.getActionCommand().equals("") && jButton2.getActionCommand().equals("")){
Random rand_gen = new Random();
int index_selected = rand_gen.nextInt(unmarked_boxes.size());
box_selected = unmarked_boxes.remove(index_selected);
/*
here you select and mark the button which corresponds to the box
selected. i.e. if the box_selected = 3, then find and mark button3 (not sure
how you access your buttons).
*/
}
- 在我插入的代码中,我们实例化了 Random 类型的 Object 并调用其成员函数 nextInt(int bound)。此函数将生成一个介于 0 和 int 'bound' 之间的数字。
- 在这种情况下,我们想从整个未标记方块列表中选择一个方块。
- 因此,我们生成了一个介于 0 和剩余方块数之间的数字。
- 然后我们在 unmarked_boxes 列表中抓取(并同时删除)位于“index_selected”处的数字,并用“O”标记相应的按钮。
- 此后,您需要实现代码以标记所选按钮。
注意:如果您只在 2 个方格之间进行选择,那么请忘记我所描述的 ArrayList 方法。只需调用 rand_gen.nextBoolean() 并插入一个 if 语句,如果为 true,则选择一个按钮,如果为 false,则选择另一个按钮。
这应该足以让您开始实施您的解决方案,
祝你好运
推荐阅读
- function - 具有函数参数的 Fortran 函数,这些函数本身具有不同数量的参数
- c++ - 为什么我不能将 std::begin/std::end 与 int(*p)[3] 一起使用,而我可以与 int(&p)[3] 一起使用?
- pygame - 复制一个 pygame.Surface 对象
- javascript - 根据 1st Select 设置 2nd Select 的选项
- tensorflow - 如何在最新版本的 Tensorflow 中使用 MultiVariateNormal 分布
- angular - Angular Grid Ag-Grid,使列可动态编辑
- javascript - 使用 jQuery 的按键传递
- html - 如何在 HTML 中对齐文本按钮
- vue.js - 是否有可能有一个可选的 vue 路线
- python - 将张量流梯度应用于特定输入