Click game example¶
In this very basic game players must click an appearing square as quick as possible in order to score points.
This example uses jQuery.
Server - examples/click-game.py¶
#!/usr/bin/env python
from time import time
from random import random
import gevent
import example_pythonpath
from example_utils import ExampleServer, ExampleStaticFile
class TimePusherServer(ExampleServer):
urls = [
('/', ExampleStaticFile('click-game.html')),
] + ExampleServer.urls
def server_init(self):
self.score = 0
gevent.spawn(self.main_loop)
def main_loop(self):
while True:
gevent.sleep(2)
x = random()
y = random()
self.sessions.notify('target', { 'x': x, 'y': y })
def rpc_click(self, request):
self.score += 1
self.sessions.notify('score', self.score)
if __name__ == '__main__':
TimePusherServer.main()
Client - examples/click-game.html¶
<!DOCTYPE html>
<html>
<head>
<title>Mushroom Click Game</title>
<style>
#score {
font-size: 200%;
font-weight: bold;
margin-bottom: 20px;
}
#playing-area {
position: relative;
width: 440px;
height: 440px;
background-color: #ccc;
border-radius: 20px;
}
#target {
position: absolute;
margin: 20px;
height: 40px;
width: 40px;
background-color: #900;
border-radius: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="score">0</div>
<div id="playing-area">
<div id="target"></div>
</div>
<script src="/js/mushroom.js"></script>
<script src="/js/jquery.js"></script>
<script>
$(function() {
var client = new mushroom.Client({
url: '/'
});
var $target = $('#target');
client.method('target', function(request) {
$target.css({
left: (request.data.x * 400) + 'px',
top: (request.data.y * 400) + 'px'
});
});
var $score = $('#score');
client.method('score', function(request) {
$score.text(request.data);
});
client.signals.connected.connect(function() {
$('#target').click(function() {
client.notify('click');
});
});
client.connect();
});
</script>
</body>
</html>