Apscheduler 習(xí)作 打斗游戲

用Apscheduler 寫了一個(gè)打斗游戲

# -*- coding: utf-8 -*-

import random
import collections

from pytz import utc

from pymongo import MongoClient
from apscheduler.schedulers.blocking import *
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.events import *

import threading

lock = threading.Lock()


host = '127.0.0.1'
port = 27017
client = MongoClient(host, port)

jobstores = {
    'mongo': MongoDBJobStore(collection='job', database='game', client=client),
    'default': MemoryJobStore()
}
executors = {
    'default': ThreadPoolExecutor(10),
    'processpool': ProcessPoolExecutor(3)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 3
}


class Unit:
    def __init__(self,name):
        self.name = name

    def __str__(self):
        return self.name

    def after_dead(self):
        pass

    def when_init(self):
        pass


class Hero(Unit):
    '''Hero: a role of the game
    name: the name of the hero
    life: the life of the hero
    damage: damage per second
    shield: the life of shield
    '''
    def __init__(self, name, life, damage, shield, speed):
        self.name = name
        self.life0 = self.life = life
        self.damage = damage
        self.shield0 = self.shield = shield
        self.speed = speed
        self._army = None

    @staticmethod
    def fromStr(s):
        # str -> Hero
        name, life, damage, shield, speed = s.split()
        return Hero(name, int(life), int(damage), int(shield), float(speed))
    
    def hit(self, other):
        assert isinstance(other, Army)
        with lock:
            if other:
                hero = other.random()
            else:
                raise ValueError('there is no hero left in the army %s'%other)
            print('%s 攻擊 %s'%(self, hero))
            if not hero.shieldbreak():
                hero.shield -= self.damage
                if hero.shieldbreak():
                    print('%s 護(hù)盾破裂'%hero)
            else:
                hero.life -= self.damage
                if hero.isdead():
                    other -= hero
            return hero, other

    def shieldbreak(self):
        return self.shield <= 0

    def isdead(self):
        return self.life <= 0
    
    def reset(self):
        self.life = self.life0
        self.shield = self.shield0


class Army(Unit, collections.UserList):
    def __init__(self, name, heros):
        self.name = name
        self.data = heros

    def copy(self):
        import copy
        return copy.deepcopy(self)

    def random(self):
        return random.choice(self)

    @staticmethod
    def fromStr(name, s):
        # str -> Army
        heros = s.split(';')
        return Army(name, [Hero.fromStr(h) for h in heros])

    def __iadd__(self, other):
        if isinstance(other, Hero):
            self.append(other)
        else:
            self.extend(other)
        return self

    def __add__(self, other):
        cpy = self.copy()
        cpy += other
        return cpy

    def __isub__(self, other):
        if isinstance(other, Hero):
            self.remove(other)
        else:
            for h in other:
                self.remove(h)
        return self

    def __sub__(self, other):
        cpy = self.copy()
        cpy -= other
        return cpy

    @property
    def damage(self):
        return sum(hero.damage for hero in self)
 
    def isdead(self):
        return len(self) == 0



class Game(object):
    '''Game has 3 (principal) propteries
    title: title
    army1: army1
    army2: army2'''
    def __init__(self, title, army1=None, army2=None):
        self.title = title
        self.army1 = army1
        self.army2 = army2
        self._scheduler = None

    def init(self):
        # 自定義軍隊(duì)真屯,要構(gòu)造新游戲只要跟新這些字符串中的數(shù)據(jù)
        army1 = Army.fromStr('袁軍', '袁紹 500 10 100 1;顏良 200 30 30 1;文丑 200 30 30 2')
        army2 = Army.fromStr('曹軍', '曹操 800 30 200 2;荀彧 100 20 600 3;許褚 100 20 10 1')

        scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)

        for h in army1:
            scheduler.add_job(h.hit, 'interval', args=(army2,), seconds=h.speed, id=str(h))
        for h in army2:
            scheduler.add_job(h.hit, 'interval', args=(army1,), seconds=h.speed, id=str(h))

        # def check(army1, army2):
        #     if army1.isdead() or army2.isdead():
        #         scheduler.shutdown()
        # scheduler.add_job(check, 'interval', args=(army1, army2), seconds=5, id='check')

        def rmjob(evt):
            # remove a job
            hero, army = evt.retval
            if hero:
                if hero.isdead():
                    scheduler.remove_job(str(hero))
                    print('%s 陣亡'%hero)
                else:
                    print('%s 還剩余生命值 %d'%(hero, hero.life))
                if army.isdead():
                    try:
                        scheduler.shutdown()
                    except RuntimeError:
                        print('%s 全軍覆沒'%army)

        scheduler.add_listener(rmjob, EVENT_JOB_EXECUTED)
        self._scheduler = scheduler


    def start(self):
        try:
            self._scheduler.start()
        except ValueError as v:
            print(v)
        finally:
            client.close()


if __name__ =="__main__":

    threeKingdoms = Game('官渡之戰(zhàn):東漢末年三大戰(zhàn)役之一')
    threeKingdoms.init()
    threeKingdoms.start()
    ```

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末阅懦,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌烈掠,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件胰默,死亡現(xiàn)場(chǎng)離奇詭異粱栖,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)扩灯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門媚赖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人珠插,你說我怎么就攤上這事惧磺。” “怎么了丧失?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵豺妓,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我布讹,道長(zhǎng)琳拭,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任描验,我火速辦了婚禮白嘁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘膘流。我一直安慰自己絮缅,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布呼股。 她就那樣靜靜地躺著耕魄,像睡著了一般。 火紅的嫁衣襯著肌膚如雪彭谁。 梳的紋絲不亂的頭發(fā)上吸奴,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼则奥。 笑死考润,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的读处。 我是一名探鬼主播糊治,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼罚舱!你這毒婦竟也來了井辜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤馆匿,失蹤者是張志新(化名)和其女友劉穎抑胎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體渐北,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡阿逃,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了赃蛛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片恃锉。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖呕臂,靈堂內(nèi)的尸體忽然破棺而出破托,到底是詐尸還是另有隱情,我是刑警寧澤歧蒋,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布土砂,位于F島的核電站,受9級(jí)特大地震影響谜洽,放射性物質(zhì)發(fā)生泄漏萝映。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一阐虚、第九天 我趴在偏房一處隱蔽的房頂上張望序臂。 院中可真熱鬧,春花似錦实束、人聲如沸奥秆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)构订。三九已至,卻和暖如春避矢,著一層夾襖步出監(jiān)牢的瞬間鲫咽,已是汗流浹背签赃。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工谷异, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留分尸,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓歹嘹,卻偏偏與公主長(zhǎng)得像箩绍,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子尺上,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 開篇語(yǔ) 聲明:本文來自Wuxia World 材蛛,我看到了,所以想要分享給更多人怎抛,這不是剽竊卑吭,我都注明了出處的~ 正...
    張照博閱讀 6,818評(píng)論 7 10
  • “守株待兔”的故事大家都知道豆赏,農(nóng)夫?yàn)榱伺既坏脕淼囊恢煌米樱瑏G下種田這個(gè)主業(yè)富稻,每天蹲守樹樁等一只千年不遇撞上樹樁的兔...
    羽宙兒閱讀 364評(píng)論 7 6
  • 那天回家掷邦,已經(jīng)有點(diǎn)晚了,照例買了幾個(gè)橙子椭赋,提在手中沉甸甸的抚岗,和此時(shí)平靜的心情有些不同。 公司的燈早已熄滅哪怔,只余下那...
    一只鹿笑亭閱讀 301評(píng)論 0 2
  • 一宣蔚、 “喂!過來认境∨呶” “唔…又要做這個(gè)啊元暴?”妻子面露苦色篷扩。 “那當(dāng)然,不做完這個(gè)怎么能讓你出門茉盏?”可我態(tài)度堅(jiān)決鉴未。 ...
    小新心心鑫鑫閱讀 1,029評(píng)論 0 1