Skip to content

Instantly share code, notes, and snippets.

View MikeShi42's full-sized avatar
πŸ’­
πŸš€

Mike Shi MikeShi42

πŸ’­
πŸš€
View GitHub Profile
socket.on('actuate', function (data) {
const { grid, metadata } = data; // Get grid and metadata properties from client
const move = {
playerIndex,
grid,
metadata,
};
// Emit the move to all other clients
socket.on('disconnect', function() {
console.log(`Player ${playerIndex} Disconnected`);
connections[playerIndex] = null;
});
...
</div>
<!-- Below is the script tag you need to add! -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script src="js/utils/keyboard_input_manager.js"></script>
...
window.requestAnimationFrame(function () {
var socket = io.connect(window.location.origin);
...
class GameManager {
constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) {
this.size = size; // Size of the grid
this.inputManager = new InputManager();
...
constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) {
this.size = size; // Size of the grid
this.inputManager = new InputManager();
this.storageManager = new StorageManager;
// Change Actuator to take in remotePlayer as an argument!
this.actuator = new Actuator(remotePlayer);
this.startTiles = 2;
sendRemoteMove(grid, metadata) {
if (!this.remotePlayer) {
this.socket.emit('actuate', { grid: grid, metadata: metadata });
}
}
// Sends the updated grid to the actuator
actuate() {
if (this.storageManager.getBestScore() < this.score) {
this.storageManager.setBestScore(this.score);
}
// Clear the state when the game is over (game over only, not win)
if (this.over) {
this.storageManager.clearGameState();
} else {
handleRemoteMove(data) {
const grid = data.grid;
const metadata = data.metadata;
this.actuator.actuate(grid, metadata);
}
constructor(socket, remotePlayer, size, InputManager, Actuator, StorageManager) {
...
// Add these two lines
this.remotePlayer = remotePlayer;
this.socket = socket;
// Add this new if statement
if (this.remotePlayer) {
this.socket.on('move', this.handleRemoteMove.bind(this));