Skip to content

Instantly share code, notes, and snippets.

@sirmmo
Created October 6, 2021 12:07
Show Gist options
  • Save sirmmo/f0d27f9ba46ccf2e9c36246d69ab1d3a to your computer and use it in GitHub Desktop.
Save sirmmo/f0d27f9ba46ccf2e9c36246d69ab1d3a to your computer and use it in GitHub Desktop.
ispra_react_intro
import React from 'react';
import Board from './Board';
import './App.css';
class App extends React.Component{
render(){
return (
<div className="App">
<header className="App-header">
<Board></Board>
</header>
</div>
);
}
}
export default App;
import React from 'react';
import Square from './Square';
class Board extends React.Component{
constructor(props){
super(props);
this.state = {
cells: Array(9).fill(null),
nextPlayer: 'X'
}
}
handleClick(i){
if (this.calculateWinner(this.state.cells)){
alert('c\'è già un vincitore. La partita è finita.');
} else {
if (!this.state.cells[i]){
const squares = this.state.cells.slice();
squares[i] = this.state.nextPlayer;
let next = 'X';
if (this.state.nextPlayer === 'X'){
next = 'O';
}
this.setState({
cells: squares,
nextPlayer: next
});
} else {
alert('Non puoi selezionare una cella già utilizzata');
}
}
}
renderSquare(i){
return(
<Square
value={this.state.cells[i]}
onClick={() => this.handleClick(i)}
/>
)
}
calculateWinner(squares){
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++){
if(squares[lines[i][0]] === squares[lines[i][1]] && squares[lines[i][0]] === squares[lines[i][2]]){
return squares[lines[i][0]];
}
}
return null;
}
render(){
const winner = this.calculateWinner(this.state.cells);
return (
<div>
Vince: {winner};
<h3>Turno di: {this.state.nextPlayer}</h3>
<div className="row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
)
}
}
export default Board;
import React from 'react';
class Square extends React.Component{
render() {
return(
<button onClick={() => this.props.onClick() }>
{this.props.value}
</button>
);
}
}
export default Square;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment