javafx写一个小游戏-井字棋

学了几天的javafx,感觉非常好用,自己写了一个小游戏,如有不足,希望大佬加以指正,谢谢。

1.先写UI界面

新建一个ui.fxml文件,用于显示ui界面
界面效果如下:
在这里插入图片描述
代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.shape.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="600.0" maxWidth="600.0" minHeight="600.0" minWidth="600.0" prefHeight="600.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
 fx:controller="application.MyController"><!--  此处添加fx:controller="xxxxr"来添加ui界面的功能处理 -->
   <children>
      <GridPane maxHeight="600.0" maxWidth="600.0" minHeight="600.0" minWidth="600.0" prefHeight="600.0" prefWidth="600.0" style="-fx-grid-lines-visible: true;">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <Button  maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false"  prefHeight="200.0" prefWidth="200.0" />
            <Button  layoutX="10.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false"  prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" />
            <Button  layoutX="210.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false"  prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2" />
            <Button  layoutX="10.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false"  prefHeight="200.0" prefWidth="200.0" GridPane.rowIndex="1" />
            <Button  layoutX="10.0" layoutY="210.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
            <Button  layoutX="10.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2" GridPane.rowIndex="1" />
            <Button  maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false"  prefHeight="200.0" prefWidth="200.0" GridPane.rowIndex="2" />
            <Button maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false"  prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="2" />
            <Button  maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false"  prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2" GridPane.rowIndex="2" />
         </children>
      </GridPane>
   </children>
</AnchorPane>

二.加载布局文件

在Main.java中,通过FXMLLoader.load()加载布局文件,
代码如下:

FXMLLoader.load(getClass().getResource("/application/ui.fxml")); //加载布局文件ui.fxml              

三.处理ui界面的功能

新建一个类,实现Initializable功能。
代码如下:

package application;

public class MyController implements Initializable {	
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {	//首先调用此方法
		
	}
}

在ui.fxml里添加 fx:controller="application.MyController"后,

 fx:controller="application.MyController"	//controller的名字和位置根据自己的配置选择

在MyController.java里可以用@FXML注解将属性分享到ui界面上

@FXML private Button bu;			//按钮控件

然后在ui.fxml文件里使用fx:id便可以绑定控件

<Button fx:id="b1" />		//绑定MyController中的属性

而按钮的点击方法可以通过设置方法的参数,如下:

public void play(ActionEvent event) {
		...
}

将方法分享到ui界面上,在ui界面上使用fx:onAction进行绑定

<onAction="#action">	//绑定点击的函数

完整代码如下:
1.Main.java

package application;
	
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
	
	@Override
	public void start(Stage primaryStage) {
		try {	
			Parent root = FXMLLoader.load(getClass()			//加载布局文件ui.fxml
                    .getResource("/application/ui.fxml"));
			primaryStage.setTitle("井字棋");								//设置标题
			primaryStage.setScene(new Scene(root));				//设置主面板
			primaryStage.show();												//显示主界面
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		launch(args);
	}
}

2.MyController.java

package application;


import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.image.Image;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundSize;

public class MyController implements Initializable {
	
	private Image imageX = new Image("x.jpg");	//图片X
	private Image imageO = new Image("o.jpg");	//图片O
	private boolean flag = true;				//标志物,决定当前是画X还是画O

	@FXML private Button b1;			//通过@FXML来绑定控件
	@FXML private Button b2;			//b1-b9代表9个格子
	@FXML private Button b3;
	@FXML private Button b4;
	@FXML private Button b5;
	@FXML private Button b6;
	@FXML private Button b7;
	@FXML private Button b8;
	@FXML private Button b9;
	private int[] r = new int[9];	//分别代表9个棋子	-1代表X 	1代表O
	
	private ButtonType buttonAgain = new ButtonType("重新开始");		//重新开始的按钮
	private ButtonType buttonOver = new ButtonType("结束游戏");		//重新开始的按钮
	private Alert alt = new Alert(AlertType.CONFIRMATION);			//游戏结束对话框
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {	//首先调用此方法
		setBackgroundEmpty();	//清空所有背景图片
		alt.setTitle("游戏结束!"); 	//设置对话框的标题
		alt.getButtonTypes().setAll(buttonAgain,buttonOver);	//添加按钮到对话框上
	}
	private	BackgroundSize bs =  new BackgroundSize(200, 200, false, false, false, false);	//设置画的图形的大小
	private BackgroundImage bX = new BackgroundImage(imageX, null, null, null, bs);		//图形X
	private BackgroundImage bO = new BackgroundImage(imageO, null, null, null, bs);		//图形O	
	
	//点击按钮时调用此方法
	public void action(ActionEvent event) {
		Button b = (Button) event.getSource();		//获得点击的对象
		int id = Integer.parseInt(b.getId().trim().substring(1))-1;	//通过按钮的id获得位置 例如是b1 得到0
		if(b.getBackground() == null) {		//如果还没有下这个位置
			if(flag == true) {					//该画X了
				b.setBackground(new Background(bX));	//画X
				r[id] = -1;
				flag = false;	//下一个应该画O
			}else {								//该画O了
				b.setBackground(new Background(bO));	//画O
				r[id] = 1;
				flag = true;	//下一个应该画X
			}
			check();
		}
	}
	//清空所有按钮的背景
	private void setBackgroundEmpty() {
		b1.setBackground(null);b2.setBackground(null);b3.setBackground(null);	
		b4.setBackground(null);b5.setBackground(null);b6.setBackground(null);
		b7.setBackground(null);b8.setBackground(null);b9.setBackground(null);
	}
	//重新开始
	private void again() {
		setBackgroundEmpty();			//清空背景
		r = new int[9];					//重新计数
	}
	//判断是否满足胜利条件
	private void check() {
		if(r[0]+r[1]+r[2]==3			//第一排横着3个O
		|| r[3]+r[4]+r[5]==3			//第二排横着3个O
		|| r[6]+r[7]+r[8]==3			//第三排横着3个O
		|| r[0]+r[3]+r[6]==3			//第一列竖着3个O
		|| r[1]+r[4]+r[7]==3			//第二列竖着3个O
		|| r[2]+r[5]+r[8]==3			//第三列竖着3个O
		|| r[0]+r[4]+r[8]==3			//  \的3个O
		|| r[2]+r[4]+r[6]==3) {			//  /的3个O
			alt.setHeaderText("O赢了");						//设置对话框内容
			Optional<ButtonType> result = alt.showAndWait();	//显示对话框
			if (result.get() == buttonAgain){		//再来一次
			    again();
			}else {
				System.exit(0);		//结束游戏
			}
		}
		if(r[0]+r[1]+r[2]==-3			//第一排横着3个X
		|| r[3]+r[4]+r[5]==-3			//第二排横着3个X
		|| r[6]+r[7]+r[8]==-3			//第三排横着3个X
		|| r[0]+r[3]+r[6]==-3			//第一列竖着3个X
		|| r[1]+r[4]+r[7]==-3			//第二列竖着3个X
		|| r[2]+r[5]+r[8]==-3			//第三列竖着3个X
		|| r[0]+r[4]+r[8]==-3			//  \的3个X
		|| r[2]+r[4]+r[6]==-3) {
			alt.setHeaderText("X赢了");						//设置对话框内容
			Optional<ButtonType> result = alt.showAndWait();	//显示对话框
			if (result.get() == buttonAgain){		//再来一次
			    again();
			}else {
				System.exit(0);		//结束游戏
			}
		}	
		//所有格子都被点了 但是没有分出胜负
		if(r[0]!=0 && r[1]!=0 && r[2]!=0	
		&& r[3]!=0 && r[4]!=0 && r[5]!=0
		&& r[6]!=0 && r[7]!=0 && r[8]!=0) {
			alt.setHeaderText("平局");						//设置对话框内容
			Optional<ButtonType> result = alt.showAndWait();	//显示对话框
			if (result.get() == buttonAgain){		//再来一次
			    again();
			}else {
				System.exit(0);		//结束游戏
			}
		}
	}
}

3.ui.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.shape.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="600.0" maxWidth="600.0" minHeight="600.0" minWidth="600.0" prefHeight="600.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MyController">
   <children>
      <GridPane maxHeight="600.0" maxWidth="600.0" minHeight="600.0" minWidth="600.0" prefHeight="600.0" prefWidth="600.0" style="-fx-grid-lines-visible: true;">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <Button fx:id="b1" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" />
            <Button fx:id="b2" layoutX="10.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" />
            <Button fx:id="b3" layoutX="210.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2" />
            <Button fx:id="b4" layoutX="10.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.rowIndex="1" />
            <Button fx:id="b5" layoutX="10.0" layoutY="210.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
            <Button fx:id="b6" layoutX="10.0" layoutY="10.0" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2" GridPane.rowIndex="1" />
            <Button fx:id="b7" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.rowIndex="2" />
            <Button fx:id="b8" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="2" />
            <Button fx:id="b9" maxHeight="200.0" maxWidth="200.0" minHeight="200.0" minWidth="200.0" mnemonicParsing="false" onAction="#action" prefHeight="200.0" prefWidth="200.0" GridPane.columnIndex="2" GridPane.rowIndex="2" />
         </children>
      </GridPane>
   </children>
</AnchorPane>

运行结果如下:
在这里插入图片描述

学习交流请加QQ群:1062828738

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

妍芯电子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值