Skip to content

Instantly share code, notes, and snippets.

@Archakov06
Last active January 6, 2018 11:04
Show Gist options
  • Save Archakov06/baa3724c40430fbdc3e945ebb2737f19 to your computer and use it in GitHub Desktop.
Save Archakov06/baa3724c40430fbdc3e945ebb2737f19 to your computer and use it in GitHub Desktop.
import Room from '../models/Room';
import { isEmpty, shuffle } from 'lodash';
import wordsList from '../public/words';
class RoomController {
get(req, res, next) {
const { room } = req.params;
Room.find({ room }, (err, room) => {
if (!err && !isEmpty(room)) {
res.json(room);
} else {
res.json({ message: 'Not found' });
}
});
next();
}
create(req, res, next) {
const { room } = req.params;
const randomWords = wordsList.slice(0, 25).sort(() => 0.5 - Math.random());
const firstTeam = Math.round(Math.random()) ? 'blue' : 'red';
let words = {};
const gridNum = 5;
const cardsNum = Math.floor(gridNum * gridNum / 3);
const emptyCardsNum = cardsNum - 1;
const generateCards = (num, type) => {
let words = randomWords.splice(0, num + (firstTeam === type ? 1 : 0));
return words.map(s => ({
[s]: type,
selected: false,
}));
};
const redCards = generateCards(cardsNum, 'red');
const blueCards = generateCards(cardsNum, 'blue');
const emptyCards = generateCards(emptyCardsNum, 'empty');
const deathCard = generateCards(1, 'death');
const result = [
...redCards,
...blueCards,
...emptyCards,
...deathCard,
].sort(() => 0.5 - Math.random());
const obj = {
words: result,
firstTeam,
};
Room.create(obj, (err, room) => {
if (!err && !isEmpty(room)) {
res.json(room);
} else {
res.json({ message: 'error' });
}
});
next();
}
check(req, res, next) {
const { room } = req.params;
console.log(req.body, room);
const { index, team } = req.body;
Room.findById(room, (err, room) => {
if (!err && !isEmpty(room)) {
const { words } = room;
const isCorrect = !isEmpty(
words.filter((o, i) => {
if (i === parseInt(index)) {
const key = Object.keys(o)[0];
const curTeam = o[key];
if (team === curTeam) {
return true;
} else {
return false;
}
} else {
return false;
}
})[0],
);
if (isCorrect) {
const mutated = words.map((o, i) => {
if (i === parseInt(index)) {
o.selected = true;
}
return o;
});
Room.findByIdAndUpdate(room, { words: mutated }, err => {
if (err) {
res.status(500).json({ message: 'error' });
}
res.json({ message: 'correct' });
});
}
} else {
res.json({ message: 'Not found' });
}
});
}
}
export default RoomController;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment