Skip to content

Instantly share code, notes, and snippets.

@xcaptain
Last active January 11, 2018 12:09
Show Gist options
  • Save xcaptain/ba8ebdb8ad9ab512f27262625471395f to your computer and use it in GitHub Desktop.
Save xcaptain/ba8ebdb8ad9ab512f27262625471395f to your computer and use it in GitHub Desktop.
pusher test
import Pusher from "pusher-js";
import axios from 'axios';
// online token
const jwtToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiAF7vaVJ0P4s';
const pusher = new Pusher("f38f86445b8c318d6ac1", {
authEndpoint: "http://21ji.wanuq.com/pusher/auth",
authTransport: "ajax",
auth: {
headers: {
Authorization: "Bearer " + jwtToken
}
},
cluster: "ap1"
});
var userId = null;
let channelId = "presence-ticket-field-unmatched-1";
let unmatchedChannel = pusher.subscribe(channelId);
unmatchedChannel.bind('pusher:subscription_succeeded', (members) => {
let me = members.me;
userId = me.id;
}).bind('matched', (message) => {
let userIds = message.user_ids;
if (userIds.find((value) => {
return value == userId;
})) { // 匹配成功,进入游戏场
let gameChannelId = message.room_channel_id;
let gameId = message.room_id;
pusher.unsubscribe(channelId);
console.log('connected to game channel', gameChannelId);
let gameChannel = pusher.subscribe(gameChannelId);
gameChannel.bind('start', (message) => {
let nextUserId = message.next_user_id;
let currentState = message.room_state;
if (nextUserId == userId) { // 下一步操作人是自己就调用接口出牌
setTimeout(() => {
autoPlay(currentState, 1, gameId);
}, 2000); // delay 2s;
}
if (message.room_state.is_over === true) {
gameChannelId.unsubscribe(gameChannelId);
}
}).bind('playing', (message) => { // 下一步操作人是自己就调用接口出牌
let currentState = message.room_state;
setTimeout(() => {
autoPlay(currentState, 1, gameId);
}, 2000); // delay 2s;
if (message.room_state.is_over === true) {
gameChannelId.unsubscribe(gameChannelId);
}
});
}
});
/**
* 按照当前局面自动出牌
*
* @param currentState
* @param fieldId
* @param gameId
*/
function autoPlay(currentState, fieldId, gameId) {
console.log('current auto play', currentState);
let unusedCardValues = currentState['card_list']
.filter((value) => { return value['is_used'] === true; })
.map((value) => { return value['value']; });
let index = getRandomInt(0, unusedCardValues.length);
axios({
method: 'patch',
responseType: 'json',
url: `http://21ji.wanuq.com/ticket/fields/${fieldId}/games/${gameId}/play`,
headers: {
Authorization: "Bearer " + jwtToken
},
data: {
"index": index,
}
}).then((response) => {
console.log('play game');
console.log(response);
});
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment