Проект игры ХО на Android
Проект игры ХО на Android
Видео урок по созданию игры ХО для Android устройств |
1) Создаем пустой проект
2) Создаем формы (активности)
3) Экспортируем картинки в проект
4) Описываем переключение между активностями
5) Описываем игровой процесс
6) Описываем завершение игры
Описание формы activity_main_menu.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainMenu"> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerVertical="true" android:layout_centerHorizontal="true"> <Button android:layout_width="203dp" android:layout_height="wrap_content" android:text="@string/StartButton" android:id="@+id/button" android:layout_gravity="center" android:onClick="OnClick" /> </FrameLayout> </RelativeLayout>
MainMenu.java
package com.example.vladimir.xoproject; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; /**поктлючаем тим дпнных VieW*/ import android.view.View; public class MainMenu extends AppCompatActivity { SelectXO SXO= new SelectXO(); public void OnClick(View view) { Intent i = new Intent(this, SXO.getClass()); startActivity(i); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Описание формы activity_select_xo.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.example.vladimir.xoproject.SelectXO"> - <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true"> <ImageButton android:layout_width="150dp" android:layout_height="150dp" android:id="@+id/imageButton" android:layout_gravity="center_horizontal|top" android:src="@drawable/krest" android:scaleType="fitXY" android:onClick="OnClick" /> <ImageButton android:layout_width="150dp" android:layout_height="150dp" android:id="@+id/imageButton2" android:layout_gravity="center_horizontal|bottom" android:src="@drawable/nolik" android:scaleType="fitXY" android:onClick="OnClick" /> </FrameLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentStart="true" /> </RelativeLayout>
SelectXO.java
package com.example.vladimir.xoproject; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class SelectXO extends AppCompatActivity { MainGame SMG = new MainGame(); public void OnClick(View view) { switch (view.getId() ) { case R.id.imageButton: SMG.Player=1; SMG.Comp =2; break; case R.id.imageButton2: SMG.Player=2; SMG.Comp =1; break; } Intent i = new Intent(this, SMG.getClass()); startActivity(i); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_xo); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_select_xo, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Описание формы activity_main_game.xml
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.example.vladimir.xoproject.MainGame"> - <TableLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentStart="true"> - <TableRow android:layout_width="match_parent" android:layout_height="match_parent"> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton3" android:layout_column="0" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton4" android:layout_column="1" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton5" android:layout_column="2" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> </TableRow> - <TableRow android:layout_width="match_parent" android:layout_height="match_parent"> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton6" android:layout_column="0" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton7" android:layout_column="1" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton8" android:layout_column="2" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> </TableRow> - <TableRow android:layout_width="match_parent" android:layout_height="match_parent"> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton9" android:layout_column="0" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton10" android:layout_column="1" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> <ImageButton android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageButton11" android:layout_column="2" android:src="@drawable/blank" android:scaleType="fitXY" android:onClick="OnClick" /> </TableRow> </TableLayout> </RelativeLayout>
MainGame.java
package com.example.vladimir.xoproject; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageButton; import android.view.View; import java.util.Random; import android.content.Intent; public class MainGame extends AppCompatActivity { boolean PlayerStep = true; /**список кнопок */ ImageButton[] Pole = new ImageButton[9]; /*выбор игрока и компьютера будет записан в данные поля класса */ static int Player=0, Comp=0; /**игровое поле в цифровом виде*/ int[] IntPole = {0,0,0,0,0,0,0,0,0}; //функция отображения результата игры void ShowResultGame(int State) { //создаем класс результата игры ResultGame MyResultGame= new ResultGame(); // передаем статус игры MyResultGame.StateGame=State; //Создаем класс окна Intent i = new Intent(this, MyResultGame.getClass()); //отображаем результат на экране startActivity(i); } void ChangeImage(int IndexButton, int IndexImg) { //если поле пустое то меняем картинку if (IntPole[IndexButton]==0) { //в зависимости от номера картинки меняем ее на кнопке на указанную switch (IndexImg) { case 1: Pole[IndexButton].setImageResource(R.drawable.krest); break; case 2: Pole[IndexButton].setImageResource(R.drawable.nolik); break; } //сохраняем ход в массиве IntPole[IndexButton]=IndexImg; } } //функция проверки выиграша boolean WhoWin() { //список вариантов выигрышных комбинаций int[][] WinVariant = { { //1 вариант 1,1,1, //Х Х Х 0,0,0, //_ _ _ 0,0,0 //_ _ _ }, { //2 вариант 0,0,0, //_ _ _ 1,1,1, //Х Х Х 0,0,0 //_ _ _ }, { //3 вариант 0,0,0, //_ _ _ 0,0,0, //_ _ _ 1,1,1 //Х Х Х }, { //4 вариант 1,0,0, //Х _ _ 1,0,0, //Х _ _ 1,0,0 //Х _ _ }, { //5 вариант 0,1,0, //_ Х _ 0,1,0, //_ Х _ 0,1,0 //_ Х _ }, { //6 вариант 0,0,1, //_ _ Х 0,0,1, //_ _ Х 0,0,1 //_ _ Х }, { //7 вариант 1,0,0, //Х _ _ 0,1,0, //_ Х _ 0,0,1 //_ _ Х }, { //8 вариант 0,0,1, //_ _ Х 0,1,0, //_ Х _ 1,0,0 //Х _ _ } }; //Обьявляем поле игрока для проверки int[] TestMapPlayer = new int[9]; //Обьявляем поле ПК для проверки int[] TestMapComp = new int[9]; //перебираем поле и собираем отдельно значения игрока и ПК for(int I=0; I<9; I++) { //если значение совпало с номером игрока то записываем его поле if(IntPole[I]==Player) TestMapPlayer[I] = 1; //если значение совпало с номером игрока то записываем его в поле if(IntPole[I]==Comp) TestMapComp[I] = 1; } //выбираем вариант для сравнения for(int V = 0; V<8; V++) { //количество совпадений у ПК и игрока int WinStateComp=0, WinStateUser=0; //Перебираем значения из варианта for(int Z=0; Z<9; Z++) { if(WinVariant[V][Z]==1) { //если в поле игрока тоже 1 то увеличиваем значение совпадений if(TestMapPlayer[Z]==1) WinStateUser++; //если в поле компьютера 1 то увеличиваем значение совпадений if(TestMapComp[Z]==1) WinStateComp++; } } //проверяем не выиграл ли кто то if(WinStateUser==3) { //выиграл Игрок ShowResultGame(1); return true; } if(WinStateComp ==3) { //выиграл ПК ShowResultGame(2); return true; } } return false; } //функция провекри возможности хода boolean canStep() { //перебираем все ячейки for(int I=0; I<9; I++ ) //если есть еще ходы то ходим if(IntPole[I]==0) return true; //иначе будем возвращать ложь return false; } void StepPC() { //проверяем не выиграл ни кто то WhoWin(); //создаем генератор случайных чисел Random R = new Random(); //получаем случайное число int Index = R.nextInt(9); //пока не сделаем ход ходим while ((!PlayerStep)&&(canStep())) { //если поле пустое то ходим if(IntPole[Index]==0) { ChangeImage(Index,Comp); PlayerStep=true; }else { //находим другую клетку случайным образом Index = R.nextInt(9); } } //если есть еще ходы пробуем ходить if((canStep()==false)&& (WhoWin())) //если ходы закончились то значит ничья ShowResultGame(0); } //функция обработки нажатия на кноаку public void OnClick(View view) { if(PlayerStep==true){ int IndexButton=0; switch ( view.getId()) { case R.id.imageButton3: IndexButton=0; break; case R.id.imageButton4: IndexButton=1; break; case R.id.imageButton5: IndexButton=2; break; case R.id.imageButton6: IndexButton=3; break; case R.id.imageButton7: IndexButton=4; break; case R.id.imageButton8: IndexButton=5; break; case R.id.imageButton9: IndexButton=6; break; case R.id.imageButton10: IndexButton=7; break; case R.id.imageButton11: IndexButton=8; break; } //записывем ход и отображаем его на поле ChangeImage(IndexButton,Player); PlayerStep =false; StepPC(); }else { StepPC(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_game); /**получаем 9 кнопок и загоняем их все в 1 массив */ Pole[0] = (ImageButton)findViewById(R.id.imageButton3); Pole[1] = (ImageButton)findViewById(R.id.imageButton4); Pole[2] = (ImageButton)findViewById(R.id.imageButton5); Pole[3] = (ImageButton)findViewById(R.id.imageButton6); Pole[4] = (ImageButton)findViewById(R.id.imageButton7); Pole[5] = (ImageButton)findViewById(R.id.imageButton8); Pole[6] = (ImageButton)findViewById(R.id.imageButton9); Pole[7] = (ImageButton)findViewById(R.id.imageButton10); Pole[8] = (ImageButton)findViewById(R.id.imageButton11); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main_game, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Описание формы activity_result_game.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.example.vladimir.xoproject.ResultGame"> - <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerHorizontal="true" android:layout_alignParentTop="true"> <TextView android:layout_width="158dp" android:layout_height="49dp" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Ничья" android:id="@+id/GameResult" android:layout_gravity="center" android:textAlignment="center" /> <Button android:layout_width="243dp" android:layout_height="wrap_content" android:text="В главное меню" android:id="@+id/button2" android:layout_gravity="center_horizontal|bottom" /> </FrameLayout> </RelativeLayout>
ResultGame.java
package com.example.vladimir.xoproject; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class ResultGame extends AppCompatActivity { static int StateGame=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result_game); TextView A = (TextView)findViewById(R.id.GameResult); switch (StateGame) { case 0: A.setText("Ничья");break; case 1: A.setText("Вы выиграли");break; case 2: A.setText("Вы проиграли");break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_result_game, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }