[英]how do i randomly perform button's action
我真的很喜欢JAVA而且我正在制作tic tac toe游戏我完成了玩家对玩家现在我想做玩家vs cpu我想要做的是当玩家点击X按钮出现然后cpu将选择他们的按钮随机出现O,但我不知道随机执行动作的代码
我在互联网上搜索了一小时,但仍然没有结果这是我的代码
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”标记正方形后,您必须检查哪些正方形仍然没有标记。 您可以通过在游戏开始时初始化整数的ArrayList(1到9)来执行此操作,该游戏表示仍未标记的正方形(按钮)。
图:编号的Tic-Tac-Toe板
2.其次,每次通过播放器或cpu标记其中一个方块时,从列表中删除相应的整数。
3.以您当前的方式观察按钮操作事件,并添加以下代码。 (我们的整数ArrayList被命名为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).
*/
}
注意:如果您只在2个方格之间进行选择,那么请忘记我所描述的ArrayList方法。 只需调用rand_gen.nextBoolean()并插入一个if语句,如果为true则选择一个按钮,如果为false则选择另一个按钮。
这应该足以让您开始实施您的解决方案,
祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.