Question

I need help developing this app using java in android studio Assignment: Tic-Tac-Toe app User interface...

I need help developing this app using java in android studio

Assignment: Tic-Tac-Toe app

User interface

Operation

The app allows the user to play a game of Tic-Tac-Toe.

The user can click the New Game button at any time to start a new game.

The app displays other messages to the user as the game progresses such as (1) whose turn it

is, (2) if a player wins, and (3) if the game ends in a tie.

Specifications

The app uses buttons for the nine Tic-Tac-Toe squares.

Make the app work well in portrait and landscape orientations.

The app should save the game when the user switches orientations or navigates away from

the app and then back to it.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the Java Code in Android Studio for "Tic-Tac-Toe" Game:-

1. Creating the Board - First step is to create the Board for the Tic-Tac-Toe game. The Board class will store the elements of the grid in an array and will contain a boolean indicating if the game is ended or no.

The play method will let you to set the mark of the currentPlayer on the grid at a given (x,y) position. A changePlayer method will be used to change the current player for the next play. Besides, a computer method is defined to let the user to randomly place a mark on the grid. Finally, we define a checkEnd method to check if the game is ended. The game is ended if there is a winner or a draw : all the cases of the grids are filled and no one wins the game.

import java.util.Random;

public class Board {

private static final Random RANDOM = new Random();
private char[] elts;
private char currentPlayer;
private boolean ended;

public Board() {
elts = new char[9];
newGame();
}

public boolean isEnded() {
return ended;
}

public char play(int x, int y) {
if (!ended && elts[3 * y + x] == ' ') {
elts[3 * y + x] = currentPlayer;
changePlayer();
}

return checkEnd();
}

public void changePlayer() {
currentPlayer = (currentPlayer == 'X' ? 'O' : 'X');
}

public char getElt(int x, int y) {
return elts[3 * y + x];
}

public void newGame() {
for (int i = 0; i < elts.length; i++) {
elts[i] = ' ';
}

currentPlayer = 'X';
ended = false;
}

public char checkEnd() {
for (int i = 0; i < 3; i++) {
if (getElt(i, 0) != ' ' &&
getElt(i, 0) == getElt(i, 1) &&  
getElt(i, 1) == getElt(i, 2)) {
ended = true;
return getElt(i, 0);
}

if (getElt(0, i) != ' ' &&
getElt(0, i) == getElt(1, i) &&  
getElt(1, i) == getElt(2, i)) {
ended = true;
return getElt(0, i);
}
}

if (getElt(0, 0) != ' ' &&  
getElt(0, 0) == getElt(1, 1) &&  
getElt(1, 1) == getElt(2, 2)) {
ended = true;
return getElt(0, 0);
}

if (getElt(2, 0) != ' ' &&  
getElt(2, 0) == getElt(1, 1) &&  
getElt(1, 1) == getElt(0, 2)) {
ended = true;
return getElt(2, 0);
}

for (int i = 0; i < 9; i++) {
if (elts[i] == ' ')
return ' ';
}

return 'T';
}

public char computer() {
if (!ended) {
int position = -1;

do {
position = RANDOM.nextInt(9);
} while (elts[position] != ' ');

elts[position] = currentPlayer;
changePlayer();
}

return checkEnd();
}
}

2. Rendering the Board on the Screen - Next step is to create a BoardView class to render our Board on the screen. Our BoardView will extend the View class and we will draw the Board and its elements on the Canvas object associated. It is a good way to discover how to draw simple shapes on a Canvas of a specific View too. Furthermore, we must manage the touch events of the users on the Board to let it to play to our Tic-Tac-Toe game. For that, we override the onTouchEvent method from the View parent class. In that method, we convert a point touched on the screen to a case on our grid. Then, we make the play on the Board object. After that, we need to call the gameEnded method of the parent activity if the game is ended to display the win dialog to the user. If not, we make the play for the computer. Like you can see, the heart of the logic game will be located in this method.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class BoardView extends View {

private static final int LINE_THICK = 5;
private static final int ELT_MARGIN = 20;
private static final int ELT_STROKE_WIDTH = 15;
private int width, height, eltW, eltH;
private Paint gridPaint, oPaint, xPaint;
private GameEngine gameEngine;
private MainActivity activity;

public BoardView(Context context) {
super(context);
}

public BoardView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
gridPaint = new Paint();
oPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
oPaint.setColor(Color.RED);
oPaint.setStyle(Paint.Style.STROKE);
oPaint.setStrokeWidth(ELT_STROKE_WIDTH);
xPaint = new Paint(oPaint);
xPaint.setColor(Color.BLUE);
}

public void setMainActivity(MainActivity a) {
activity = a;
}

public void setGameEngine(GameEngine g) {
gameEngine = g;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
height = View.MeasureSpec.getSize(heightMeasureSpec);
width = View.MeasureSpec.getSize(widthMeasureSpec);
eltW = (width - LINE_THICK) / 3;
eltH = (height - LINE_THICK) / 3;

setMeasuredDimension(width, height);
}

@Override
protected void onDraw(Canvas canvas) {
drawGrid(canvas);
drawBoard(canvas);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
if (!gameEngine.isEnded() && event.getAction() == MotionEvent.ACTION_DOWN) {
int x = (int) (event.getX() / eltW);
int y = (int) (event.getY() / eltH);
char win = gameEngine.play(x, y);
invalidate();

if (win != ' ') {
activity.gameEnded(win);
} else {
// computer plays ...
win = gameEngine.computer();
invalidate();

if (win != ' ') {
activity.gameEnded(win);
}
}
}

return super.onTouchEvent(event);
}

private void drawBoard(Canvas canvas) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
drawElt(canvas, gameEngine.elt(i, j), i, j);
}
}
}

private void drawGrid(Canvas canvas) {
for (int i = 0; i < 2; i++) {
// vertical lines
float left = eltW * (i + 1);
float right = left + LINE_THICK;
float top = 0;
float bottom = height;

canvas.drawRect(left, top, right, bottom, gridPaint);

// horizontal lines
float left2 = 0;
float right2 = width;
float top2 = eltH * (i + 1);
float bottom2 = top2 + LINE_THICK;

canvas.drawRect(left2, top2, right2, bottom2, gridPaint);
}
}

private void drawElt(Canvas canvas, char c, int x, int y) {
if (c == 'O') {
float cx = (eltW * x) + eltW / 2;
float cy = (eltH * y) + eltH / 2;

canvas.drawCircle(cx, cy, Math.min(eltW, eltH) / 2 - ELT_MARGIN * 2, oPaint);

} else if (c == 'X') {
float startX = (eltW * x) + ELT_MARGIN;
float startY = (eltH * y) + ELT_MARGIN;
float endX = startX + eltW - ELT_MARGIN * 2;
float endY = startY + eltH - ELT_MARGIN;

canvas.drawLine(startX, startY, endX, endY, xPaint);

float startX2 = (eltW * (x + 1)) - ELT_MARGIN;
float startY2 = (eltH * y) + ELT_MARGIN;
float endX2 = startX2 - eltW + ELT_MARGIN * 2;
float endY2 = startY2 + eltH - ELT_MARGIN;

canvas.drawLine(startX2, startY2, endX2, endY2, xPaint);
}
}

}

3. Creating the UI for our Game - The biggest part of the user interface of our Tic-Tac-Toe game is managed in the BoardView class. So, we just need to set our BoardView component into a RelativeLayout parent View in our layout file:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ssaurel.tictactoe.MainActivity">

<com.ssaurel.tictactoe.BoardView
android:id="@+id/board"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>

</RelativeLayout>

4. Starting a new Game:- To star a new game, the user will have to click on a load item in the action bar of our application. So, we add the item in a main.xml menu file under /res/menu:-

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
android:id="@+id/action_new_game"
android:orderInCategory="50"
android:title="New Game"
app:showAsAction="always" />

</menu>

5. Assemble all the pieces of the puzzle - Last step is to assemble all the components created previously in the MainActivity class. In the onCreate method, we create the Board object and then we pass it in parameter of the BoardView got from the main layout of the application. Then, we connect the new game item of the action bar with the newGame method of the Board object to create a new game when the user will click on it. Finally, we define the gameEnded method which was called in the BoardView object.

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

private BoardView boardView;
private GameEngine gameEngine;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boardView = (BoardView) findViewById(board);
gameEngine = new GameEngine();
boardView.setGameEngine(gameEngine);
boardView.setMainActivity(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_new_game) {
newGame();
}

return super.onOptionsItemSelected(item);
}

public void gameEnded(char c) {
String msg = (c == 'T') ? "Game Ended. Tie" : "GameEnded. " + c + " win";

new AlertDialog.Builder(this).setTitle("Tic Tac Toe").
setMessage(msg).
setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
newGame();
}
}).show();
}

private void newGame() {
gameEngine.newGame();
boardView.invalidate();
}

}

The output is attached below:-

Please let me know in case of any clarifications required. Thanks!

Add a comment
Know the answer?
Add Answer to:
I need help developing this app using java in android studio Assignment: Tic-Tac-Toe app User interface...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use di...

    18. Tic-Tac-Toe Game rite a program that allows two players to play a game of tic-tac-toe. Use dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Write . Displays the contents of the board array. . Allows player 1 to select a location on the board for an X. The program should ask the...

  • I need screenshots for this solution done in Flowgorithm. Thank you. Tic-Tac-Toe Game Design a program...

    I need screenshots for this solution done in Flowgorithm. Thank you. Tic-Tac-Toe Game Design a program that allows two players to play a game of tic-tac-toe. Use a two- dimensional String array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: a. Displays the contents of the board array. b. Allows player 1 to select a location...

  • Assignment C++: Rock-Scissor-Paper & Tic-Tac-Toe i need you to write two different program for RSP and...

    Assignment C++: Rock-Scissor-Paper & Tic-Tac-Toe i need you to write two different program for RSP and TTT: R-S-P Requirement: - write one program that mimics the Rock-Scissor-Paper game. This program will ask user to enter an input (out of R-S-P), and the computer will randomly pick one and print out the result (user wins / computer wins). - User's input along with computer's random pick will be encoded in the following format: -- user's rock: 10 -- user's scissor: 20...

  • I need to create a Tic Tac Toe program in C++. These are the requirements Write...

    I need to create a Tic Tac Toe program in C++. These are the requirements Write a program that allows the computer to play TicTacToe against a human player or allow two human players to play one another. Implement the following conditions: The player that wins the current game goes first in the next round, and their symbol is X. The other player will be O. Keep track of the number of games played, wins, and draws for each player....

  • Tic-Tac-Toe Game Write a program that allows two players to play a game of tic-tac-toe. Use...

    Tic-Tac-Toe Game Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Displays the contents of the board array. Allows player 1 to select a location on the board for an X. The program should ask the user to enter...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • Hey guys, I need help writing a Tic-Tac-Toe game programmed in Java. The game has to...

    Hey guys, I need help writing a Tic-Tac-Toe game programmed in Java. The game has to be a 1D (One-Dimension) array board NOT 2D. It has to be a human plays against the computer type of Tic-Tac-Toe. Here is the requirements for the program. PLEASE NO COPY AND PASTE ANSWER. Thank you in advance! You will develop a program in which a human plays against the computer. 1. Validate user input at every opportunity. a. Do not allow number entries...

  • In a game of Tic Tac Toe, two players take turns making an available cell in...

    In a game of Tic Tac Toe, two players take turns making an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A stalemate occurs when all the cells on the grid have been filled with tokens and neither player has achieved a win. Write a program...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT