我的 2 人、纯文本、基于浏览器的游戏运行良好,但一名玩家无法知道另一名玩家的回合何时完成,除非尝试自己轮流。可以在标准的低成本 GAE 应用程序中实现所需的结果(传达(推送)信息)吗?
我已经消化了Joran Beasley's fine answer example使用普通 Python 编写,但假设套接字会增加 GAE 应用程序的成本。如果我关于成本的前提不正确,请纠正我,然后你能告诉我如何在 GAE 中添加套接字吗?但我希望有一种经济的方法可以在没有套接字的情况下增强我的应用程序。
Python:
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(
self,
filename,
template_values,
**template_args
):
template = JINJA_ENVIRONMENT.get_template(filename)
self.response.out.write(template.render(template_values))
class MainPage(BaseHandler):
def get(self):
global player
global players
global scores
global target
global guesses
player = 0
players = ['me','you']
scores = [False , False]
target = random.randrange(10)
initguesses = ['','']
guesses = initguesses
template_values = {'scores':scores}
return webapp2.redirect("/game/%s" % players[0])
class Game(BaseHandler):
def get(self,who_id):
who = players.index(who_id)
template_values = {'scores':scores,'guesses':guesses[who],'players':players,'who_id':who_id}
template = JINJA_ENVIRONMENT.get_template('game.html')
self.response.out.write(template.render(template_values))
def post(self,who_id):
global player
who = players.index(who_id)
if who == player:
guess = self.request.get('guess', None)
guesses[player]=guess+guesses[player]
scores[player]=int(guess)==target
logging.info("target: %s" % target)
next_player = player
player = (1+player)%2
template_values = {'scores':scores}
return webapp2.redirect("/game/%s" % who_id)
游戏.html
{% extends "base.html" %}
{% block content %}
<h1>{{who_id}}</h1>
<br/>
<form action="" method="post">
Guess an integer here <br />
0 ... 9: <input type="textbox" name="guess" value=></input>
<input type="submit" value="submit" />
</form>
<p> Your previous guess(es): {{ guesses }}</p>
<p> Got target right (yet)?:
{% for score in scores %}
<br />
{% if score %}
<h2>
{% endif %}
{{players[loop.index0] }} {{ score }}
{% if score %}
</h2>
{% endif %}
{% endfor %}
</p>
{% if who_id == players[0] %}
<p> You can start over at the beginning (<a href="/"> here.</a>) but everyone restarts. </p>
{% endif %}
<p>If you see no change above, it's not your turn.</p>
{% endblock content %}
最佳答案
菲利普给出了一个很好的答案。
作为替代方案,您可以考虑使用推送通知服务,例如 OneSignal例如。
当玩家采取行动时,您向 OneSingla 发出 http(s) 请求,他们会处理 Websocket(或客户端可用的任何内容)来发送通知。
while game.is_active:
client1 => AppEngine => OneSignal => client2
client2 => AppEngine => OneSignal => client1
使用 OneSignal 是免费的,而且很少有类似的服务。
关于python - 无套接字多人游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46625275/