-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGamePlay.java
More file actions
92 lines (77 loc) · 2.52 KB
/
GamePlay.java
File metadata and controls
92 lines (77 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package ticTacToe;
import java.util.Arrays;
public class GamePlay {
private int turnsLeft;
private String[][] moves;
private String currentPlayer;
public GamePlay(){
this.turnsLeft = 9;
moves = new String[3][3];
currentPlayer = "Turn: X";
//inialise array to remove Nulls
for(String[] ary: moves){
Arrays.fill(ary, " ");
}
}
public boolean gameOver(){
if(this.turnsLeft > 0){
return false;
}
return true;
}
public int getTurnsLeft() {
return turnsLeft;
}
public void setTurnsLeft(int turnsLeft) {
this.turnsLeft = turnsLeft;
}
public void addMove(int row, int column) {
this.moves[row][column] = getButtonPlayer();
//increment player
if(currentPlayer.equals("Turn: X")){
currentPlayer = "Turn: O";
} else {
currentPlayer = "Turn: X";
}
//update number of turns left
turnsLeft--;
}
public boolean checkFor3inaRow(String p){
//returns true if there is a winning line
for(int i = 0; i < 3; i++){
//check for vertical 3 in a row
if(this.moves[i][0].equals(p) && this.moves[i][1].equals(p) && this.moves[i][2].equals(p) ){
return true;
}
//check for horizontal 3 in a row
if(this.moves[0][i].equals(p) && this.moves[1][i].equals(p) && this.moves[2][i].equals(p) ){
return true;
}
}
//check for diagonal 3 in a row
if(this.moves[0][0].equals(p) && this.moves[1][1].equals(p) && this.moves[2][2].equals(p) ){
return true;
}
if(this.moves[2][0].equals(p) && this.moves[1][1].equals(p) && this.moves[0][2].equals(p) ){
return true;
}
return false;
}
public boolean checkForWinner(){
if(checkFor3inaRow("X") || checkFor3inaRow("O")){
return true;//there is a winner
}
return false; //no winner yet
}
public String getCurrentPlayer() {
return currentPlayer;
}
public void setCurrentPlayer(String currentPlayer) {
this.currentPlayer = currentPlayer;
}
public String getButtonPlayer(){
//Returns X or O to populate button text
String[] bits = currentPlayer.split(" ");
return bits[1];
}
}