source: pycgibattler/trunk/index.cgi @ 75

Revision 75, 7.3 KB checked in by atzm, 13 years ago (diff)

add preamble

  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4#  Copyright (C) 2010 by Atzm WATANABE <atzm@atzm.org>
5#
6#  This program is free software; you can redistribute it and/or modify it
7#  under the terms of the GNU General Public License (version 2) as
8#  published by the Free Software Foundation.  It is distributed in the
9#  hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
10#  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11#  PURPOSE.  See the GNU General Public License for more details.
12#
13# $Id$
14#
15
16from __future__ import with_statement
17
18import os
19import re
20import sys
21import cgi
22import json
23import glob
24import copy
25import fcntl
26import shutil
27import hashlib
28import ConfigParser
29
30try:
31    import cStringIO as _StringIO
32except ImportError:
33    import StringIO as _StringIO
34
35try:
36    import cPickle as _pickle
37except ImportError:
38    import pickle as _pickle
39
40from Cheetah.Template import Template
41import pycodebattler
42
43
44CONFIG = ConfigParser.SafeConfigParser()
45CONFIG.read('pycgibattler.conf')
46
47
48class ListChooser:
49    def __init__(self, code):
50        self._code = code
51        self._digest = int(hashlib.sha512(code).hexdigest(), 16)
52
53    def lslide(self, i):
54        self._digest <<= i
55
56    def rslide(self, i):
57        self._digest >>= i
58
59    def choose(self, list_):
60        return list_[self._digest % len(list_)]
61
62
63class CharacterManager:
64    VALID_ID = re.compile(r'^[a-f0-9]{128}$')
65    DATA_DIR = os.path.expanduser(CONFIG.get('data', 'basedir'))
66
67    def __init__(self, id_):
68        if not self.VALID_ID.match(id_):
69            raise ValueError('Invalid ID: %s' % id_)
70        self._id = id_
71        self._locker = os.path.join(self.DATA_DIR, '.%s.lck' % id_)
72        self._prefix = os.path.join(self.DATA_DIR, id_)
73        self._codepath = os.path.join(self._prefix, '%s.py' % id_)
74        self._datapath = os.path.join(self._prefix, '%s.dat' % id_)
75
76    def id(self):
77        return self._id
78
79    def mtime(self):
80        with open(self._locker) as fp:
81            fcntl.flock(fp, fcntl.LOCK_SH)
82            return os.fstat(fp.fileno()).st_mtime
83
84    def delete(self):
85        with open(self._locker, 'w') as fp:
86            fcntl.flock(fp, fcntl.LOCK_EX)
87            shutil.rmtree(self._prefix, True)
88            os.remove(self._locker)  # XXX
89
90    def load(self):
91        with open(self._locker) as fp:
92            fcntl.flock(fp, fcntl.LOCK_SH)
93            code = open(self._codepath).read()
94            warrior = _pickle.load(open(self._datapath))
95            return code, warrior
96
97    def flatten(self):
98        code, warrior = self.load()
99        return {
100            'id':      self.id(),
101            'mtime':   self.mtime(),
102            'code':    code,
103            'warrior': warrior,
104            'skills':  [warrior.skill(s) for s in warrior.skill_list()],
105        }
106
107    @classmethod
108    def dump(klass, name, code):
109        self = klass(hashlib.sha512(code).hexdigest())
110        cname = os.path.join(self._prefix, os.path.basename(name))
111        warrior = self.make_warrior(code)
112
113        with open(self._locker, 'w') as fp:
114            fcntl.flock(fp, fcntl.LOCK_EX)
115
116            try:
117                os.mkdir(self._prefix)
118            except OSError:
119                if not os.path.isdir(self._prefix):
120                    raise
121
122            open(self._codepath, 'w').write(code)
123            _pickle.dump(warrior, open(self._datapath, 'w'))
124
125            try:
126                os.symlink(os.path.basename(self._codepath), cname)
127            except OSError:
128                if not os.path.islink(cname):
129                    raise
130
131        return self
132
133    @classmethod
134    def make_warrior(klass, code):
135        chara_names = [x.strip() for x in open(os.path.expanduser(
136            CONFIG.get('character', 'name_list_file'))).xreadlines()]
137        skill_data = json.load(open(os.path.expanduser(
138            CONFIG.get('character', 'skill_list_file'))))
139
140        lc = ListChooser(code)
141        name = lc.choose(chara_names)
142        skills = []
143
144        for i in range(lc.choose(range(1, 4))):
145            lc.lslide(i)
146            sk = lc.choose(skill_data)
147            skname = sk['name'].encode('utf-8')
148            skpoint = sk['point']
149            sktype = getattr(pycodebattler.skill, sk['type'])
150            sklevel = sk['level']
151            sk = pycodebattler.skill.Skill(skname, skpoint, sktype, sklevel)
152            skills.append(sk)
153
154        return pycodebattler.warrior.Warrior(
155            name, _StringIO.StringIO(code), skills)
156
157    @classmethod
158    def list(klass):
159        return sorted((klass(os.path.basename(d)) for d in
160                       glob.iglob(os.path.join(klass.DATA_DIR, '*'))
161                       if klass.VALID_ID.match(os.path.basename(d))),
162                      cmp=klass.mtimecmp)
163
164    @classmethod
165    def sweep(klass, thresh=CONFIG.getint('limit', 'max_entries')):
166        for self in klass.list()[thresh:]:
167            self.delete()
168
169    @staticmethod
170    def mtimecmp(a, b):
171        return int(b.mtime()) - int(a.mtime())
172
173
174def do_battle(warriors, turn=CONFIG.getint('battle', 'max_turn')):
175    proto = pycodebattler.battle.BattleProto(warriors, turn)
176    result = {
177        'winner':  None,
178        'history': [],
179    }
180
181    try:
182        for turn in proto.battle():
183            actions = []
184            try:
185                for attacker, skname, damages in turn:
186                    actions.append({
187                        'attacker': copy.deepcopy(attacker),
188                        'skill':    copy.deepcopy(skname),
189                        'damages':  copy.deepcopy(damages),
190                    })
191            except pycodebattler.battle.DrawGame:
192                pass
193
194            result['history'].append({
195                'actions':  actions,
196                'warriors': copy.deepcopy(warriors),
197            })
198
199        result['winner'] = proto.winner()
200
201    except pycodebattler.battle.DrawGame:
202        pass
203
204    return result
205
206
207def httpdump(template, entries=[], result={}):
208    tmpl = Template(open(os.path.expanduser(template)).read())
209    tmpl.script = sys.argv[0]
210    tmpl.config = CONFIG
211    tmpl.entries = entries
212    tmpl.result = result
213    sys.stdout.write('Content-type: text/html; charset=UTF-8\r\n\r\n')
214    sys.stdout.write(tmpl.respond().encode('utf-8'))
215    sys.stdout.flush()
216
217
218def main():
219    form = cgi.FieldStorage()
220
221    if 'id' in form:
222        entries = [CharacterManager(form.getfirst('id')).flatten()]
223        return httpdump(CONFIG.get('template', 'character'), entries=entries)
224
225    if 'warrior' in form:
226        ids = form['warrior']
227        if type(ids) is list:
228            if len(ids) > CONFIG.getint('battle', 'max_entries'):
229                raise ValueError('battle warriors too long')
230            warriors = [CharacterManager(id_.value).load()[1] for id_ in ids]
231            result = do_battle(warriors)
232            return httpdump(CONFIG.get('template', 'battle'), result=result)
233
234    if 'filename' in form:
235        item = form['filename']
236        if item.file and item.filename:
237            code = item.file.read(CONFIG.getint('limit', 'max_size'))
238            if code:
239                CharacterManager.dump(item.filename, code)
240
241    CharacterManager.sweep()
242
243    entries = [cm.flatten() for cm in CharacterManager.list()]
244    return httpdump(CONFIG.get('template', 'index'), entries=entries)
245
246
247if __name__ == '__main__':
248    try:
249        main()
250    except:
251        httpdump(CONFIG.get('template', 'error'))
Note: See TracBrowser for help on using the repository browser.