Last active
August 21, 2018 01:30
-
-
Save aspencer8111/c89d78cc52cfec8614d96de2a8b78d60 to your computer and use it in GitHub Desktop.
For minesweeper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
const BASE_URL = 'https://minesweeper-api.herokuapp.com/' | |
class Minesweeper extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
game: { | |
board: [], | |
level: 0 | |
} | |
} | |
} | |
createGame() { | |
fetch(`${BASE_URL}games`, { | |
method: "POST", | |
body: JSON.stringify({ difficulty: this.state.level }), | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}) | |
.then(resp => resp.json()) | |
.then(newGame => { | |
console.log(newGame) | |
this.setState({ | |
game: newGame | |
}) | |
}) | |
} | |
componentDidMount() { | |
this.createGame() | |
} | |
checkTheAPI = (action, row, col) => { | |
fetch(`${BASE_URL}games/${this.state.game.id}/${action}`, { | |
method: "POST", | |
body: JSON.stringify({ row: row, col: col }), | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}) | |
.then(resp => resp.json()) | |
.then(newGameState => { | |
this.setState({ | |
game: newGameState, | |
}, () => { | |
this.props.updateMessage(this.state.game.state) | |
}) | |
}) | |
} | |
handleCellClick = (row, col) => { | |
if (this.state.game.state !== "youLost" && this.state.game.state !== "youWon") { | |
this.checkTheAPI("check", row, col) | |
} | |
} | |
handleFlaggedCell = (event, row, col) => { | |
event.preventDefault() | |
this.checkTheAPI("flag", row, col) | |
} | |
resetEvent = () => { | |
this.createGame() | |
} | |
render () { | |
return( | |
<div> | |
Currently Playing: {this.state.game.id} | |
<div> | |
<table> | |
<tbody> | |
{this.state.game.board.map((row, i) => { | |
return ( | |
<tr key={i}> | |
{row.map((col, j) => { | |
return ( | |
<td key={j}>{j}</td> | |
) | |
})} | |
</tr> | |
) | |
})} | |
</tbody> | |
</table> | |
</div> | |
</div> | |
); | |
} | |
} | |
export default Minesweeper; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment