<commit_before>function TweetsTimeline(timelineId, manager, template) {
  this.timelineId = timelineId;
  this.manager = manager;
  this.template = template;

  this.tweetsCache = [];
  this.newTweetsCache = [];
  this.unreadNotified = [];

  this.timerId = null;
  this.currentError = null;
  this.currentCallback = null;
  this.currentScroll = 0;
  this.firstRun = true;
  this.timelinePath = null;
  this.timelineId = timelineId;
  this.timelineStopped = false;
  this.timelinePath = this.template.templatePath;
  this.unifiedRunning = false;
  this.currentRequestId = 0;
  this.canceledRequests = {};
}

TweetsTimeline.prototype = {
  init: function() {
    this._baseInit();
  },

  remove: function(){
    this.template.setVisible(false);
    if(!this.template.includeInUnified) {
      this.killTimeline();
      return true;
    }
    return false;
  },

  getError: function() {
    return this.currentError;
  },

  killTimeline: function() {
    this.timelineStopped = true;
    this._stopTimer();
  },

  giveMeTweets: function(callback, syncNew, cacheOnly, keepCache, suggestedCount) {
    if(!this.timelinePath) {
      callback([], this.timelineId, this);
      return;
    }
    var _this = this;
    if(this.unifiedRunning) {
      this._cancelRequest();
    }
    if(this.currentCallback) {
      if(this.unifiedRunning) {
        try {
          this.currentCallback([], this.timelineId, this);
        } catch(e) {
          /* ignoring */
        } finally {
          this.currentCallback = null;
        }
      } else {
        //Handling multiple calls to giveMeTweets, just update the registered
        //callback and let the first request finish.
        this.currentCallback = callback;
        return;
      }
    }
    if(syncNew) {
      //We should fetch new tweets, update the cache and then return the
      //cached results.
      var oldNewTweetsCallback = this.manager.newTweetsCallback;
      this.currentCallback = callback;
      this.manager.newTweetsCallback = null;
      var onFinishCallback = function() {
        var tweetsCallback = _this.currentCallback;
        _this.currentCallback = null;

        _this.updateNewTweets();
        _this.manager.updateAlert();
        _this.giveMeTweets(tweetsCallback, false, true);
        _this.manager.newTweetsCallback = oldNewTweetsCallback;
      };
      this._fetchNewTweets(onFinishCallback);
      return;
    }
    if(cacheOnly && !this.firstRun) {
      //Only return cached results if this is not the first run.
      if(!keepCache) {
        this._cleanUpCache();
      }
      try {
        callback(this.tweetsCache, this.timelineId, this);
      } catch(e) {
        /* ignoring exception, popup might be closed */
      }
      return;
    }
    //If we didn't return yet it's because we want to fetch old tweets
    //from twitter's API.

    this.currentCallback = callback;
    var params = this._makeOldTweetsRequestParams(suggestedCount);
    var context = {
      usingMaxId: !!params.max_id,
      requestId: this._nextRequestId()
    };
    this._doBackendRequest(this.timelinePath, function(success, tweets, status, context) {
      _this._onFetch(success, tweets, status, context);
    }, context, params);
  },

  updateNewTweets: function() {
    this.tweetsCache = this.newTweetsCache.concat(this.tweetsCache);
    this.newTweetsCache = [];
    this.unreadNotified = [];
  },

  newTweetsCount: function() {
    var unreadCount = 0;
    for(var i = this.newTweetsCache.length - 1; i >= 0; --i) {
      if(!this.manager.isTweetRead(this.newTweetsCache[i].id)) {
        ++unreadCount;
      }
    }
    return [this.newTweetsCache.length, unreadCount];
  },

  getNewUnreadTweets: function() {
    var unreadNewList = [];
    for(var i = 0; i < this.newTweetsCache.length; ++i) {
      var tweet = this.newTweetsCache[i];
      if(!this.manager.isTweetRead(tweet.id) && !this.unreadNotified[tweet.id] && tweet.user.screen_name != TweetManager.instance.twitterBackend.oauthLib.screen_name) {
        unreadNewList.push(tweet);
        this.unreadNotified[tweet.id] = true;
      }
    }
    return unreadNewList;
  },

  getNewUnreadIds: function() {
    var unreadNewIds = [];
    for(var i = 0; i < this.newTweetsCache.length; ++i) {
      var tweet = this.newTweetsCache[i];
      if(!this.manager.isTweetRead(tweet.id) && tweet.user.screen_name != TweetManager.instance.twitterBackend.oauthLib.screen_name) {
        unreadNewIds.push(tweet.id);
      }
    }
    return unreadNewIds;
  },

  removeFromCache: function(id) {
    var i = 0;
    for(; i < this.tweetsCache.length; ++i) {
      if(this.tweetsCache[i].id == id)
        break;
    }
    if(i != this.tweetsCache.length) {
      this.tweetsCache.splice(i, 1);
    }
  },

  findTweet: function(id) {
    var i = 0;
    for(; i < this.tweetsCache.length; ++i) {
      if(this.tweetsCache[i].id == id)
        return this.tweetsCache[i];
    }
    return null;
  },

  getNewTweetsCache: function() {
    return this.newTweetsCache;
  },

  getTweetsCache: function() {
    return this.tweetsCache;
  },

  reset: function() {
    this.tweetsCache = [];
    this.newTweetsCache = [];
    this.unreadNotified = [];
    this.firstRun = true;
    this._stopTimer();
  },

  /* Private Methods */

  _setError: function(status) {
    this.currentError = status;
  },

  _setTimelinePath: function(path) {
    this.timelinePath = path;
  },

  _stopTimer: function() {
    if(this.timerId) {
      clearTimeout(this.timerId);
      this.timerId = null;
    }
  },

  _onFetchNew: function(success, tweets, status, context) {
    if(this.timelineStopped) {
      return;
    }
    if(this._isRequestCanceled(context.requestId)) {
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
      return;
    }
    var _this = this;
    if(!success) {
      this._setError(status);
      if(context.onFinish)
        context.onFinish(0);
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
      return;
    }
    this._setError(null);

    this._syncNewTweets(tweets, context);

    if(tweets.length > 0) {
      this.manager.notifyNewTweets();
    }
    if(context.onFinish)
      context.onFinish(tweets.length);
    this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
  },

  _doBackendRequest: function(path, callback, context, params) {
    this.manager.twitterBackend.timeline(path, callback, context, params);
  },

  _fetchNewTweets: function(onFinishCallback) {
    this._stopTimer();
    var _this = this;
    if(this.manager.suspend && !onFinishCallback) {
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
      return;
    }
    var context = {
      requestId: this._nextRequestId(),
      onFinish: onFinishCallback
    };
    var params = this._makeNewTweetsRequestParams();
    this._doBackendRequest(this.timelinePath, function(success, tweets, status, context) {
      _this._onFetchNew(success, tweets, status, context);
    }, context, params);
  },

  _onFetch: function(success, tweets, status, context) {
    if(this.timelineStopped || this._isRequestCanceled(context.requestId)) {
      return;
    }
    if(!success) {
      this._setError(status);
      try {
        this.currentCallback(null, this.timelineId, this);
      } catch(e) {
        /* ignoring exception, popup might be closed */
      }

      this._setError(null);
      this.currentCallback = null;
      return;
    }
    this._setError(null);
    this._syncOldTweets(tweets, context);

    // Let's clean this.currentCallback before calling it as
    // there might be unexpected errors and this should not block
    // the extension.
    var callback = this.currentCallback;
    this.currentCallback = null;
    try {
      callback(this.tweetsCache, this.timelineId, this);
    } catch(e) {
      /* ignoring exception, popup might be closed */
    }

    if(this.firstRun) {
      this.firstRun = false;
      var _this = this;
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
    }
  },

  _cleanUpCache: function() {
    if(this.currentScroll !== 0) {
      return;
    }
    var len = this.tweetsCache.length;
    if(len <= OptionsBackend.get('max_cached_tweets'))
      return;
    this.tweetsCache = this.tweetsCache.slice(0, OptionsBackend.get('max_cached_tweets') + 1);
  },

  _makeOldTweetsRequestParams: function(suggestedCount) {
    if(!suggestedCount) {
      suggestedCount = OptionsBackend.get('tweets_per_page');
    }
    var params = {count: suggestedCount, per_page: suggestedCount};
    var maxId = null;
    if(this.tweetsCache.length > 0) {
      maxId = this.tweetsCache[this.tweetsCache.length - 1].id;
    }
    if(maxId) {
      params.max_id = maxId;
    }
    return params;
  },

  _makeNewTweetsRequestParams: function() {
    var lastId = null;
    if(this.newTweetsCache.length > 0) {
      lastId = this.newTweetsCache[0].id;
    } else if(this.tweetsCache.length > 0) {
      lastId = this.tweetsCache[0].id;
    }
    var params = {count: 200};
    if(lastId) {
      params.since_id = lastId;
    }
    return params;
  },

  _syncOldTweets: function(tweets, context) {
    var tweetsCacheLastId = (this.tweetsCache.length > 0) ? this.tweetsCache[this.tweetsCache.length - 1].id : -1;
    for(var i = 0; i < tweets.length; ++i) {
      if(tweets[i].id == tweetsCacheLastId) {
        continue;
      }
      this.tweetsCache.push(tweets[i]);
    }
  },

  _syncNewTweets: function(tweets, context) {
    for(var i = tweets.length - 1; i >= 0; --i) {
      this.newTweetsCache.unshift(tweets[i]);
      var tid = tweets[i].id;
      if(context.onFinish) {
        this.manager.readTweet(tid);
      } else if(!this.manager.readTweets[tid]) {
        this.manager.unreadTweets[tid] = true;
      }
    }
  },

  /**
  * Filter-out all tweets and retweets that contain a status.user.id
  * or status.retweeted_status.user.id in this.manager.blockedUserIds.
  *
  * @param json tweets - response as returned by a Twitter timeline REST method
  * @return json
  */
  _filterBlockedTweets: function(tweets) {
    var filteredTweets = [];
    for(var i in tweets) {
      if(!(tweets[i].user && tweets[i].user.id in this.manager.blockedUserIds || tweets[i].retweeted_status && tweets[i].retweeted_status.user.id in this.manager.blockedUserIds)) {
        filteredTweets.push(tweets[i]);
      }
    }
    return filteredTweets;
  },

  _baseInit: function() {
    var _this = this;
    this.giveMeTweets(function(success) {
      if(!success) {
        setTimeout(function() {
          if(_this.firstRun && !_this.timelineStopped && !_this.currentCallback) {
            _this._baseInit();
          }
        }, 3000);
      }
    });
  },

  _cancelRequest: function() {
    this.canceledRequests[this.currentRequestId] = true;
  },

  _nextRequestId: function() {
    this.currentRequestId += 1;
    return this.currentRequestId;
  },

  _isRequestCanceled: function(requestId) {
    var isCanceled = requestId in this.canceledRequests;
    delete this.canceledRequests[requestId];
    return isCanceled;
  }
};<commit_msg>Stupid me....<commit_after>function TweetsTimeline(timelineId, manager, template) {
  this.timelineId = timelineId;
  this.manager = manager;
  this.template = template;

  this.tweetsCache = [];
  this.newTweetsCache = [];
  this.unreadNotified = [];

  this.timerId = null;
  this.currentError = null;
  this.currentCallback = null;
  this.currentScroll = 0;
  this.firstRun = true;
  this.timelinePath = null;
  this.timelineId = timelineId;
  this.timelineStopped = false;
  this.timelinePath = this.template.templatePath;
  this.unifiedRunning = false;
  this.currentRequestId = 0;
  this.canceledRequests = {};
}

TweetsTimeline.prototype = {
  init: function() {
    this._baseInit();
  },

  remove: function(){
    this.template.setVisible(false);
    if(!this.template.includeInUnified) {
      this.killTimeline();
      return true;
    }
    return false;
  },

  getError: function() {
    return this.currentError;
  },

  killTimeline: function() {
    this.timelineStopped = true;
    this._stopTimer();
  },

  giveMeTweets: function(callback, syncNew, cacheOnly, keepCache, suggestedCount) {
    if(!this.timelinePath) {
      callback([], this.timelineId, this);
      return;
    }
    var _this = this;
    if(this.unifiedRunning) {
      this._cancelRequest();
    }
    if(this.currentCallback) {
      if(this.unifiedRunning) {
        try {
          this.currentCallback([], this.timelineId, this);
        } catch(e) {
          /* ignoring */
        } finally {
          this.currentCallback = null;
        }
      } else {
        //Handling multiple calls to giveMeTweets, just update the registered
        //callback and let the first request finish.
        this.currentCallback = callback;
        return;
      }
    }
    if(syncNew) {
      //We should fetch new tweets, update the cache and then return the
      //cached results.
      var oldNewTweetsCallback = this.manager.newTweetsCallback;
      this.currentCallback = callback;
      this.manager.newTweetsCallback = null;
      var onFinishCallback = function() {
        var tweetsCallback = _this.currentCallback;
        _this.currentCallback = null;

        _this.updateNewTweets();
        _this.manager.updateAlert();
        _this.giveMeTweets(tweetsCallback, false, true);
        _this.manager.newTweetsCallback = oldNewTweetsCallback;
      };
      this._fetchNewTweets(onFinishCallback);
      return;
    }
    if(cacheOnly && !this.firstRun) {
      //Only return cached results if this is not the first run.
      if(!keepCache) {
        this._cleanUpCache();
      }
      try {
        callback(this.tweetsCache, this.timelineId, this);
      } catch(e) {
        /* ignoring exception, popup might be closed */
      }
      return;
    }
    //If we didn't return yet it's because we want to fetch old tweets
    //from twitter's API.

    this.currentCallback = callback;
    var params = this._makeOldTweetsRequestParams(suggestedCount);
    var context = {
      usingMaxId: !!params.max_id,
      requestId: this._nextRequestId()
    };
    this._doBackendRequest(this.timelinePath, function(success, tweets, status, context) {
      _this._onFetch(success, tweets, status, context);
    }, context, params);
  },

  updateNewTweets: function() {
    this.tweetsCache = this.newTweetsCache.concat(this.tweetsCache);
    this.newTweetsCache = [];
    this.unreadNotified = [];
  },

  newTweetsCount: function() {
    var unreadCount = 0;
    for(var i = this.newTweetsCache.length - 1; i >= 0; --i) {
      if(!this.manager.isTweetRead(this.newTweetsCache[i].id)) {
        ++unreadCount;
      }
    }
    return [this.newTweetsCache.length, unreadCount];
  },

  getNewUnreadTweets: function() {
    var unreadNewList = [];
    for(var i = 0; i < this.newTweetsCache.length; ++i) {
      var tweet = this.newTweetsCache[i];
      if(!this.manager.isTweetRead(tweet.id) && !this.unreadNotified[tweet.id] && tweet.user.screen_name != TweetManager.instance.twitterBackend.oauthLib.screen_name) {
        unreadNewList.push(tweet);
        this.unreadNotified[tweet.id] = true;
      }
    }
    return unreadNewList;
  },

  getNewUnreadIds: function() {
    var unreadNewIds = [];
    for(var i = 0; i < this.newTweetsCache.length; ++i) {
      var tweet = this.newTweetsCache[i];
      if(!this.manager.isTweetRead(tweet.id) && tweet.user.screen_name != TweetManager.instance.twitterBackend.oauthLib.screen_name) {
        unreadNewIds.push(tweet.id);
      }
    }
    return unreadNewIds;
  },

  removeFromCache: function(id) {
    var i = 0;
    for(; i < this.tweetsCache.length; ++i) {
      if(this.tweetsCache[i].id == id)
        break;
    }
    if(i != this.tweetsCache.length) {
      this.tweetsCache.splice(i, 1);
    }
  },

  findTweet: function(id) {
    var i = 0;
    for(; i < this.tweetsCache.length; ++i) {
      if(this.tweetsCache[i].id == id)
        return this.tweetsCache[i];
    }
    return null;
  },

  getNewTweetsCache: function() {
    return this.newTweetsCache;
  },

  getTweetsCache: function() {
    return this.tweetsCache;
  },

  reset: function() {
    this.tweetsCache = [];
    this.newTweetsCache = [];
    this.unreadNotified = [];
    this.firstRun = true;
    this._stopTimer();
  },

  /* Private Methods */

  _setError: function(status) {
    this.currentError = status;
  },

  _setTimelinePath: function(path) {
    this.timelinePath = path;
  },

  _stopTimer: function() {
    if(this.timerId) {
      clearTimeout(this.timerId);
      this.timerId = null;
    }
  },

  _onFetchNew: function(success, tweets, status, context) {
    if(this.timelineStopped) {
      return;
    }
    var _this = this;
    if(this._isRequestCanceled(context.requestId)) {
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
      return;
    }
    if(!success) {
      this._setError(status);
      if(context.onFinish)
        context.onFinish(0);
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
      return;
    }
    this._setError(null);

    this._syncNewTweets(tweets, context);

    if(tweets.length > 0) {
      this.manager.notifyNewTweets();
    }
    if(context.onFinish)
      context.onFinish(tweets.length);
    this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
  },

  _doBackendRequest: function(path, callback, context, params) {
    this.manager.twitterBackend.timeline(path, callback, context, params);
  },

  _fetchNewTweets: function(onFinishCallback) {
    this._stopTimer();
    var _this = this;
    if(this.manager.suspend && !onFinishCallback) {
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
      return;
    }
    var context = {
      requestId: this._nextRequestId(),
      onFinish: onFinishCallback
    };
    var params = this._makeNewTweetsRequestParams();
    this._doBackendRequest(this.timelinePath, function(success, tweets, status, context) {
      _this._onFetchNew(success, tweets, status, context);
    }, context, params);
  },

  _onFetch: function(success, tweets, status, context) {
    if(this.timelineStopped || this._isRequestCanceled(context.requestId)) {
      return;
    }
    if(!success) {
      this._setError(status);
      try {
        this.currentCallback(null, this.timelineId, this);
      } catch(e) {
        /* ignoring exception, popup might be closed */
      }

      this._setError(null);
      this.currentCallback = null;
      return;
    }
    this._setError(null);
    this._syncOldTweets(tweets, context);

    // Let's clean this.currentCallback before calling it as
    // there might be unexpected errors and this should not block
    // the extension.
    var callback = this.currentCallback;
    this.currentCallback = null;
    try {
      callback(this.tweetsCache, this.timelineId, this);
    } catch(e) {
      /* ignoring exception, popup might be closed */
    }

    if(this.firstRun) {
      this.firstRun = false;
      var _this = this;
      this.timerId = setTimeout(function() { _this._fetchNewTweets(); }, this.template.refreshInterval);
    }
  },

  _cleanUpCache: function() {
    if(this.currentScroll !== 0) {
      return;
    }
    var len = this.tweetsCache.length;
    if(len <= OptionsBackend.get('max_cached_tweets'))
      return;
    this.tweetsCache = this.tweetsCache.slice(0, OptionsBackend.get('max_cached_tweets') + 1);
  },

  _makeOldTweetsRequestParams: function(suggestedCount) {
    if(!suggestedCount) {
      suggestedCount = OptionsBackend.get('tweets_per_page');
    }
    var params = {count: suggestedCount, per_page: suggestedCount};
    var maxId = null;
    if(this.tweetsCache.length > 0) {
      maxId = this.tweetsCache[this.tweetsCache.length - 1].id;
    }
    if(maxId) {
      params.max_id = maxId;
    }
    return params;
  },

  _makeNewTweetsRequestParams: function() {
    var lastId = null;
    if(this.newTweetsCache.length > 0) {
      lastId = this.newTweetsCache[0].id;
    } else if(this.tweetsCache.length > 0) {
      lastId = this.tweetsCache[0].id;
    }
    var params = {count: 200};
    if(lastId) {
      params.since_id = lastId;
    }
    return params;
  },

  _syncOldTweets: function(tweets, context) {
    var tweetsCacheLastId = (this.tweetsCache.length > 0) ? this.tweetsCache[this.tweetsCache.length - 1].id : -1;
    for(var i = 0; i < tweets.length; ++i) {
      if(tweets[i].id == tweetsCacheLastId) {
        continue;
      }
      this.tweetsCache.push(tweets[i]);
    }
  },

  _syncNewTweets: function(tweets, context) {
    for(var i = tweets.length - 1; i >= 0; --i) {
      this.newTweetsCache.unshift(tweets[i]);
      var tid = tweets[i].id;
      if(context.onFinish) {
        this.manager.readTweet(tid);
      } else if(!this.manager.readTweets[tid]) {
        this.manager.unreadTweets[tid] = true;
      }
    }
  },

  /**
  * Filter-out all tweets and retweets that contain a status.user.id
  * or status.retweeted_status.user.id in this.manager.blockedUserIds.
  *
  * @param json tweets - response as returned by a Twitter timeline REST method
  * @return json
  */
  _filterBlockedTweets: function(tweets) {
    var filteredTweets = [];
    for(var i in tweets) {
      if(!(tweets[i].user && tweets[i].user.id in this.manager.blockedUserIds || tweets[i].retweeted_status && tweets[i].retweeted_status.user.id in this.manager.blockedUserIds)) {
        filteredTweets.push(tweets[i]);
      }
    }
    return filteredTweets;
  },

  _baseInit: function() {
    var _this = this;
    this.giveMeTweets(function(success) {
      if(!success) {
        setTimeout(function() {
          if(_this.firstRun && !_this.timelineStopped && !_this.currentCallback) {
            _this._baseInit();
          }
        }, 3000);
      }
    });
  },

  _cancelRequest: function() {
    this.canceledRequests[this.currentRequestId] = true;
  },

  _nextRequestId: function() {
    this.currentRequestId += 1;
    return this.currentRequestId;
  },

  _isRequestCanceled: function(requestId) {
    var isCanceled = requestId in this.canceledRequests;
    delete this.canceledRequests[requestId];
    return isCanceled;
  }
};<|endoftext|>


<commit_before>var request = require('superagent');
var Hand = require('./hand');

module.exports = {

  VERSION: "GrandMaster Level 2 RefactorMaster Fixed",

  bet_request: function(gameState, response) {
    var respond = function(message) {
      response.send(200, message.toString());
    };

    var player = gameState.players[gameState.in_action];

    try {
      console.log('Actual game state', JSON.stringify(gameState, null, 4));

      var hand = player.hole_cards;

      var isPreFlop = function(gameState) {
        return gameState.community_cards.length === 0;
      };

      var betToCall = gameState.current_buy_in - player.bet;

      var fetchHandRank = function (hand, community_cards, callback) {
        var cards = hand.concat(community_cards);
        request
            .get('http://rainman.leanpoker.org/rank')
            .send('cards=' + JSON.stringify(cards))
            .end(function (err, res) {
              console.log("rainmain", res.text);
              callback(JSON.parse(res.text));
            });
      };

      var getPreFlopBet = function(gameState, player, hand) {
        if (hand.rankIsSame() && hand.rankHasBiggerThan(7)) {
          return player.stack;
        }

        if (hand.rankIsSame()) {
          return gameState.minimum_raise * 40;
        }

        if (hand.diffIsOne() && hand.suiteIsSame()) {
          return gameState.minimum_raise * 30;
        }

        if (hand.diffIsOne()) {
          return gameState.minimum_raise * 20;
        }

        if (hand.suiteIsSame()) {
          return gameState.minimum_raise * 10;
        }

        if (player.bet > 0) {
          return betToCall;
        }

        return 0;
      };

      if (isPreFlop(gameState)) {
        respond(getPreFlopBet(gameState, player, new Hand(hand)));
      } else {
        fetchHandRank(hand, gameState.community_cards, function(rankResponse) {
          if (rankResponse.rank == 0) {
            respond(0);
          } else if (rankResponse.rank == 1) {
            respond(betToCall);
          } else {
            respond(gameState.minimum_raise * 20);
          }
        });
      }

    } catch (e) {
      console.log('EXCEPTION', e);
      respond(gameState.current_buy_in - player.bet);
    }

  },

  showdown: function(gameState) {
    //console.log('Showdown', JSON.stringify(gameState, null, 4));
  }

};
<commit_msg>FIXXXX<commit_after>var request = require('superagent');
var Hand = require('./hand');

module.exports = {

  VERSION: "GrandMaster Level 2 RefactorMaster Fixed",

  bet_request: function(gameState, response) {
    var respond = function(message) {
      response.send(200, message.toString());
    };

    var player = gameState.players[gameState.in_action];

    try {
      console.log('Actual game state', JSON.stringify(gameState, null, 4));

      var hand = player.hole_cards;

      var isPreFlop = function(gameState) {
        return gameState.community_cards.length === 0;
      };

      var betToCall = gameState.current_buy_in - player.bet;

      var fetchHandRank = function (hand, community_cards, callback) {
        var cards = hand.concat(community_cards);
        request
            .get('http://rainman.leanpoker.org/rank')
            .send('cards=' + JSON.stringify(cards))
            .end(function (err, res) {
              console.log("rainmain", res.text);
              callback(JSON.parse(res.text));
            });
      };

      var getPreFlopBet = function(gameState, player, hand) {
        var notFirstLicit = player.bet > (gameState.small_blind * 2);

        if (notFirstLicit) {
          if (betToCall > (player.stack/2)) return 0;
        }

        if (hand.rankIsSame() && hand.rankHasBiggerThan(7)) {
          return player.stack;
        }

        if (hand.rankIsSame()) {
          return gameState.minimum_raise * 40;
        }

        if (hand.diffIsOne() && hand.suiteIsSame()) {
          return gameState.minimum_raise * 30;
        }

        if (hand.diffIsOne()) {
          return gameState.minimum_raise * 20;
        }

        if (hand.suiteIsSame()) {
          return gameState.minimum_raise * 10;
        }

        if (player.bet > 0) {
          return betToCall;
        }

        return 0;
      };

      if (isPreFlop(gameState)) {
        respond(getPreFlopBet(gameState, player, new Hand(hand)));
      } else {
        fetchHandRank(hand, gameState.community_cards, function(rankResponse) {
          if (rankResponse.rank == 0) {
            respond(0);
          } else if (rankResponse.rank == 1) {
            respond(betToCall);
          } else {
            respond(gameState.minimum_raise * 20);
          }
        });
      }

    } catch (e) {
      console.log('EXCEPTION', e);
      respond(gameState.current_buy_in - player.bet);
    }

  },

  showdown: function(gameState) {
    //console.log('Showdown', JSON.stringify(gameState, null, 4));
  }

};
<|endoftext|>


<commit_before>var game = require('socket.io-client')('http://192.168.0.24:3000'),
    lobby = require('socket.io-client')('http://192.168.0.24:3030'),
    Chess = require('chess.js').Chess,

    name = 'RndJesus_' + Math.floor(Math.random() * 100);;

lobby.on('connect', function () {
    console.log('Player ' + name + ' is connected to lobby');
});

lobby.on('join', function (gameId) {
    console.log('Player is joining game: ' + gameId);
    game.emit('join', gameId);
});

game.on('connect', function () {
    console.log('Player ' + name + ' is connected to game');
    //game.emit('join', 'test_game');
});

game.on('move', function (gameState) {
    var chess = new Chess();
    chess.load(gameState.board);

    var moves = chess.moves(),
        move = moves[Math.floor(Math.random() * moves.length)];

    console.log(move);
    gameState.move = move;

    game.emit('move', gameState);
});
<commit_msg>Use localhost when running locally<commit_after>var game = require('socket.io-client')('http://localhost:3000'),
    lobby = require('socket.io-client')('http://localhost:3030'),
    Chess = require('chess.js').Chess,

    name = 'RndJesus_' + Math.floor(Math.random() * 100);;

lobby.on('connect', function () {
    console.log('Player ' + name + ' is connected to lobby');
});

lobby.on('join', function (gameId) {
    console.log('Player is joining game: ' + gameId);
    game.emit('join', gameId);
});

game.on('connect', function () {
    console.log('Player ' + name + ' is connected to game');
    //game.emit('join', 'test_game');
});

game.on('move', function (gameState) {
    var chess = new Chess();
    chess.load(gameState.board);

    var moves = chess.moves(),
        move = moves[Math.floor(Math.random() * moves.length)];

    console.log(move);
    gameState.move = move;

    game.emit('move', gameState);
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Settings for Assemble's default plugins.
 */

module.exports = function plugins_(assemble) {
  // enable all plugins by default
  assemble.disable('minimal config');

  // default `src` plugins
  assemble.enable('src:init plugin');
  assemble.enable('src:assets plugin');
  assemble.enable('src:drafts plugin');

  // default `dest` plugins
  assemble.enable('dest:dest plugin');
  assemble.enable('dest:render plugin');
};
<commit_msg>update default enabled plugins<commit_after>'use strict';

/**
 * Settings for Assemble's default plugins.
 */

module.exports = function plugins_(assemble) {
  // default `src` plugins
  assemble.enable('src:vfs plugin');
  assemble.enable('src:init plugin');
  assemble.enable('src:drafts plugin');

  // default `dest` plugins
  assemble.enable('dest:paths plugin');
  assemble.enable('dest:render plugin');
  assemble.enable('dest:vfs plugin');
};
<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    bet(0);
  },

  showdown: function(game_state) {

  }
};
<commit_msg>being bold<commit_after>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    bet(200);
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>
/**
 * Module requirements.
 */

var Transport = require('../transport')
  , parser = require('../parser')
  , debug = require('debug')('engine:transport')

/**
 * Exports the constructor.
 */

module.exports = Polling;

/**
 * HTTP polling constructor.
 *
 * @api public.
 */

function Polling (req) {
  Transport.call(this, req);
};

/**
 * Inherits from Transport.
 *
 * @api public.
 */

Polling.prototype.__proto__ = Transport.prototype;

/**
 * Transport name
 *
 * @api public
 */

Polling.prototype.name = 'polling';

/**
 * Overrides onRequest.
 *
 * @param {http.ServerRequest}
 * @api private
 */

Polling.prototype.onRequest = function (req) {
  var res = req.res;

  if ('GET' == req.method) {
    this.onPollRequest(req, res);
  } else if ('POST' == req.method) {
    this.onDataRequest(req, res);
  } else {
    res.writeHead(500);
    res.end();
  }
};

/**
 * The client sends a request awaiting for us to send data.
 *
 * @api private
 */

Polling.prototype.onPollRequest = function (req, res) {
  if (this.req) {
    debug('poll request overlap');
    // assert: this.res, '.req and .res should be (un)set together'
    this.onError('poll overlap from client');
    res.writeHead(500);
  } else {
    debug('setting poll request');
    this.req = req;
    this.res = res;

    var self = this;

    function onClose () {
      self.onError('poll connection closed prematurely');
    }

    function cleanup () {
      req.removeListener('close', onClose);
      self.req = self.res = null;
    }

    req.cleanup = cleanup;
    req.on('close', onClose);

    this.writable = true;
    this.emit('drain');

    // if we're still writable but had a pending close, trigger an empty send
    if (this.writable && this.shouldClose) {
      debug('triggering empty send to append close packet');
      this.send([]);
    }
  }
};

/**
 * The client sends a request with data.
 *
 * @api private
 */

Polling.prototype.onDataRequest = function (req, res) {
  if (this.dataReq) {
    // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
    this.onError('data request overlap from client');
    res.writeHead(500);
  } else {
    this.dataReq = req;
    this.dataRes = res;

    var chunks = ''
      , self = this

    function cleanup () {
      chunks = '';
      req.removeListener('data', onData);
      req.removeListener('end', onEnd);
      req.removeListener('close', cleanup);
      self.dataReq = self.dataRes = null;
    };

    function onClose () {
      cleanup();
      self.onError('data request connection closed prematurely');
    };

    function onData (data) {
      chunks += data;
    };

    function onEnd () {
      self.onData(chunks);
      res.writeHead(204);
      res.end();
      cleanup();
    };

    req.abort = cleanup;
    req.on('close', onClose);
    req.on('data', onData);
    req.on('end', onEnd);
    req.setEncoding('utf8');
  }
};

/**
 * Processes the incoming data payload.
 */

Polling.prototype.onData = function (data) {
  var packets = parser.decodePayload(data);
  debug('polling got packets', JSON.stringify(packets));
  for (var i = 0, l = packets.length; i < l; i++) {
    if ('close' == packets[i].type) {
      debug('got xhr close packet');
      return this.onClose();
    }

    this.onPacket(packets[i]);
  }
};

/**
 * Writes a packet payload.
 *
 * @param {Object} packet
 * @api private
 */

Polling.prototype.send = function (packets) {
  debug('polling writing packets', JSON.stringify(packets));
  if (this.shouldClose) {
    debug('appending close packet to payload');
    packets.push({ type: 'close' });
    this.shouldClose();
    this.shouldClose = null;
  }

  this.write(parser.encodePayload(packets));
};

/**
 * Writes data as response to poll request.
 *
 * @param {String} data
 * @api private
 */

Polling.prototype.write = function (data) {
  this.doWrite(data);
  this.req.cleanup();
  this.writable = false;
};

/**
 * Closes the transport.
 *
 * @api private
 */

Polling.prototype.doClose = function (fn) {
  if (this.dataReq) {
    // FIXME: should we do this?
    debug('aborting ongoing data request');
    this.dataReq.abort();
  }

  if (this.writable) {
    debug('polling transport is writable - closing right away');
    this.send([{ type: 'close' }]);
  } else {
    debug('polling transport not writable - marking that we should close');
    this.shouldClose = fn;
  }
};
<commit_msg>Fixed closing of polling transport callback.<commit_after>
/**
 * Module requirements.
 */

var Transport = require('../transport')
  , parser = require('../parser')
  , debug = require('debug')('engine:transport')

/**
 * Exports the constructor.
 */

module.exports = Polling;

/**
 * HTTP polling constructor.
 *
 * @api public.
 */

function Polling (req) {
  Transport.call(this, req);
};

/**
 * Inherits from Transport.
 *
 * @api public.
 */

Polling.prototype.__proto__ = Transport.prototype;

/**
 * Transport name
 *
 * @api public
 */

Polling.prototype.name = 'polling';

/**
 * Overrides onRequest.
 *
 * @param {http.ServerRequest}
 * @api private
 */

Polling.prototype.onRequest = function (req) {
  var res = req.res;

  if ('GET' == req.method) {
    this.onPollRequest(req, res);
  } else if ('POST' == req.method) {
    this.onDataRequest(req, res);
  } else {
    res.writeHead(500);
    res.end();
  }
};

/**
 * The client sends a request awaiting for us to send data.
 *
 * @api private
 */

Polling.prototype.onPollRequest = function (req, res) {
  if (this.req) {
    debug('poll request overlap');
    // assert: this.res, '.req and .res should be (un)set together'
    this.onError('poll overlap from client');
    res.writeHead(500);
  } else {
    debug('setting poll request');
    this.req = req;
    this.res = res;

    var self = this;

    function onClose () {
      self.onError('poll connection closed prematurely');
    }

    function cleanup () {
      req.removeListener('close', onClose);
      self.req = self.res = null;
    }

    req.cleanup = cleanup;
    req.on('close', onClose);

    this.writable = true;
    this.emit('drain');

    // if we're still writable but had a pending close, trigger an empty send
    if (this.writable && this.shouldClose) {
      debug('triggering empty send to append close packet');
      this.send([]);
    }
  }
};

/**
 * The client sends a request with data.
 *
 * @api private
 */

Polling.prototype.onDataRequest = function (req, res) {
  if (this.dataReq) {
    // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
    this.onError('data request overlap from client');
    res.writeHead(500);
  } else {
    this.dataReq = req;
    this.dataRes = res;

    var chunks = ''
      , self = this

    function cleanup () {
      chunks = '';
      req.removeListener('data', onData);
      req.removeListener('end', onEnd);
      req.removeListener('close', cleanup);
      self.dataReq = self.dataRes = null;
    };

    function onClose () {
      cleanup();
      self.onError('data request connection closed prematurely');
    };

    function onData (data) {
      chunks += data;
    };

    function onEnd () {
      self.onData(chunks);
      res.writeHead(204);
      res.end();
      cleanup();
    };

    req.abort = cleanup;
    req.on('close', onClose);
    req.on('data', onData);
    req.on('end', onEnd);
    req.setEncoding('utf8');
  }
};

/**
 * Processes the incoming data payload.
 */

Polling.prototype.onData = function (data) {
  var packets = parser.decodePayload(data);
  debug('polling got packets', JSON.stringify(packets));
  for (var i = 0, l = packets.length; i < l; i++) {
    if ('close' == packets[i].type) {
      debug('got xhr close packet');
      return this.onClose();
    }

    this.onPacket(packets[i]);
  }
};

/**
 * Writes a packet payload.
 *
 * @param {Object} packet
 * @api private
 */

Polling.prototype.send = function (packets) {
  debug('polling writing packets', JSON.stringify(packets));
  if (this.shouldClose) {
    debug('appending close packet to payload');
    packets.push({ type: 'close' });
    this.shouldClose();
    this.shouldClose = null;
  }

  this.write(parser.encodePayload(packets));
};

/**
 * Writes data as response to poll request.
 *
 * @param {String} data
 * @api private
 */

Polling.prototype.write = function (data) {
  this.doWrite(data);
  this.req.cleanup();
  this.writable = false;
};

/**
 * Closes the transport.
 *
 * @api private
 */

Polling.prototype.doClose = function (fn) {
  if (this.dataReq) {
    // FIXME: should we do this?
    debug('aborting ongoing data request');
    this.dataReq.abort();
  }

  if (this.writable) {
    debug('polling transport is writable - closing right away');
    this.send([{ type: 'close' }]);
    fn();
  } else {
    debug('polling transport not writable - marking that we should close');
    this.shouldClose = fn;
  }
};
<|endoftext|>


<commit_before>// @flow

import classnames from 'classnames';
import { Localized } from 'fluent-react/compat';
import React from 'react';

import LayoutWrapper from './LayoutWrapper';
import LocalizedHtml from '../components/LocalizedHtml';
import { VariantTests, VariantTestCase, VariantTestDefault } from './VariantTests';

import config from '../config';

import type { MainInstallButtonProps } from './types';

type MainInstallButtonState = { isInstalling: boolean };

export default class MainInstallButton extends React.Component {
  props: MainInstallButtonProps;
  state: MainInstallButtonState;

  constructor(props: MainInstallButtonProps) {
    super(props);
    this.state = {
      isInstalling: false
    };
  }

  install(e: Object) {
    // Don't install if a mouse button other than the primary button was clicked
    if (e.button !== 0) {
      return;
    }
    const { requireRestart, sendToGA, eventCategory, eventLabel, hasAddon, installAddon, installCallback, navigateTo } = this.props;

    if (hasAddon) {
      navigateTo('/experiments');
      return;
    }
    if (installCallback) {
      this.setState({ isInstalling: true });
      installCallback(e);
      return;
    }
    this.setState({ isInstalling: true });
    installAddon(requireRestart, sendToGA, eventCategory, eventLabel)
      .then(() => navigateTo('/experiments'));
  }

  render() {
    const { isFirefox, isMinFirefox, isMobile, hasAddon } = this.props;
    const isInstalling = this.state.isInstalling && !hasAddon;
    const terms = <Localized id="landingLegalNoticeTermsOfUse">

    </Localized>;
    const privacy = <Localized id="landingLegalNoticePrivacyNotice">

    </Localized>;

    return (
      <LayoutWrapper flexModifier="column-center-start-breaking">
        {(isMinFirefox && !isMobile) ? this.renderInstallButton(isInstalling, hasAddon) : this.renderAltButton(isFirefox, isMobile) }
        {isMinFirefox && !isMobile && <LocalizedHtml id="landingLegalNotice" $terms={terms} $privacy={privacy}>

            By proceeding, you agree to the {terms} and {privacy} of Test Pilot.

        </LocalizedHtml>}
      </LayoutWrapper>
    );
  }

  renderOneClickInstallButton(title: string) {
    return (

        <LocalizedHtml id="oneClickInstallMinorCta">
          Install Test Pilot &
        </LocalizedHtml>
        <Localized id="oneClickInstallMajorCta" $title={title}>
          Enable {title}
        </Localized>

    );
  }

  renderInstallButton(isInstalling: boolean, hasAddon: any) {
    const { experimentTitle } = this.props;
    let installButton = null;
    if (experimentTitle) {
      installButton = this.renderOneClickInstallButton(experimentTitle);
    } else {
      installButton = <Localized id="landingInstallButton">

          Install the Test Pilot Add-on

      </Localized>;
    }
    const makeInstallButton = (extraClass = '') => {
      return <button onClick={e => this.install(e)}
        className={classnames(`button extra-large primary install ${extraClass}`, { 'state-change': isInstalling })}>
        {hasAddon && <Localized id="landingInstalledButton">
          Installed
        </Localized>}
        {!hasAddon && !isInstalling && installButton}
        {!hasAddon && isInstalling &&
          <Localized id="landingInstallingButton">
            Installing...
          </Localized>}

      </button>;
    };

    return <VariantTests name="installButtonBorder" varianttests={ this.props.varianttests }>
      <VariantTestCase value="bigBorder">
        { makeInstallButton('big-border') }
      </VariantTestCase>
      <VariantTestDefault>
        { makeInstallButton() }
      </VariantTestDefault>
    </VariantTests>;
  }

  renderAltButton(isFirefox: boolean, isMobile: boolean) {
    if (isFirefox && isMobile) {
      return (

          <Localized id="landingRequiresDesktop">
            Test Pilot requires Firefox for Desktop on Windows, Mac or Linux
          </Localized>

      );
    }
    return (

          {!isFirefox ? (
              <Localized id="landingDownloadFirefoxDesc">
                (Test Pilot is available for Firefox on Windows, OS X and Linux)
              </Localized>
            ) : (
              <Localized id="landingUpgradeDesc2" $version={config.minFirefoxVersion}>
                Test Pilot requires Firefox { config.minFirefoxVersion } or higher.
              </Localized>
            )
          }
          {!isMobile &&

              {(!isFirefox) ? (
                  <Localized id="landingDownloadFirefoxTitle">

Firefox

                  </Localized>
                ) : (
                  <Localized id="landingUpgradeFirefoxTitle">

Upgrade Firefox

                  </Localized>
                )
              }
              <Localized id="landingDownloadFirefoxSubTitle">

Free Download

              </Localized>

          }

    );
  }
}
<commit_msg>Fix #2997 Don't navigate to /experiments on install; the page changes state in place now. (#3009)<commit_after>// @flow

import classnames from 'classnames';
import { Localized } from 'fluent-react/compat';
import React from 'react';

import LayoutWrapper from './LayoutWrapper';
import LocalizedHtml from '../components/LocalizedHtml';
import { VariantTests, VariantTestCase, VariantTestDefault } from './VariantTests';

import config from '../config';

import type { MainInstallButtonProps } from './types';

type MainInstallButtonState = { isInstalling: boolean };

export default class MainInstallButton extends React.Component {
  props: MainInstallButtonProps;
  state: MainInstallButtonState;

  constructor(props: MainInstallButtonProps) {
    super(props);
    this.state = {
      isInstalling: false
    };
  }

  install(e: Object) {
    // Don't install if a mouse button other than the primary button was clicked
    if (e.button !== 0) {
      return;
    }
    const { requireRestart, sendToGA, eventCategory, eventLabel, hasAddon, installAddon, installCallback, navigateTo } = this.props;

    if (hasAddon) {
      navigateTo('/experiments');
      return;
    }
    if (installCallback) {
      this.setState({ isInstalling: true });
      installCallback(e);
      return;
    }
    this.setState({ isInstalling: true });
    installAddon(requireRestart, sendToGA, eventCategory, eventLabel);
  }

  render() {
    const { isFirefox, isMinFirefox, isMobile, hasAddon } = this.props;
    const isInstalling = this.state.isInstalling && !hasAddon;
    const terms = <Localized id="landingLegalNoticeTermsOfUse">

    </Localized>;
    const privacy = <Localized id="landingLegalNoticePrivacyNotice">

    </Localized>;

    return (
      <LayoutWrapper flexModifier="column-center-start-breaking">
        {(isMinFirefox && !isMobile) ? this.renderInstallButton(isInstalling, hasAddon) : this.renderAltButton(isFirefox, isMobile) }
        {isMinFirefox && !isMobile && <LocalizedHtml id="landingLegalNotice" $terms={terms} $privacy={privacy}>

            By proceeding, you agree to the {terms} and {privacy} of Test Pilot.

        </LocalizedHtml>}
      </LayoutWrapper>
    );
  }

  renderOneClickInstallButton(title: string) {
    return (

        <LocalizedHtml id="oneClickInstallMinorCta">
          Install Test Pilot &
        </LocalizedHtml>
        <Localized id="oneClickInstallMajorCta" $title={title}>
          Enable {title}
        </Localized>

    );
  }

  renderInstallButton(isInstalling: boolean, hasAddon: any) {
    const { experimentTitle } = this.props;
    let installButton = null;
    if (experimentTitle) {
      installButton = this.renderOneClickInstallButton(experimentTitle);
    } else {
      installButton = <Localized id="landingInstallButton">

          Install the Test Pilot Add-on

      </Localized>;
    }
    const makeInstallButton = (extraClass = '') => {
      return <button onClick={e => this.install(e)}
        className={classnames(`button extra-large primary install ${extraClass}`, { 'state-change': isInstalling })}>
        {hasAddon && <Localized id="landingInstalledButton">
          Installed
        </Localized>}
        {!hasAddon && !isInstalling && installButton}
        {!hasAddon && isInstalling &&
          <Localized id="landingInstallingButton">
            Installing...
          </Localized>}

      </button>;
    };

    return <VariantTests name="installButtonBorder" varianttests={ this.props.varianttests }>
      <VariantTestCase value="bigBorder">
        { makeInstallButton('big-border') }
      </VariantTestCase>
      <VariantTestDefault>
        { makeInstallButton() }
      </VariantTestDefault>
    </VariantTests>;
  }

  renderAltButton(isFirefox: boolean, isMobile: boolean) {
    if (isFirefox && isMobile) {
      return (

          <Localized id="landingRequiresDesktop">
            Test Pilot requires Firefox for Desktop on Windows, Mac or Linux
          </Localized>

      );
    }
    return (

          {!isFirefox ? (
              <Localized id="landingDownloadFirefoxDesc">
                (Test Pilot is available for Firefox on Windows, OS X and Linux)
              </Localized>
            ) : (
              <Localized id="landingUpgradeDesc2" $version={config.minFirefoxVersion}>
                Test Pilot requires Firefox { config.minFirefoxVersion } or higher.
              </Localized>
            )
          }
          {!isMobile &&

              {(!isFirefox) ? (
                  <Localized id="landingDownloadFirefoxTitle">

Firefox

                  </Localized>
                ) : (
                  <Localized id="landingUpgradeFirefoxTitle">

Upgrade Firefox

                  </Localized>
                )
              }
              <Localized id="landingDownloadFirefoxSubTitle">

Free Download

              </Localized>

          }

    );
  }
}
<|endoftext|>


<commit_before>P.player = (function() {
  'use strict';

  var stage;
  var frameId = null;
  var isFullScreen = false;

  var progressBar = document.querySelector('.progress-bar');
  var player = document.querySelector('.player');
  var projectLink = document.querySelector('.project-link');
  var bugLink = document.querySelector('#bug-link');

  var controls = document.querySelector('.controls');
  var flag = document.querySelector('.flag');
  var turbo = document.querySelector('.turbo');
  var pause = document.querySelector('.pause');
  var stop = document.querySelector('.stop');
  var fullScreen = document.querySelector('.full-screen');

  var error = document.querySelector('.internal-error');
  var errorBugLink = document.querySelector('#error-bug-link');

  var flagTouchTimeout;
  function flagTouchStart() {
    flagTouchTimeout = setTimeout(function() {
      turboClick();
      flagTouchTimeout = true;
    }, 500);
  }
  function turboClick() {
    stage.isTurbo = !stage.isTurbo;
    flag.title = stage.isTurbo ? 'Turbo mode enabled. Shift+click to disable.' : 'Shift+click to enable turbo mode.';
    turbo.style.display = stage.isTurbo ? 'block' : 'none';
  }
  function flagClick(e) {
    if (!stage) return;
    if (flagTouchTimeout === true) return;
    if (flagTouchTimeout) {
      clearTimeout(flagTouchTimeout);
    }
    if (e.shiftKey) {
      turboClick();
    } else {
      stage.start();
      pause.className = 'pause';
      stage.stopAll();
      stage.triggerGreenFlag();
    }
    stage.focus();
    e.preventDefault();
  }

  function pauseClick(e) {
    if (!stage) return;
    if (stage.isRunning) {
      stage.pause();
      pause.className = 'play';
    } else {
      stage.start();
      pause.className = 'pause';
    }
    stage.focus();
    e.preventDefault();
  }

  function stopClick(e) {
    if (!stage) return;
    stage.start();
    pause.className = 'pause';
    stage.stopAll();
    stage.focus();
    e.preventDefault();
  }

  function fullScreenClick(e) {
    if (e) e.preventDefault();
    if (!stage) return;
    document.documentElement.classList.toggle('fs');
    isFullScreen = !isFullScreen;
    if (!e || !e.shiftKey) {
      if (isFullScreen) {
        var el = document.documentElement;
        if (el.requestFullScreenWithKeys) {
          el.requestFullScreenWithKeys();
        } else if (el.webkitRequestFullScreen) {
          el.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        }
      }
    }
    if (!isFullScreen) {
      document.body.style.width =
      document.body.style.height =
      document.body.style.marginLeft =
      document.body.style.marginTop = '';
    }
    updateFullScreen();
    if (!stage.isRunning) {
      stage.draw();
    }
    stage.focus();
  }

  function exitFullScreen(e) {
    if (isFullScreen && e.keyCode === 27) {
      fullScreenClick(e);
    }
  }

  function updateFullScreen() {
    if (!stage) return;
    if (isFullScreen) {
      window.scrollTo(0, 0);
      var padding = 8;
      var w = window.innerWidth - padding * 2;
      var h = window.innerHeight - padding - controls.offsetHeight;
      w = Math.min(w, h / .75);
      h = w * .75 + controls.offsetHeight;
      document.body.style.width = w + 'px';
      document.body.style.height = h + 'px';
      document.body.style.marginLeft = (window.innerWidth - w) / 2 + 'px';
      document.body.style.marginTop = (window.innerHeight - h - padding) / 2 + 'px';
      stage.setZoom(w / 480);
    } else {
      stage.setZoom(1);
    }
  }

  function preventDefault(e) {
    e.preventDefault();
  }

  window.addEventListener('resize', updateFullScreen);

  if (P.hasTouchEvents) {
    flag.addEventListener('touchstart', flagTouchStart);
    flag.addEventListener('touchend', flagClick);
    pause.addEventListener('touchend', pauseClick);
    stop.addEventListener('touchend', stopClick);
    fullScreen.addEventListener('touchend', fullScreenClick);

    flag.addEventListener('touchstart', preventDefault);
    pause.addEventListener('touchstart', preventDefault);
    stop.addEventListener('touchstart', preventDefault);
    fullScreen.addEventListener('touchstart', preventDefault);

    document.addEventListener('touchmove', function(e) {
      if (isFullScreen) e.preventDefault();
    });
  } else {
    flag.addEventListener('click', flagClick);
    pause.addEventListener('click', pauseClick);
    stop.addEventListener('click', stopClick);
    fullScreen.addEventListener('click', fullScreenClick);
  }

  document.addEventListener("fullscreenchange", function () {
    if (isFullScreen !== document.fullscreen) fullScreenClick();
  });
  document.addEventListener("mozfullscreenchange", function () {
    if (isFullScreen !== document.mozFullScreen) fullScreenClick();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    if (isFullScreen !== document.webkitIsFullScreen) fullScreenClick();
  });

  function load(id, cb, titleCallback) {
    P.player.projectId = id;
    P.player.projectURL = id ? 'http://scratch.mit.edu/projects/' + id + '/' : '';

    if (stage) {
      stage.stopAll();
      stage.pause();
    }
    while (player.firstChild) player.removeChild(player.lastChild);
    turbo.style.display = 'none';
    error.style.display = 'none';
    pause.className = 'pause';
    progressBar.style.display = 'none';

    if (id) {
      showProgress(P.IO.loadScratchr2Project(id), cb);
      P.IO.loadScratchr2ProjectTitle(id, function(title) {
        if (titleCallback) titleCallback(P.player.projectTitle = title);
      });
    } else {
      if (titleCallback) setTimeout(function() {
        titleCallback('');
      });
    }
  }

  function showError(e) {
    error.style.display = 'block';
    errorBugLink.href = 'https://github.com/nathan/phosphorus/issues/new?title=' + encodeURIComponent(P.player.projectTitle || P.player.projectURL) + '&body=' + encodeURIComponent('\n\n\n' + P.player.projectURL + '\nhttp://phosphorus.herokuapp.com/#' + P.player.projectId + '\n' + navigator.userAgent + (e.stack ? '\n\n```\n' + e.stack + '\n```' : ''));
    console.error(e.stack);
  }

  function showProgress(request, loadCallback) {
    progressBar.style.display = 'none';
    setTimeout(function() {
      progressBar.style.width = '10%';
      progressBar.className = 'progress-bar';
      progressBar.style.opacity = 1;
      progressBar.style.display = 'block';
    });
    request.onload = function(s) {
      progressBar.style.width = '100%';
      setTimeout(function() {
        progressBar.style.opacity = 0;
        setTimeout(function() {
          progressBar.style.display = 'none';
        }, 300);
      }, 100);

      var zoom = stage ? stage.zoom : 1;
      window.stage = stage = s;
      stage.start();
      stage.setZoom(zoom);

      stage.root.addEventListener('keydown', exitFullScreen);
      stage.handleError = showError;

      player.appendChild(stage.root);
      stage.focus();
      if (loadCallback) {
        loadCallback(stage);
        loadCallback = null;
      }
    };
    request.onerror = function(e) {
      progressBar.style.width = '100%';
      progressBar.className = 'progress-bar error';
      console.error(e.stack);
    };
    request.onprogress = function(e) {
      progressBar.style.width = (10 + e.loaded / e.total * 90) + '%';
    };
  }

  return {
    load: load,
    showProgress: showProgress
  };

}());
<commit_msg>Fix domain of bug report link to phosphorus (player.js)<commit_after>P.player = (function() {
  'use strict';

  var stage;
  var frameId = null;
  var isFullScreen = false;

  var progressBar = document.querySelector('.progress-bar');
  var player = document.querySelector('.player');
  var projectLink = document.querySelector('.project-link');
  var bugLink = document.querySelector('#bug-link');

  var controls = document.querySelector('.controls');
  var flag = document.querySelector('.flag');
  var turbo = document.querySelector('.turbo');
  var pause = document.querySelector('.pause');
  var stop = document.querySelector('.stop');
  var fullScreen = document.querySelector('.full-screen');

  var error = document.querySelector('.internal-error');
  var errorBugLink = document.querySelector('#error-bug-link');

  var flagTouchTimeout;
  function flagTouchStart() {
    flagTouchTimeout = setTimeout(function() {
      turboClick();
      flagTouchTimeout = true;
    }, 500);
  }
  function turboClick() {
    stage.isTurbo = !stage.isTurbo;
    flag.title = stage.isTurbo ? 'Turbo mode enabled. Shift+click to disable.' : 'Shift+click to enable turbo mode.';
    turbo.style.display = stage.isTurbo ? 'block' : 'none';
  }
  function flagClick(e) {
    if (!stage) return;
    if (flagTouchTimeout === true) return;
    if (flagTouchTimeout) {
      clearTimeout(flagTouchTimeout);
    }
    if (e.shiftKey) {
      turboClick();
    } else {
      stage.start();
      pause.className = 'pause';
      stage.stopAll();
      stage.triggerGreenFlag();
    }
    stage.focus();
    e.preventDefault();
  }

  function pauseClick(e) {
    if (!stage) return;
    if (stage.isRunning) {
      stage.pause();
      pause.className = 'play';
    } else {
      stage.start();
      pause.className = 'pause';
    }
    stage.focus();
    e.preventDefault();
  }

  function stopClick(e) {
    if (!stage) return;
    stage.start();
    pause.className = 'pause';
    stage.stopAll();
    stage.focus();
    e.preventDefault();
  }

  function fullScreenClick(e) {
    if (e) e.preventDefault();
    if (!stage) return;
    document.documentElement.classList.toggle('fs');
    isFullScreen = !isFullScreen;
    if (!e || !e.shiftKey) {
      if (isFullScreen) {
        var el = document.documentElement;
        if (el.requestFullScreenWithKeys) {
          el.requestFullScreenWithKeys();
        } else if (el.webkitRequestFullScreen) {
          el.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        }
      }
    }
    if (!isFullScreen) {
      document.body.style.width =
      document.body.style.height =
      document.body.style.marginLeft =
      document.body.style.marginTop = '';
    }
    updateFullScreen();
    if (!stage.isRunning) {
      stage.draw();
    }
    stage.focus();
  }

  function exitFullScreen(e) {
    if (isFullScreen && e.keyCode === 27) {
      fullScreenClick(e);
    }
  }

  function updateFullScreen() {
    if (!stage) return;
    if (isFullScreen) {
      window.scrollTo(0, 0);
      var padding = 8;
      var w = window.innerWidth - padding * 2;
      var h = window.innerHeight - padding - controls.offsetHeight;
      w = Math.min(w, h / .75);
      h = w * .75 + controls.offsetHeight;
      document.body.style.width = w + 'px';
      document.body.style.height = h + 'px';
      document.body.style.marginLeft = (window.innerWidth - w) / 2 + 'px';
      document.body.style.marginTop = (window.innerHeight - h - padding) / 2 + 'px';
      stage.setZoom(w / 480);
    } else {
      stage.setZoom(1);
    }
  }

  function preventDefault(e) {
    e.preventDefault();
  }

  window.addEventListener('resize', updateFullScreen);

  if (P.hasTouchEvents) {
    flag.addEventListener('touchstart', flagTouchStart);
    flag.addEventListener('touchend', flagClick);
    pause.addEventListener('touchend', pauseClick);
    stop.addEventListener('touchend', stopClick);
    fullScreen.addEventListener('touchend', fullScreenClick);

    flag.addEventListener('touchstart', preventDefault);
    pause.addEventListener('touchstart', preventDefault);
    stop.addEventListener('touchstart', preventDefault);
    fullScreen.addEventListener('touchstart', preventDefault);

    document.addEventListener('touchmove', function(e) {
      if (isFullScreen) e.preventDefault();
    });
  } else {
    flag.addEventListener('click', flagClick);
    pause.addEventListener('click', pauseClick);
    stop.addEventListener('click', stopClick);
    fullScreen.addEventListener('click', fullScreenClick);
  }

  document.addEventListener("fullscreenchange", function () {
    if (isFullScreen !== document.fullscreen) fullScreenClick();
  });
  document.addEventListener("mozfullscreenchange", function () {
    if (isFullScreen !== document.mozFullScreen) fullScreenClick();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    if (isFullScreen !== document.webkitIsFullScreen) fullScreenClick();
  });

  function load(id, cb, titleCallback) {
    P.player.projectId = id;
    P.player.projectURL = id ? 'http://scratch.mit.edu/projects/' + id + '/' : '';

    if (stage) {
      stage.stopAll();
      stage.pause();
    }
    while (player.firstChild) player.removeChild(player.lastChild);
    turbo.style.display = 'none';
    error.style.display = 'none';
    pause.className = 'pause';
    progressBar.style.display = 'none';

    if (id) {
      showProgress(P.IO.loadScratchr2Project(id), cb);
      P.IO.loadScratchr2ProjectTitle(id, function(title) {
        if (titleCallback) titleCallback(P.player.projectTitle = title);
      });
    } else {
      if (titleCallback) setTimeout(function() {
        titleCallback('');
      });
    }
  }

  function showError(e) {
    error.style.display = 'block';
    errorBugLink.href = 'https://github.com/nathan/phosphorus/issues/new?title=' + encodeURIComponent(P.player.projectTitle || P.player.projectURL) + '&body=' + encodeURIComponent('\n\n\n' + P.player.projectURL + '\nhttp://phosphorus.github.io/#' + P.player.projectId + '\n' + navigator.userAgent + (e.stack ? '\n\n```\n' + e.stack + '\n```' : ''));
    console.error(e.stack);
  }

  function showProgress(request, loadCallback) {
    progressBar.style.display = 'none';
    setTimeout(function() {
      progressBar.style.width = '10%';
      progressBar.className = 'progress-bar';
      progressBar.style.opacity = 1;
      progressBar.style.display = 'block';
    });
    request.onload = function(s) {
      progressBar.style.width = '100%';
      setTimeout(function() {
        progressBar.style.opacity = 0;
        setTimeout(function() {
          progressBar.style.display = 'none';
        }, 300);
      }, 100);

      var zoom = stage ? stage.zoom : 1;
      window.stage = stage = s;
      stage.start();
      stage.setZoom(zoom);

      stage.root.addEventListener('keydown', exitFullScreen);
      stage.handleError = showError;

      player.appendChild(stage.root);
      stage.focus();
      if (loadCallback) {
        loadCallback(stage);
        loadCallback = null;
      }
    };
    request.onerror = function(e) {
      progressBar.style.width = '100%';
      progressBar.className = 'progress-bar error';
      console.error(e.stack);
    };
    request.onprogress = function(e) {
      progressBar.style.width = (10 + e.loaded / e.total * 90) + '%';
    };
  }

  return {
    load: load,
    showProgress: showProgress
  };

}());
<|endoftext|>


<commit_before>function calculateBet(gameState) {
  let ownCards = gameState.players[gameState.in_action].hole_cards;
  let communityCards = gameState.community_cards;

  return 100;
}

module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function (game_state, bet) {
    try {
      bet(calculateBet(game_state));
    } catch (error) {
      console.error('error occurred fix it and redeploy, playing random now', error);
      if (Math.random(1) > 0.5) {
        bet(game_state.current_buy_in);
      }
      else {
        bet(0);
      }
    }
  },

  showdown: function (game_state) {

  }
};
<commit_msg>require valuemap<commit_after>const valueMap = require('valuemap');

function calculateBet(gameState) {
  let ownCards = gameState.players[gameState.in_action].hole_cards;
  let communityCards = gameState.community_cards;

  return 100;
}

module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function (game_state, bet) {
    try {
      bet(calculateBet(game_state));
    } catch (error) {
      console.error('error occurred fix it and redeploy, playing random now', error);
      if (Math.random(1) > 0.5) {
        bet(game_state.current_buy_in);
      }
      else {
        bet(0);
      }
    }
  },

  showdown: function (game_state) {

  }
};
<|endoftext|>


<commit_before>var _ = require('lodash')
var inherits = require('inherits')
var aabb = require('aabb-2d')
var math = require('mathjs')
var transform = require('./transform.js')
var circle = require('./geo/circle.js')
var Collision = require('./collision.js')
var Fixmove = require('./fixmove.js')
var Automove = require('./automove.js')
var Freemove = require('./freemove.js')
var Entity = require('crtrdg-entity')

module.exports = Player;
inherits(Player, Entity);

function Player(opts){
  this.geometry = circle({
    position: opts.position,
    angle: opts.angle,
    fill: opts.fill,
    stroke: opts.stroke,
    scale: opts.scale,
    thickness: opts.thickness,
    children: [
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [-0.7, -.9], scale: 0.6, angle: -45, aspect: 0.6}),
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [0.7, -.9], scale: 0.6, angle: 45, aspect: 0.6})
    ]
  })
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['Q', 'E', 'S', 'W'],
    heading: [-60, 60, -180, 0],
    shift: [0, 0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: ['S'],
    heading: [-180],
    shift: [8],
    speed: opts.speed
  })
  this.collision = new Collision()
  this.waiting = true
}

Player.prototype.move = function(keyboard, world) {
  var self = this

  var current = self.geometry.transform
  var tile = world.tiles[world.locate(self.position())]
  var inside =  tile.children[0].contains(current.position())
  var keys = keyboard.keysDown

  var delta
  if (inside) {
    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        position: [tile.transform.position()[0], tile.transform.position()[1]]
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }
  } else {
    self.waiting = true
    self.movement.tile.reset()
    delta = self.movement.path.compute(keys, current)
  }

  self.geometry.update(delta)
  self.collision.handle(world, self.geometry, delta)
}

Player.prototype.draw = function(context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.position = function() {
  return this.geometry.transform.position()
}

Player.prototype.angle = function() {
  return this.geometry.transform.angle()
}

Player.prototype.scale = function() {
  return this.geometry.transform.scale()
}
<commit_msg>Change current keys<commit_after>var _ = require('lodash')
var inherits = require('inherits')
var aabb = require('aabb-2d')
var math = require('mathjs')
var transform = require('./transform.js')
var circle = require('./geo/circle.js')
var Collision = require('./collision.js')
var Fixmove = require('./fixmove.js')
var Automove = require('./automove.js')
var Freemove = require('./freemove.js')
var Entity = require('crtrdg-entity')

module.exports = Player;
inherits(Player, Entity);

function Player(opts){
  this.geometry = circle({
    position: opts.position,
    angle: opts.angle,
    fill: opts.fill,
    stroke: opts.stroke,
    scale: opts.scale,
    thickness: opts.thickness,
    children: [
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [-0.7, -.9], scale: 0.6, angle: -45, aspect: 0.6}),
      circle({fill: opts.fill, stroke: opts.stroke, thickness: opts.thickness,
        position: [0.7, -.9], scale: 0.6, angle: 45, aspect: 0.6})
    ]
  })
  this.movement = {}
  this.movement.center = new Fixmove({speed: opts.speed})
  this.movement.tile = new Automove({
    keymap: ['A', 'D', 'S', 'W'],
    heading: [-60, 60, -180, 0],
    shift: [0, 0, 0, 8],
    speed: opts.speed
  })
  this.movement.path = new Automove({
    keymap: ['S'],
    heading: [-180],
    shift: [8],
    speed: opts.speed
  })
  this.collision = new Collision()
  this.waiting = true
}

Player.prototype.move = function(keyboard, world) {
  var self = this

  var current = self.geometry.transform
  var tile = world.tiles[world.locate(self.position())]
  var inside =  tile.children[0].contains(current.position())
  var keys = keyboard.keysDown

  var delta
  if (inside) {
    if (self.movement.tile.keypress(keys)) self.waiting = false
    if (self.waiting) {
      var center = {
        position: [tile.transform.position()[0], tile.transform.position()[1]]
      }
      delta = self.movement.center.compute(current, center)
    } else {
      delta = self.movement.tile.compute(keys, current, tile.transform)
    }
  } else {
    self.waiting = true
    self.movement.tile.reset()
    delta = self.movement.path.compute(keys, current)
  }

  self.geometry.update(delta)
  self.collision.handle(world, self.geometry, delta)
}

Player.prototype.draw = function(context, camera) {
  this.geometry.draw(context, camera, {order: 'bottom'})
}

Player.prototype.position = function() {
  return this.geometry.transform.position()
}

Player.prototype.angle = function() {
  return this.geometry.transform.angle()
}

Player.prototype.scale = function() {
  return this.geometry.transform.scale()
}
<|endoftext|>


<commit_before>var ranker = require("./ranker");
module.exports = {

    VERSION: "Objects in mirror are closer than they appear",

    bet_request: function (game_state, bet) {
        //max and min for random bet
        var max = 1000;
        var min = 300;
        try {
            var sb = game_state.small_blind;
            var orbits = game_state.orbits;
            var cc = game_state.community_cards;
            var cb = game_state.current_buy_in;
            var pot = game_state.pot;
            var we;

            //Assign variable for our player
            game_state.players.forEach(function (player) {
                if (player.name == 'All In') {
                    we = player;
                    //console.log(we);
                }
            });

            var hc = we.hole_cards;
            var call = cb - we.bet; //buyin - our bet

            //Print community cards in loop
            /*
            cc.forEach(function (card) {
                console.log("Cards");
                console.log(card);
            });
*/
            var rank = ranker.rank_hand(hc);
            if (rank <= 3) {
                //if we are forced to all-in, then
                if (call >= we.stack) {
                    switch (rank) {
                    case 1:
                        bet(call);
                        break;
                    case 2:
                        if (Math.random() < 0.75 ? 1 : 0) {
                            bet(call);
                        }
                        break;
                    case 3:
                        if (Math.random() < 0.6 ? 1 : 0) {
                            bet(call);
                        }
                        break;
                    }
                    bet(0);
                } else {
                    //raise 200
                    bet(call + 200);
                }
            } else if (rank >= 4 && rank <= 6) {
                bet(call);
            } else if (rank >= 7) {
                bet(0);
            } else {
                // Bet min call to cb + 200
                bet(Math.floor(Math.random() * (call + 200 - call + 1) + call));
            }

            //bet(Math.floor(Math.random() * (max - min + 1) + min));
        } catch (e) {
            bet(4000);
            //console.log(e);
        }

    },

    showdown: function (game_state) {
        console.log(game_state);
    }
};<commit_msg>repair<commit_after>var ranker = require("./ranker");
module.exports = {

    VERSION: "Objects in mirror are closer than they appear",

    bet_request: function (game_state, bet) {
        //max and min for random bet
        var max = 1000;
        var min = 300;
        try {
            var sb = game_state.small_blind;
            var orbits = game_state.orbits;
            var cc = game_state.community_cards;
            var cb = game_state.current_buy_in;
            var pot = game_state.pot;
            var we;

            //Assign variable for our player
            game_state.players.forEach(function (player) {
                if (player.name == 'All In') {
                    we = player;
                    //console.log(we);
                }
            });

            var hc = we.hole_cards;
            var call = cb - we.bet; //buyin - our bet

            //Print community cards in loop
            /*
            cc.forEach(function (card) {
                console.log("Cards");
                console.log(card);
            });
*/
            var ourBet;
            var rank = ranker.rank_hand(hc);
            if (rank <= 3) {
                //if we are forced to all-in, then
                if (call >= we.stack) {
                    switch (rank) {
                    case 1:
                        ourBet = call;
                        break;
                    case 2:
                        if (Math.random() < 0.75 ? 1 : 0) {
                            ourBet = call;
                        }
                        break;
                    case 3:
                        if (Math.random() < 0.6 ? 1 : 0) {
                            ourBet = call;
                        }
                        break;
                    }
                    ourBet = 0;
                } else {
                    //raise 200
                    ourBet = call + 200;
                }
            } else if (rank >= 4 && rank <= 6) {
                ourBet = call;
            } else if (rank >= 7) {
                ourBet = 0;
            } else {
                // Bet min call to cb + 200
                ourBet = Math.floor(Math.random() * (call + 200 - call + 1) + call);
            }
            bet(ourBet | 0);
            //bet(Math.floor(Math.random() * (max - min + 1) + min));
        } catch (e) {
            bet(4000);
            //console.log(e);
        }

    },

    showdown: function (game_state) {
        console.log(game_state);
    }
};<|endoftext|>


<commit_before>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var SWAP_BUFFER = 0.5;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/1.5;
	this.y = SCREEN_HEIGHT/1.3;
	this.width = 72.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87

	this.lives = 3;
	this.shooting = false;

	this.swapBuffer = SWAP_BUFFER;
	this.swapAllowed = true;

	this.score = 0;

	this.hasKey = false;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellPortal 	= cellAtTileCoord(LAYER_PORTAL, tx, 		ty);
	var cellKey 	= cellAtTileCoord(LAYER_KEYS, 	   tx, 		ty);
	var cellDoor 	= cellAtTileCoord(LAYER_DOORS,    tx, 		ty);

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;
		if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
			this.sprite.setAnimation(ANIM_WALK_LEFT);
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
	}

	//reset to idle animation
	else {
		if(this.jumping == false && this.falling == false)
		{
			if(this.sprite.currentAnimation != ANIM_IDLE)
			this.sprite.setAnimation(ANIM_IDLE);
		}
	}

	//set jumping animation
	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	//check for a reality swap
	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellPortal && this.swapAllowed){

		if (CurrentLevel == level1_green){
			CurrentLevel = level1_blue;
			initialize(CurrentLevel);
		}
		else if (CurrentLevel == level1_blue){
			CurrentLevel = level1_green;
			initialize(CurrentLevel);
		}

		this.swapAllowed = false;
	}

	if (!this.swapAllowed){
		this.swapBuffer -= deltaTime;

		if (this.swapBuffer <= 0){
			this.swapBuffer = SWAP_BUFFER;
			this.swapAllowed = true;

		}

	}

	//the player gains the key
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellKey){
		this.hasKey = true;
	}

	//player has key and is at the door
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor && this.hasKey){
		curGameState = GAMESTATE_ENDGAME
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;
		this.sprite.setAnimation(ANIM_JUMP)
	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/2;
	this.y = SCREEN_HEIGHT/2;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x + (this.width/2), this.y + (this.height/2));
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();

	//context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<commit_msg>changed respawn location.<commit_after>var METER  = TILE;
var GRAVITY = METER * 9.8 * 3;
var MAXDX = METER * 10;
var MAXDY = METER * 15;
var ACCEL = MAXDX * 2;
var JUMP = METER * 1500;
var FRICTION = MAXDX * 6;

var SWAP_BUFFER = 0.5;

var LEFT = 0;
var RIGHT = 1;

var ANIM_IDLE = 0;
var ANIM_JUMP = 1;
var ANIM_WALK_LEFT = 2;
var ANIM_WALK_RIGHT = 3;
var ANIM_MAX = 4;

var Player = function(){

	this.sprite = new Sprite("p1_spritesheet.png");
	this.sprite.buildAnimation(7, 3, 73.5, 95, 0.05,
		[4]);
	this.sprite.buildAnimation(7, 3, 73, 94, 0.05,
		[13, 13]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[0, 1, 2, 7, 9, 10, 3, 4, 5]);
	this.sprite.buildAnimation(7, 3, 72.7, 97, 0.05,
		[5, 4, 3, 10, 9, 7, 2, 1, 0]);

	for(var i=0; i<ANIM_MAX; i++)
	{
		this.sprite.setAnimationOffset(i, -55, -87);
	}

	this.x = SCREEN_WIDTH/1.7;
	this.y = SCREEN_HEIGHT/1.3;
	this.width = 72.5;
	this.height = 95;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.falling = true;
	this.jumping = false;

	this.offset_x = -55;
	this.offset_y = -87

	this.lives = 3;
	this.shooting = false;

	this.swapBuffer = SWAP_BUFFER;
	this.swapAllowed = true;

	this.score = 0;

	this.hasKey = false;

	this.direction = LEFT;

};

Player.prototype.Update = function(deltaTime) {

	this.sprite.update(deltaTime);

	GRAVITY = METER * 9.8 * 3;

	var tx = pixel2Tile(this.x);
	var ty = pixel2Tile(this.y);

	var nx = this.x % TILE;
	var ny = this.y % TILE;

	var cell = 		 cellAtTileCoord(LAYER_GROUND, tx, 		ty);
	var cellRight =	 cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty);
	var cellDown  =	 cellAtTileCoord(LAYER_GROUND, tx, 		ty + 1);
	var cellDiag  =  cellAtTileCoord(LAYER_GROUND, tx + 1, 	ty + 1);

	var cellPortal 	= cellAtTileCoord(LAYER_PORTAL, tx, 		ty);
	var cellKey 	= cellAtTileCoord(LAYER_KEYS, 	   tx, 		ty);
	var cellDoor 	= cellAtTileCoord(LAYER_DOORS,    tx, 		ty);

	var left, right, jump;
	left = right = jump = false;

	//changing anmiation and direction for left
	if(keyboard.isKeyDown(keyboard.KEY_LEFT)){
		left = true;
		this.direction = LEFT;
		if(this.sprite.currentAnimation != ANIM_WALK_LEFT)
			this.sprite.setAnimation(ANIM_WALK_LEFT);
	}

	//changing anmiation and direction for right
	else if (keyboard.isKeyDown(keyboard.KEY_RIGHT)){
		right = true;
		this.direction = RIGHT;
		if(this.sprite.currentAnimation != ANIM_WALK_RIGHT)
			this.sprite.setAnimation(ANIM_WALK_RIGHT);
	}

	//reset to idle animation
	else {
		if(this.jumping == false && this.falling == false)
		{
			if(this.sprite.currentAnimation != ANIM_IDLE)
			this.sprite.setAnimation(ANIM_IDLE);
		}
	}

	//set jumping animation
	if ((keyboard.isKeyDown(keyboard.KEY_SPACE)) || (keyboard.isKeyDown(keyboard.KEY_UP))){
		jump = true;
		this.score += 1;
		if(this.sprite.currentAnimation != ANIM_JUMP)
			this.sprite.setAnimation(ANIM_JUMP);
	}

	//check for a reality swap
	if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellPortal && this.swapAllowed){

		if (CurrentLevel == level1_green){
			CurrentLevel = level1_blue;
			initialize(CurrentLevel);
		}
		else if (CurrentLevel == level1_blue){
			CurrentLevel = level1_green;
			initialize(CurrentLevel);
		}

		this.swapAllowed = false;
	}

	if (!this.swapAllowed){
		this.swapBuffer -= deltaTime;

		if (this.swapBuffer <= 0){
			this.swapBuffer = SWAP_BUFFER;
			this.swapAllowed = true;

		}

	}

	//the player gains the key
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellKey){
		this.hasKey = true;
	}

	//player has key and is at the door
	else if ((keyboard.isKeyDown(keyboard.KEY_CTRL)) && cellDoor && this.hasKey){
		curGameState = GAMESTATE_ENDGAME
	}

	//jump = keyboard.isKeyDown(keyboard.KEY_SPACE);

	var wasleft = this.velocityX < 0;
	var wasright = this.velocityX > 0;

	var falling = this.falling;
	var ddx = 0;			 //ACCELERATION
	var ddy = GRAVITY;

	if (left){
		ddx -= ACCEL;
	}
	else if (wasleft){
		ddx += FRICTION;
	}

	if (right){
		ddx += ACCEL;
	}
	else if (wasright){
		ddx -= FRICTION
	}

	if (jump && !this.jumping && !falling){
		ddy -= JUMP;
		this.jumping = true;
		this.sprite.setAnimation(ANIM_JUMP)
	}

	//calculate the new postioin and velocity:
	this.x += deltaTime * this.velocityX;
	this.y += deltaTime * this.velocityY;
	this.velocityX = bound(this.velocityX + (deltaTime * ddx), -MAXDX, MAXDX);
	this.velocityY = bound(this.velocityY + (deltaTime * ddy), -MAXDY, MAXDY);

	if (this.y > SCREEN_HEIGHT){
			this.lives --;
			if (this.lives <= 0){
				curGameState = GAMESTATE_ENDGAME;

			}

			else{
				this.respawn();
			}

		}

	if ( (wasleft && (this.velocityX > 0)) || (wasright && (this.velocityX < 0))){
		//clamp at zero to prevbent frition from making us jiggle side to side
		this.velocityX = 0;
	}

	//rotation when walking
	//if ( this.velocityX > 0){
	//	this.rotation = (this.velocityX / MAXDX) * (Math.PI / 8) ;
	//}
	//else if (this.velocityX < 0){
	//	this.rotation = (-this.velocityX / MAXDX) * (-Math.PI /8);
	//}
	//else{
	//	this.rotation = 0;
	//}

	//CEILING
	if(this.velocityY > 0){
		if ((cellDown & !cell) || (cellDiag && !cellRight && nx)){
			this.y = tile2Pixel(ty);
			this.velocityY = 0;
			this.falling = false;
			this.jumping = false;
			ny = 0;
		}

	}
	//FLOOR
	else if (this.velocityY < 0) {
		if ((cell && !cellDown) || (cellRight && !cellDiag && nx)){
			//calmp the y poition to avoid jumping into platform above

			this.y = tile2Pixel(ty + 1);
			this.velocityY = 0; 		//stop upward velocity

			cell = cellDown;
			cellRight = cellDiag;
			ny = 0;
		}
	}

	if (this.velocityX > 0){
		if ((cellRight && !cell) || (cellDiag && !cellDown && ny)){
			//clamp the x position to avoid moving into the platform we just hit
			this.x = tile2Pixel(tx);
			this.velocityX = 0;
		}
	}

	else if (this.velocityX < 0){
		if((cell && !cellRight) || (cellDown && !cellDiag && ny)){
			this.x = tile2Pixel(tx + 1);
			this.velocityX = 0;
		}
	}

Player.prototype.respawn = function(){
	this.x = SCREEN_WIDTH/1.7;
	this.y = SCREEN_HEIGHT/1.3;
	this.width = 73.5;
	this.height = 95;

	this.offset_x = -55;
	this.offset_y = -87;

	this.velocityX =  0;
	this.velocityY = 0;
	this.angularVelocity = 0;
	this.rotation = 0;

	this.shooting = false;
	this.ammo = 7;
}

};

Player.prototype.Draw = function(_cam_x, _cam_y){

	this.sprite.draw(context, this.x + (this.width/2), this.y + (this.height/2));
//	context.save();
//
//		context.translate(this.x + _cam_x, this.y + _cam_y);
//		context.rotate(this.rotation);
//		context.drawImage(this.image,
//							-this.width/2,
//							-this.height/2)
//
//	context.restore();
//
	context.save();

	context.beginPath();

	//context.rect(this.x - (this.width/2)  , this.y - (this.height/2), this.width, this.height);
	context.stroke();
	context.restore();

};

<|endoftext|>