Last active
August 29, 2015 14:13
-
-
Save RomanKurbanov/d491896cb4f617b6478d to your computer and use it in GitHub Desktop.
Another minesweeper on JavaFX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<component name="ArtifactManager"> | |
<artifact type="javafx" name="JavaFXApp"> | |
<output-path>$PROJECT_DIR$/out/artifacts/JavaFXApp</output-path> | |
<properties id="javafx-properties"> | |
<options> | |
<option name="appClass" value="sample.Main" /> | |
</options> | |
</properties> | |
<root id="root"> | |
<element id="archive" name="JavaFXApp.jar"> | |
<element id="module-output" name="Minesweeper" /> | |
</element> | |
</root> | |
</artifact> | |
</component> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<component name="ArtifactManager"> | |
<artifact type="javafx" name="Minesweeper"> | |
<output-path>$PROJECT_DIR$/out/artifacts/Minesweeper</output-path> | |
<properties id="javafx-properties"> | |
<options> | |
<option name="appClass" value="sample.Main" /> | |
</options> | |
</properties> | |
<root id="root"> | |
<element id="archive" name="JavaFXApp.jar"> | |
<element id="module-output" name="Minesweeper" /> | |
</element> | |
</root> | |
</artifact> | |
</component> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="CompilerConfiguration"> | |
<option name="DEFAULT_COMPILER" value="Javac" /> | |
<resourceExtensions /> | |
<wildcardResourcePatterns> | |
<entry name="!?*.java" /> | |
<entry name="!?*.form" /> | |
<entry name="!?*.class" /> | |
<entry name="!?*.groovy" /> | |
<entry name="!?*.scala" /> | |
<entry name="!?*.flex" /> | |
<entry name="!?*.kt" /> | |
<entry name="!?*.clj" /> | |
</wildcardResourcePatterns> | |
<annotationProcessing> | |
<profile default="true" name="Default" enabled="false"> | |
<processorPath useClasspath="true" /> | |
</profile> | |
</annotationProcessing> | |
</component> | |
</project> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<component name="CopyrightManager"> | |
<settings default="" /> | |
</component> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html>Simple <b>JavaFX 2.0</b> application that includes simple .fxml file with attached controller and Main class to quick start. Artifact to build JavaFX application is provided. | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" /> | |
</project> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="GradleSettings"> | |
<option name="gradleHome" value="C:/Program Files (x86)/Gradle/gradle-1.0-rc-3" /> | |
</component> | |
</project> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="ClientPropertiesManager"> | |
<properties class="javax.swing.AbstractButton"> | |
<property name="hideActionText" class="java.lang.Boolean" /> | |
</properties> | |
<properties class="javax.swing.JComponent"> | |
<property name="html.disable" class="java.lang.Boolean" /> | |
</properties> | |
<properties class="javax.swing.JEditorPane"> | |
<property name="JEditorPane.w3cLengthUnits" class="java.lang.Boolean" /> | |
<property name="JEditorPane.honorDisplayProperties" class="java.lang.Boolean" /> | |
<property name="charset" class="java.lang.String" /> | |
</properties> | |
<properties class="javax.swing.JList"> | |
<property name="List.isFileList" class="java.lang.Boolean" /> | |
</properties> | |
<properties class="javax.swing.JPasswordField"> | |
<property name="JPasswordField.cutCopyAllowed" class="java.lang.Boolean" /> | |
</properties> | |
<properties class="javax.swing.JSlider"> | |
<property name="Slider.paintThumbArrowShape" class="java.lang.Boolean" /> | |
<property name="JSlider.isFilled" class="java.lang.Boolean" /> | |
</properties> | |
<properties class="javax.swing.JTable"> | |
<property name="Table.isFileList" class="java.lang.Boolean" /> | |
<property name="JTable.autoStartsEdit" class="java.lang.Boolean" /> | |
<property name="terminateEditOnFocusLost" class="java.lang.Boolean" /> | |
</properties> | |
<properties class="javax.swing.JToolBar"> | |
<property name="JToolBar.isRollover" class="java.lang.Boolean" /> | |
</properties> | |
<properties class="javax.swing.JTree"> | |
<property name="JTree.lineStyle" class="java.lang.String" /> | |
</properties> | |
<properties class="javax.swing.text.JTextComponent"> | |
<property name="caretAspectRatio" class="java.lang.Double" /> | |
<property name="caretWidth" class="java.lang.Integer" /> | |
</properties> | |
</component> | |
<component name="EntryPointsManager"> | |
<entry_points version="2.0" /> | |
</component> | |
<component name="IdProvider" IDEtalkID="00E7B3C1A7A880C5A5C6B5E77CB565DF" /> | |
<component name="ProjectKey"> | |
<option name="state" value="project://e79810c8-c5c8-43b1-b19c-90c1f4095425" /> | |
</component> | |
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="1.7" project-jdk-type="JavaSDK"> | |
<output url="file://$PROJECT_DIR$/out" /> | |
</component> | |
</project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="ProjectModuleManager"> | |
<modules> | |
<module fileurl="file://$PROJECT_DIR$/Minesweeper.iml" filepath="$PROJECT_DIR$/Minesweeper.iml" /> | |
</modules> | |
</component> | |
</project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<component name="DependencyValidationManager"> | |
<state> | |
<option name="SKIP_IMPORT_STATEMENTS" value="false" /> | |
</state> | |
</component> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="Palette2"> | |
<group name="Swing"> | |
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" /> | |
</item> | |
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" /> | |
</item> | |
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" /> | |
</item> | |
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true"> | |
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" /> | |
</item> | |
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" /> | |
<initial-values> | |
<property name="text" value="Button" /> | |
</initial-values> | |
</item> | |
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> | |
<initial-values> | |
<property name="text" value="RadioButton" /> | |
</initial-values> | |
</item> | |
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" /> | |
<initial-values> | |
<property name="text" value="CheckBox" /> | |
</initial-values> | |
</item> | |
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" /> | |
<initial-values> | |
<property name="text" value="Label" /> | |
</initial-values> | |
</item> | |
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> | |
<preferred-size width="150" height="-1" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> | |
<preferred-size width="150" height="-1" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1"> | |
<preferred-size width="150" height="-1" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> | |
<preferred-size width="150" height="50" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> | |
<preferred-size width="150" height="50" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> | |
<preferred-size width="150" height="50" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" /> | |
</item> | |
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> | |
<preferred-size width="150" height="50" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3"> | |
<preferred-size width="150" height="50" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3"> | |
<preferred-size width="150" height="50" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> | |
<preferred-size width="200" height="200" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3"> | |
<preferred-size width="200" height="200" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true"> | |
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> | |
</item> | |
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" /> | |
</item> | |
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" /> | |
</item> | |
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" /> | |
</item> | |
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1"> | |
<preferred-size width="-1" height="20" /> | |
</default-constraints> | |
</item> | |
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false"> | |
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" /> | |
</item> | |
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false"> | |
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" /> | |
</item> | |
</group> | |
</component> | |
</project> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="VcsDirectoryMappings"> | |
<mapping directory="" vcs="" /> | |
</component> | |
</project> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<module type="JAVA_MODULE" version="4"> | |
<component name="NewModuleRootManager" inherit-compiler-output="true"> | |
<exclude-output /> | |
<content url="file://$MODULE_DIR$"> | |
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" /> | |
</content> | |
<orderEntry type="inheritedJdk" /> | |
<orderEntry type="sourceFolder" forTests="false" /> | |
</component> | |
</module> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample; | |
import javafx.event.EventHandler; | |
import javafx.fxml.FXML; | |
import javafx.scene.control.Button; | |
import javafx.scene.control.ComboBox; | |
import javafx.scene.control.Label; | |
import javafx.scene.image.Image; | |
import javafx.scene.image.ImageView; | |
import javafx.scene.input.MouseButton; | |
import javafx.scene.input.MouseEvent; | |
import javafx.scene.layout.GridPane; | |
import java.util.Random; | |
public class Controller { | |
Image mineIcon = new Image(getClass().getResourceAsStream("icon.png"));//Эта штука грабит картинку | |
Image flagIcon = new Image(getClass().getResourceAsStream("flag.png"));//Серьезно | |
@FXML | |
Label mineCountLabel=new Label(); | |
static boolean IsFirstButtonPressed = false; //Первая кнопка должна быть без мины. | |
@FXML | |
int dotsLeft=80, minesFlagged=20; //dotsLeft показывает, сколько еще кнопок должен нажать игрок, чтобы выиграть | |
//Когда он нажмет на все кнопки, кроме мин, тогда и победит. | |
//minesFlagged показывает юзеру, сколько мнимых мин осталось. Тоесть когда он поставит флажок, | |
//Кол-во оставшихся мин, которых он не отметил уменьшится на счетчике, чтобы не держать их в уме. | |
//На победу minesFlagged никак не влияет. | |
@FXML | |
Button startButton; | |
@FXML //На это не обращай внимание, особенность десктопных приложений джавы | |
private GridPane mineFieldPane; //Как бы панелька с кучей ячеек внутри | |
public void setMineFieldPane(GridPane mineFieldPane, mineButton[][] mineField) { | |
this.mineFieldPane = mineFieldPane; | |
this.mineFieldPane.getChildren().clear(); | |
for(mineButton[] line : mineField){ | |
for(mineButton dot : line){ | |
mineFieldPane.add(dot,dot.x,dot.y); //Должны добавляться в GridPane кнопки из массива | |
} | |
} | |
} | |
//Снизу метод, который создает поле с нужными параметрами. | |
//Х - кнопки по горизонтали, у - кнопки по вертикали, mines - кол-во мин на поле. | |
@FXML | |
private mineButton[][] CreateNewField(int x, int y, int mines){ | |
//Создается переменная field, это массив из объектов класса MineButton | |
mineButton[][] field = new mineButton[x][y]; | |
Random random = new Random(); | |
x=0; | |
y=0; | |
//Поле нужно рандомно заполнить. | |
while (mines>0){ //Пока нужно добавить на поле мины | |
for (mineButton[] line : field){ //Счетчик проходит по столбцам | |
for(mineButton dot : line){ //А здесь по строке столбца | |
// IF ниже проверяет, существует ли кнопка в массиве, так как хоть ты и создал массив, | |
// он все равно пуст и пока не содержит ни кнопок, вообще ничего, поэтому они создаются | |
// и заполняются здесь, снизу. | |
if (dot==null){ //Если кнопка не существует | |
dot = new mineButton(x,y); //На её место призывается новая кнопка, которой дают собственные координаты | |
dot = SetMineButton(dot); //Здесь же настраивается её обработчик событий | |
dot.setDisable(false);//Настроенные кнопки должны быть активированы. | |
} | |
//Если кнопка не содержит мину и нужно накинуть на поле еще мин, то она добавляется | |
//Или не добавляется, как повезет | |
if ((!dot.isMineHere) && mines>0){ | |
if (random.nextInt(5)==3){ //Вместо шанса 50% теперь шанс 20% (Шанс того, что случайное число от 0 до 4 будет тройкой) | |
//Шанс пропорционален кол-ву мин и кнопок на поле. | |
dot.isMineHere = true; | |
mines--; //Кол-во мин, которое нужно добавить на поле уменьшается на 1 с каждой миной | |
} | |
} | |
field[y][x]=dot;//Кнопка ДОБАВЛЯЕТСЯ в возвращаемый массив | |
x++; | |
} | |
y++; | |
x=0; | |
} | |
y=0; | |
x=0; | |
} | |
return field; //Возвращается заполненый кнопками и минами массив. | |
} | |
@FXML | |
public mineButton[][] field = CreateNewField(10, 10, 20); //Создается массив из кнопок с минами с помощью метода выше | |
@FXML | |
public void StartNewGame(){ //Эта штука вызывается при нажатии на самую большущую кнопку сверху, но вызов описан только в FXML-файле | |
dotsLeft=80; //Обновляем dotsLeft | |
minesFlagged=20; //Обновляем minesFlagged | |
mineCountLabel.setText(Integer.toString(minesFlagged)); //Обновляем надпись, которая у нас играет роль счетчика для игрока | |
IsFirstButtonPressed = false; //Обновляем фактор первого нажатия на кнопку, чтобы не жахнуло на первом же ходе | |
field = CreateNewField(10, 10, 20); //Переставляем мины | |
setMineFieldPane(mineFieldPane,field); //Обновляем поле | |
startButton.setText("Заново"); | |
} | |
private void CheckOtherButtons(mineButton thisButton){//Метод, который считает сколько мин в остальных кнопках. | |
{ | |
//код снизу проверяет все в массиве рядом с данной, если она конечно есть. | |
if (((thisButton.y - 1 >= 0 && thisButton.y - 1 < field.length) && (thisButton.x - 1 >= 0 && thisButton.x - 1 < field[0].length)) && (!field[thisButton.y - 1][thisButton.x - 1].isChecked)) CheckButton(field[thisButton.y - 1][thisButton.x - 1]); //Сверху слева | |
if (((thisButton.y - 1 >= 0 && thisButton.y - 1 < field.length) && (thisButton.x >= 0 && thisButton.x < field[0].length)) && (!field[thisButton.y - 1][thisButton.x].isChecked)) CheckButton(field[thisButton.y - 1][thisButton.x]); //Сверху | |
if (((thisButton.y - 1 >= 0 && thisButton.y - 1 < field.length) && (thisButton.x + 1 >= 0 && thisButton.x + 1 < field[0].length)) && (!field[thisButton.y - 1][thisButton.x + 1].isChecked)) CheckButton(field[thisButton.y - 1][thisButton.x+1]); //Сверху справа | |
if (((thisButton.y >= 0 && thisButton.y < field.length) && (thisButton.x - 1 >= 0 && thisButton.x - 1 < field[0].length)) && (!field[thisButton.y][thisButton.x - 1].isChecked)) CheckButton(field[thisButton.y][thisButton.x - 1]); //Слева | |
if (((thisButton.y >= 0 && thisButton.y < field.length) && (thisButton.x + 1 >= 0 && thisButton.x + 1 < field[0].length)) && (!field[thisButton.y][thisButton.x + 1].isChecked)) CheckButton(field[thisButton.y][thisButton.x + 1]); //Справа | |
if (((thisButton.y + 1 >= 0 && thisButton.y + 1 < field.length) && (thisButton.x - 1 >= 0 && thisButton.x - 1 < field[0].length)) && (!field[thisButton.y + 1][thisButton.x-1].isChecked)) CheckButton(field[thisButton.y + 1][thisButton.x - 1]); //Слева снизу | |
if (((thisButton.y + 1 >= 0 && thisButton.y + 1 < field.length) && (thisButton.x >= 0 && thisButton.x < field[0].length)) && (!field[thisButton.y + 1][thisButton.x].isChecked)) CheckButton(field[thisButton.y + 1][thisButton.x]); //Снизу | |
if (((thisButton.y + 1 >= 0 && thisButton.y + 1 < field.length) && (thisButton.x + 1 >= 0 && thisButton.x + 1 < field[0].length)) && (!field[thisButton.y + 1][thisButton.x + 1].isChecked)) CheckButton(field[thisButton.y + 1][thisButton.x + 1]); //Справа снизу | |
if (!thisButton.isMineHere) { //Если не жахнуло | |
thisButton.isChecked=true; | |
thisButton.setDisable(true); //Деактивируем кнопку. | |
if (thisButton.minesNearby > 0) { //Если рядом есть мины | |
thisButton.setText(Integer.toString(thisButton.minesNearby)); //То показываем прямо на кнопке сколько | |
} | |
} | |
} | |
//return thisButton; | |
} | |
private void CheckButton(mineButton thisButton){ | |
{ //Проверяем флагнута ли кнопка | |
if (thisButton.isMineHere) GameOver(); //Если мина есть - геймовер | |
//код снизу проверяет все в массиве рядом с данной, если она конечно есть. | |
if (((thisButton.y - 1 >= 0 && thisButton.y - 1 < field.length) && (thisButton.x - 1 >= 0 && thisButton.x - 1 < field[0].length)) && (field[thisButton.y - 1][thisButton.x - 1].isMineHere)) | |
thisButton.minesNearby++; //Сверху слева | |
if (((thisButton.y - 1 >= 0 && thisButton.y - 1 < field.length) && (thisButton.x >= 0 && thisButton.x < field[0].length)) && field[thisButton.y - 1][thisButton.x].isMineHere) | |
thisButton.minesNearby++; //Сверху | |
if (((thisButton.y - 1 >= 0 && thisButton.y - 1 < field.length) && (thisButton.x + 1 >= 0 && thisButton.x + 1 < field[0].length)) && field[thisButton.y - 1][thisButton.x + 1].isMineHere) | |
thisButton.minesNearby++; //Сверху справа | |
if (((thisButton.y >= 0 && thisButton.y < field.length) && (thisButton.x - 1 >= 0 && thisButton.x - 1 < field[0].length)) && field[thisButton.y][thisButton.x - 1].isMineHere) | |
thisButton.minesNearby++; //Слева | |
if (((thisButton.y >= 0 && thisButton.y < field.length) && (thisButton.x + 1 >= 0 && thisButton.x + 1 < field[0].length)) && field[thisButton.y][thisButton.x + 1].isMineHere) | |
thisButton.minesNearby++; //Справа | |
if (((thisButton.y + 1 >= 0 && thisButton.y + 1 < field.length) && (thisButton.x - 1 >= 0 && thisButton.x - 1 < field[0].length)) && field[thisButton.y + 1][thisButton.x - 1].isMineHere) | |
thisButton.minesNearby++; //Слева снизу | |
if (((thisButton.y + 1 >= 0 && thisButton.y + 1 < field.length) && (thisButton.x >= 0 && thisButton.x < field[0].length)) && field[thisButton.y + 1][thisButton.x].isMineHere) | |
thisButton.minesNearby++; //Снизу | |
if (((thisButton.y + 1 >= 0 && thisButton.y + 1 < field.length) && (thisButton.x + 1 >= 0 && thisButton.x + 1 < field[0].length)) && field[thisButton.y + 1][thisButton.x + 1].isMineHere) | |
thisButton.minesNearby++; //Справа снизу | |
if (!thisButton.isMineHere) { //Если не жахнуло | |
thisButton.isChecked=true; | |
thisButton.setDisable(true); //Деактивируем кнопку. | |
dotsLeft--; | |
if (thisButton.minesNearby > 0) { //Если рядом есть мины | |
thisButton.setText(Integer.toString(thisButton.minesNearby)); //То показываем прямо на кнопке сколько | |
} | |
else { // Ну а если нет | |
CheckOtherButtons(thisButton); //Этим методом проверяются остальные кнопки | |
} | |
if (dotsLeft<=0) startButton.setText("Ты подебил");//Типа победа. | |
} | |
} | |
} | |
public mineButton SetMineButton(final mineButton thisButton) { //Метод настраивает кнопку, получая саму кнопку | |
thisButton.setOnMouseClicked(new EventHandler<MouseEvent>() { //Если на кнопку кликнули мышкой | |
@Override //То событие ПРЕРЫВАЕТ естественный ход программы | |
public void handle(MouseEvent mouseEvent) { //И обрабатывает это событие. Обработчик получает данные о нажатии на кнопку, это переменная mouseEvent | |
if (mouseEvent.getButton()== MouseButton.SECONDARY){ //Если кнопка была нажата с ПКМ | |
if (!thisButton.isFlagged) { //А если она еще и не флагнута | |
thisButton.isFlagged = true; //То маркируем как флагнутую | |
thisButton.setGraphic(new ImageView(flagIcon)); //И заставляем её показывать нам флажок | |
minesFlagged--; //Увеличиваем кол-во флагнутых мин, тоесть как бы уменьшаем кол-во мин, которое НУЖНО флагнуть | |
mineCountLabel.setText(Integer.toString(minesFlagged)); // и выводим это кол-во на счетчик | |
} | |
else { //А если флагнута | |
thisButton.isFlagged = false; //То убираем флаг | |
thisButton.setGraphic(null); //И картинку | |
minesFlagged++; //И кол-во флагнутых мин уменьшаем... Ну ты понял | |
mineCountLabel.setText(Integer.toString(minesFlagged));//И даже показываем это игроку :| | |
} | |
} | |
else //А если не ПКМ | |
if (!thisButton.isFlagged) { //То проверяем флагнута ли кнопка | |
if (!IsFirstButtonPressed) { //Если это первая нажатая кнопка | |
if (thisButton.isMineHere) { //Если тут мина | |
thisButton.isMineHere = false; //То убираем с неё мину | |
minesFlagged--; //А еще придется показать игроку, что миной стало меньше | |
mineCountLabel.setText(Integer.toString(minesFlagged)); //Да-да, именно показать | |
dotsLeft++; //А еще ему придется нажать на кнопку больше взамен этой мины | |
} | |
IsFirstButtonPressed = true; //И говорим типа нажали. | |
} | |
if (thisButton.isMineHere) GameOver(); //Если мина есть - геймовер | |
else CheckButton(thisButton); | |
} | |
} | |
} | |
); | |
return thisButton; //Возвращает настроенную кнопку | |
} | |
@FXML | |
public void GameOver(){ | |
for(mineButton[] line : field){//Проходится по столбцу | |
for (mineButton dot : line){//Проходится по строке | |
dot.setText(""); //Очищает текст кнопки | |
dot.setGraphic(null); //Убирает флажок | |
if (dot.isMineHere) dot.setGraphic(new ImageView(mineIcon)); //Показывает есть ли мина, картинкой. | |
dot.setDisable(true); //Вырубает все кнопки. | |
} | |
} | |
startButton.setText("Ты проиграл"); | |
} | |
} | |
class mineButton extends Button { //Объявляешь новый класс, как число или строка, только кнопка | |
int x,y,minesNearby=0; // Координаты кнопки и кол-во мин рядом. | |
mineButton(int x, int y){ //Билдер кнопки, если при создании кнопки переданы аргументы, здесь это координаты, | |
//То кнопки создадутся сразу с ними | |
this.x=x; | |
this.y=y; | |
this.setText(""); //Очищается текст кнопки при создании. | |
this.setDisabled(false);//Кнопка после создания активирована. | |
this.setMaxSize(34,34); //Размеры кнопки | |
this.setMinSize(15,15); | |
this.setPrefSize(33,33); | |
} | |
boolean isMineHere = false; //Наличие мины на кнопке. По умолчанию её нет. | |
boolean isFlagged = false; //Поставлен ли на мине флажок. | |
boolean isChecked = false; //костыль :| Проверяет была ли нажата кнопка, чтобы автоматика не проверяла её несколько раз и не выдавала STACK OVERFLOW | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample; | |
import javafx.application.Application; | |
import javafx.fxml.FXMLLoader; | |
import javafx.scene.Parent; | |
import javafx.scene.Scene; | |
import javafx.scene.control.ComboBox; | |
import javafx.scene.image.Image; | |
import javafx.scene.layout.GridPane; | |
import javafx.stage.Stage; | |
public class Main extends Application { | |
@Override | |
public void start(Stage primaryStage) throws Exception{ //Запуск формочки | |
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); //Файл с разметкой формочки | |
primaryStage.setTitle("Minesweeper"); //Установка тайтла, тоесть названия окошка | |
primaryStage.setScene(new Scene(root, 355, 405)); //Настройка размеров окошка | |
Image icon = new Image(getClass().getResourceAsStream("icon.png"));//Иконка загружается в память | |
primaryStage.getIcons().add(icon); //И устанавливается как иконка окна | |
primaryStage.setResizable(false); //Размер окошка теперь не изменяется пользователем | |
primaryStage.show(); //Показываем окошко | |
} | |
public static void main(String[] args) { | |
launch(args); | |
} //Запуск. Дальше от этого модуля не шибко много зависит | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<?import javafx.geometry.*?> | |
<?import javafx.scene.text.*?> | |
<?import javafx.scene.effect.*?> | |
<?import javafx.scene.image.*?> | |
<?import javafx.scene.control.*?> | |
<?import java.lang.*?> | |
<?import javafx.scene.layout.*?> | |
<?import javafx.geometry.Insets?> | |
<?import javafx.scene.layout.GridPane?> | |
<?import javafx.scene.control.Button?> | |
<?import javafx.scene.control.Label?> | |
<SplitPane dividerPositions="0.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" orientation="VERTICAL" pickOnBounds="false" prefHeight="400.0" prefWidth="355.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller"> | |
<items> | |
<AnchorPane minHeight="50.0" minWidth="50.0" prefHeight="100.0" prefWidth="160.0"> | |
<children> | |
<HBox alignment="CENTER" layoutY="1.0" prefHeight="50.0" prefWidth="353.0"> | |
<children> | |
<Pane prefHeight="50.0" prefWidth="357.0"> | |
<children> | |
<ImageView fitHeight="45.0" fitWidth="45.0" layoutX="14.0" layoutY="3.0" pickOnBounds="true" preserveRatio="true"> | |
<image> | |
<Image url="@icon45.png" /> | |
</image> | |
</ImageView> | |
<Label fx:id="mineCountLabel" layoutX="59.0" layoutY="10.0" prefHeight="32.0" prefWidth="45.0"> | |
<font> | |
<Font size="22.0" /> | |
</font> | |
</Label> | |
<Button fx:id="startButton" cancelButton="true" defaultButton="true" layoutX="109.0" layoutY="13.0" mnemonicParsing="false" onAction="#StartNewGame" prefHeight="26.0" prefWidth="135.0" text="Запускайся" /> | |
</children> | |
</Pane> | |
</children> | |
</HBox> | |
</children></AnchorPane> | |
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="355.0" prefWidth="355.0"> | |
<children> | |
<GridPane fx:id="mineFieldPane" layoutX="12.0" prefHeight="345.0" prefWidth="345.0" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="5.0"> | |
<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 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 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 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 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 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 minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> | |
</rowConstraints> | |
<effect> | |
<Blend opacity="0.17" /> | |
</effect> | |
</GridPane> | |
</children></AnchorPane> | |
</items> | |
</SplitPane> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment