summaryrefslogtreecommitdiff
path: root/frontend/src/sagas/game.js
blob: dc92e89a4bed77a48ad458baf340e3f69c3fba24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { eventChannel } from 'redux-saga';
import { apply, call, put, take } from 'redux-saga/effects';
import type { ApiPlayerTurnInfo, ApiPreparedCard, ApiTable } from '../api/model';
import { SevenWondersSession } from '../api/sevenWondersApi';
import { actions } from '../redux/actions/game';
import { types } from '../redux/actions/game';
import { types as gameTypes } from '../redux/actions/lobby';

function* watchPlayerReady(session: SevenWondersSession, gameId: number) {
  const channel = yield eventChannel(session.watchPlayerReady(gameId));
  try {
    while (true) {
      const username = yield take(channel);
      yield put(actions.receivePlayerReady(username));
    }
  } finally {
    yield apply(channel, channel.close);
  }
}

function* watchTableUpdates(session: SevenWondersSession, gameId: number) {
  const channel = yield eventChannel(session.watchTableUpdates(gameId));
  try {
    while (true) {
      const table: ApiTable = yield take(channel);
      yield put(actions.receiveTableUpdate(table));
    }
  } finally {
    yield apply(channel, channel.close);
  }
}

function* watchPreparedCards(session: SevenWondersSession, gameId: number) {
  const channel = yield eventChannel(session.watchPreparedCards(gameId));
  try {
    while (true) {
      const preparedCard: ApiPreparedCard = yield take(channel);
      yield put(actions.receivePreparedCard(preparedCard));
    }
  } finally {
    yield apply(channel, channel.close);
  }
}

function* sayReady(session: SevenWondersSession) {
  while (true) {
    yield take(types.REQUEST_SAY_READY);
    yield apply(session, session.sayReady);
  }
}

function* prepareMove(session: SevenWondersSession) {
  while (true) {
    let action = yield take(types.REQUEST_PREPARE_MOVE);
    yield apply(session, session.prepareMove, [action.move]);
  }
}

function* watchTurnInfo(session: SevenWondersSession) {
  const channel = yield eventChannel(session.watchTurnInfo());
  try {
    while (true) {
      const turnInfo: ApiPlayerTurnInfo = yield take(channel);
      yield put(actions.receiveTurnInfo(turnInfo));
    }
  } finally {
    yield apply(channel, channel.close);
  }
}

export function* gameSaga(session: SevenWondersSession) {
  const { gameId } = yield take(gameTypes.ENTER_GAME);
  console.log('Entered game!', gameId);
  yield [
    call(watchPlayerReady, session, gameId),
    call(watchTableUpdates, session, gameId),
    call(watchPreparedCards, session, gameId),
    call(sayReady, session),
    call(prepareMove, session),
    call(watchTurnInfo, session)
  ];
}
bgstack15