Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sarah J. Olivas - Spruce #66

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
5 changes: 2 additions & 3 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
"eslint:recommended",
"plugin:react/recommended",
"plugin:jsx-a11y/recommended",
"plugin:react-hooks/recommended",
"plugin:jest/recommended",
"plugin:testing-library/react"
"plugin:react-hooks/recommended"
// "plugin:testing-library/react"
],
"parserOptions": {
"ecmaFeatures": {
Expand Down
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# React Tic-Tac-Toe

## Please Read First!

The digital campus' version of Tic-Tac-Toe differs from the original in the following ways:
- We will *not* be using `main` branch. Follow step 6 in the **One-Time Project Setup** to change branches.
- Wave 1 has been completed for you; however, it would help you understand the flow of data by reviewing the code written for Wave 1.
- Wave 3's `checkForWinner` function has been created for you; however, read through Wave 3 instructions to figure out how and where to use it.

## Skills Assessed

- Following directions and reading comprehension
Expand Down Expand Up @@ -81,9 +88,15 @@ We can run `yarn install` multiple times safely, but we only need to do this onc

The file `package.json` contains details about our project, the scripts available, and the dependencies needed. We can inspect this file when we are curious about the details of our dependencies.

6. Follow the directions in the "Getting Started" section.
6. We will not being using `main` branch. Make sure you are working from `digital-starter` by running:

```bash
$ git checkout digital-starter
```

7. Follow the directions in the "Getting Started" section.

7. Follow the directions in the "Project Requirements" section.
8. Follow the directions in the "Project Requirements" section.

## Project Development Workflow

Expand Down
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
"react-app"
]
},
"browserslist": {
Expand Down
122 changes: 105 additions & 17 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,26 @@ import './App.css';

import Board from './components/Board';

const PLAYER_1 = 'X';
const PLAYER_2 = 'O';
const PLAYER_1 = 'x';
const PLAYER_2 = 'o';
Comment on lines -6 to +7

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We gave bad guidance here. This should have been

const PLAYER_1 = 'x';
const PLAYER_2 = 'o';

since the tests were all written for lower case x and o. But it looks like you took care of this on your own!


const generateSquares = () => {
// builds the structure (state of our board)
// creating rows and columns using for loops and nested structures.
// each object within the nestes lists is a representation of one square.
// each object (square) has an id and value.
const squares = [];

let currentId = 0;

// says to loop 3 times. for 3 times, add a new inner array.
for (let row = 0; row < 3; row += 1) {
// getting pushed into array squares.
squares.push([]);
// loop 3 times.
for (let col = 0; col < 3; col += 1) {
// pushing an object with an id and value.
// id starts at 0 and increases by 1 every time we add a new object to our nested structure.
squares[row].push({
id: currentId,
value: '',
Expand All @@ -26,43 +35,122 @@ const generateSquares = () => {
};

const App = () => {
// sqaures is the name of the variable we are using to store state.
// The value we are using to initialize useState is the result of calling generateSquares().
// This starts state off as a 2D array of JS objects with
// empty value and unique ids.
const [squares, setSquares] = useState(generateSquares());
const [squares, setSquares] = useState(generateSquares()); // if the parentheses are removed from the function call, it will still work, because if the value is a function reference, then React will call the function the first time we need to initialize state, but every time after that it won't call the function. It can tell the difference between a function and not a function, so technically the no parentheses is a little bit more efficient, because they call the function every time, building a new 2D array pass it into useState the first time and ignore it everytime after that, but we will have called generateSquares ourselves every time. Without parentheses, we give it a function reference to generate squares and React will just call that function only the first timr and use the return value as an initial vlaue for the state.
const [player, setPlayer] = useState(PLAYER_1);

// Wave 2
// You will need to create a method to change the square
// When it is clicked on.
// Then pass it into the squares as a callback
const onClickCallback = (id) => {
// doesn't allow anymore moves after a win.
if (winner) {
return;
}
Comment on lines +50 to +53

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can check the winner due to closure semantics (winner is defined in the outer execution context).


// variable 'move' flag for valid move
let move = false;
const updateSquares = squares.map((row) =>
row.map((pos) => {
if (pos.id !== id || pos.value !== '') {
return pos;
}

// valid move if passes all checks
move = true;

// create new array that includes played square(s)
const playedSquare = { ...pos, value: player };
return playedSquare;
})
);
Comment on lines +57 to +70

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good use of double mapping and spreading the player square so that when a move is made, the new state is no longer connected to the old state (avoid state cross contamination).


// if valid move, state for squares and player updates
if (move) {
setSquares(updateSquares);
// ternary swithes player state
setPlayer(player === PLAYER_1 ? PLAYER_2 : PLAYER_1);
}
};

const checkForWinner = () => {
// Complete in Wave 3
// You will need to:
// 1. Go accross each row to see if
// 3 squares in the same row match
// i.e. same value
// 2. Go down each column to see if
// 3 squares in each column match
// 3. Go across each diagonal to see if
// all three squares have the same value.
let i = 0;
// Check all the rows and columns for a winner by doing 2D indexing.
// have to check all straight across, down, and diagonal positions or if any of the winning positions are blank to find a winner.
// the winning positions much all be equal and not an empty string (blank square).
while (i < 3) {
if (
// checking rows (row value is the same on each check while the column shifts)
squares[i][0].value === squares[i][1].value &&
squares[i][2].value === squares[i][1].value &&
// this checks if it is an 'x' or 'o' not an empty string ''.
squares[i][0].value !== ''
) {
return squares[i][0].value;
} else if (
// checking columns (column remains the same on each check while the row shifts)
squares[0][i].value === squares[1][i].value &&
squares[2][i].value === squares[1][i].value &&
squares[0][i].value !== ''
) {
return squares[0][i].value;
}
i += 1;
}
// Check Top-Left to bottom-right diagonal
if (
squares[0][0].value === squares[1][1].value &&
squares[2][2].value === squares[1][1].value &&
squares[1][1].value !== ''
) {
return squares[0][0].value;
}

// Check Top-right to bottom-left diagonal
if (
squares[0][2].value === squares[1][1].value &&
squares[2][0].value === squares[1][1].value &&
squares[1][1].value !== ''
) {
return squares[0][2].value;
}

// if no winner is found (can possibly use this to detect a tie or return tied game)
return null;
};

// resets squares state and player state.
const resetGame = () => {
// Complete in Wave 4
setSquares(generateSquares());
setPlayer(PLAYER_1);
};
Comment on lines +126 to +130

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep. Resetting the game essentially comes down setting the pieces of state back to their initial values.


// checkForWinner() being used to update the status line until we have a winner. Then the winner is diplayed.
const winner = checkForWinner();
const statusLine = () => {
if (winner) {
return `Winner is ${winner}`;
}
return `${player}'s turn`;
};
Comment on lines +134 to 139

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice helper to update the status line for the player turn or game winner.


return (
<div className="App">
<header className="App-header">
<h1>React Tic Tac Toe</h1>
<h2>The winner is ... -- Fill in for wave 3 </h2>
<button>Reset Game</button>
<h2>{statusLine()} </h2>
<button onClick={() => resetGame()}>Reset Game</button>
</header>
<main>
<Board squares={squares} />
{/* properties being passed. React is going to take this and anything that we've put as attrs it's going to make a new dict of values and each of the attr names is going to become a key and the value is the JS expression in the curly braces (state variable) */}
{/* no matter how many properties we have listed when we call a component, it all gets packaged up into one dictionary, where the keys match the names of the attrs. */}
<Board squares={squares} onClickCallback={onClickCallback} />
</main>
</div>
);
};

export default App;
Loading