文件结构:
[root@xmdevops xmdevops_limanman]# tree |grep -v ".pyc"
|-- main.py 主文件
|-- CommonPyutils.py 通用方法
|-- GameRoleControl.py 角色操作类
|-- GameSceneControl.py 场景控制类
|-- GameUserControl.py 用户注册类
|-- GameLockDatabase.pkl 帐号锁定数据库
|-- GameUserDatabase.pkl 账户管理数据库
原文数据:
John and Liz是高中同学时的恋人,后来Liz考上了北京城市学院,而Jhon没有,为了跟女朋友在一起
他来到了北京打工(一家网吧当网管),挣钱为Liz交学费,后来LIZ毕业后工作了,遇到了公司的高富帅
Peter,然后两人就苟且在了一起,John发现后非常伤心,发誓要把LIZ夺回来,然后他发粪学习,增加
自身能力,参加自考,学习老男孩Python,若干年后,当上了某大型互联网公司的IT总监,月薪5万,北京
买了车和房,偶然又见到了LIZ,此时她已被高富Peter甩了,LIZ提出再回到JHON身边时,JHONE说...
具体要求:
1. 用PYTHON面向对象编写模拟人生屌丝逆袭的故事~
代码流程:
代码实现:
/xm-workspace/xm-pyss/auto_python/xmdevops_limanman/main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://my.oschina.net/pydevops/ # Purpose: # """ import os import sys import time import pprint from CommonPyutils import pkl_load_dump from GameUserControl import (UserControl) from GameSceneControl import (SceneControl) from GameRoleControl import (BaseRole, RoleControl) # 引导精灵 def game_guidespeak(message, with_guid=True): """Game guid. Args: message : guid message. with_guid: wither with guider Returns: None """ if with_guid: print 'manbao: %s' % message else: print message # 游戏背景 def game_showbanner(): print u'''游戏背景: John and Liz是高中同学时的恋人,后来Liz考上了北京城市学院,而Jhon没有,为了跟女朋友在一起 他来到了北京打工(一家网吧当网管),挣钱为Liz交学费,后来LIZ毕业后工作了,遇到了公司的高富帅 Peter,然后两人就苟且在了一起,John发现后非常伤心,发誓要把LIZ夺回来,然后他发粪学习,增加 自身能力,参加自考,学习老男孩Python,若干年后,当上了某大型互联网公司的IT总监,月薪5万,北京 买了车和房,偶然又见到了LIZ,此时她已被高富Peter甩了,LIZ提出再回到JHON身边时,JHONE说... ''' # 画矩形盒 def grame_drawbox(box_width, menu_list): """Draw a game box with menu list. Args: box_width : menu box width menu_list : menu list with choice Returns: None """ side_sta_width = 5 side_end_width = side_sta_width + box_width print ''.join([' '*(side_sta_width-1), '-'*box_width]) for cur_index, cur_item in enumerate(menu_list,start=0): cur_menu_item = '%s. %s' % (cur_index, cur_item) print '|'.join([' '*(side_sta_width-1), cur_menu_item.ljust(box_width-side_sta_width, ' ')]), print '|' print ''.join([' '*(side_sta_width-1), '-'*box_width]) # 首页选择 def login_select(menu_list): """Login menu select. Args: menu_list: login menu list Returns: bool """ while True: grame_drawbox(75 ,menu_list) login_choice = raw_input('please input mb choice: ') if login_choice not in map(str, range(len(menu_list))): print 'errors: valid login choice number. try again.' continue if login_choice == '0': # 用户注册 uc_control.register_verification() continue elif login_choice == '1': # 登陆游戏(返回用户ID) user_hash = uc_control.login_verification() if user_hash: return user_hash continue else: # 退出游戏 sys.exit('notice: %s quit game at %s' % (None, None)) # 登入选择 def roles_select(user_hash, menu_list): """Roles select. Args: menu_list: roles Returns: bool """ # 开始角色相关 role_name = uc_control.user_pkl_db[user_hash]['username'] role_data = uc_control.user_pkl_db[user_hash]['useroles'] baserole = BaseRole(role_name) rolecontrol = RoleControl(baserole) while True: grame_drawbox(75 ,menu_list) select_choice = raw_input('please input mb choice: ') if select_choice not in map(str, range(len(menu_list))): print 'errors: valid login choice number. try again.' continue if select_choice == '0': select_id = rolecontrol.role_add(role_name, role_data) continue elif select_choice == '1': select_id = rolecontrol.role_select(role_name, role_data) if select_id: return select_id continue elif select_choice == '2': rolecontrol.role_delete(role_name, role_data) continue elif select_choice == '3': return False # 场景相关 def scene_select(user_hash, role_id, menu_list): """Game scene select. Args: user_hash: user hash role_id : role id menu_list: menu list Returns: bool """ scenecontrol = SceneControl(user_hash, role_id, uc_control.user_pkl_db) while True: grame_drawbox(75 ,menu_list) scene_choice = raw_input('please input mb choice: ') if scene_choice not in map(str, range(len(menu_list))): print 'errors: valid login choice number. try again.' continue if scene_choice == '0': res = scenecontrol.scene_studyskill() if not res: continue elif scene_choice == '1': scenecontrol.scene_changework() continue elif scene_choice == '2': # 简单交朋友(细节略) scenecontrol.scene_makefriend('Liz') continue elif scene_choice == '3': scenecontrol.scene_makemoney() continue elif scene_choice == '4': scenecontrol.scene_printinfo() continue elif scene_choice == '5': pkl_load_dump(pkl_user_file, 'dump', uc_control.user_pkl_db) return True def main(): """Main function. """ game_showbanner() game_guidespeak(u'''免责声明: 欢迎到ManBao模拟人生游戏平台,请遵守游戏规则,未成年人请在成年人监护下进行游戏!''', False) game_guidespeak(u'''正在载入....''', False) time.sleep(2) # 开始登陆相关 user_hash = login_select(login_menu) if not user_hash: return False select_id = roles_select(user_hash ,roctl_menu) if not select_id: return False print "notice: welcome %s's %s role login game scene." % (user_hash, select_id) # 开始场景相关 scene_select(user_hash, select_id, works_menu) if __name__ == '__main__': login_menu = [u'注册帐号', u'登陆游戏', u'退出游戏'] roctl_menu = [u'创建角色', u'选择角色', u'删除角色', u'重新登陆'] works_menu = [u'学习技能', u'换个工作', u'交个朋友', u'努力赚钱', u'查看信息', u'保存进度'] pkl_user_file = os.path.join(os.getcwd(), 'GameUserDatabase.pkl') pkl_lock_file = os.path.join(os.getcwd(), 'GameLockDatabase.pkl') # 用户控制 uc_control = UserControl(pkl_user_file, pkl_lock_file) main()
/xm-workspace/xm-pyss/auto_python/xmdevops_limanman/CommonPyutils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://my.oschina.net/pydevops/ # Purpose: # """ import cPickle def pkl_load_dump(pkl_file, pkl_type, pkl_data=None): """ Args: pkl_file: pickle source file pkl_type: pickle type pkl_data: pickle source data Returns: None/dict """ if pkl_type == 'load': with open(pkl_file, 'r+b') as rhandler: try: return cPickle.load(rhandler) except EOFError as eof_err: print 'errors: first load %s, content is empty.' % pkl_file return {} if pkl_type == 'dump': with open(pkl_file, 'w+b') as whandler: cPickle.dump(pkl_data, whandler) if __name__ == '__main__': pass
/xm-workspace/xm-pyss/auto_python/xmdevops_limanman/GameRoleControl.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://my.oschina.net/pydevops/ # Purpose: # """ import os import pprint class BaseRole(object): """ Attributes: role_age : role age role_sex : role sex role_name : role name role_salary: role salary role_assets: role assets girl_friend: role girl friend current_job: role current job """ def __init__(self, role_name): self.role_num = 0 self.role_age = None self.role_salary = 0 self.role_assets = 0 self.girl_friend = None self.current_job = None self.role_sex = None self.role_name = role_name class RoleControl(object): """ Attributes: baserole: base role object """ def __init__(self, baserole): self.baserole = baserole def __is_created(self, role_num, role_datadb): """Game role is created? Args: user_hash : user hash role_datadb: role datadb Returns: bool """ if role_datadb.has_key(role_num): return True return False # 添加角色(每个用户最多创建3个角色) def role_add(self, role_name, role_datadb): role_num = self.baserole.role_num if len(role_datadb) > 3: print 'errors: up to three characters peer user.' return False if self._RoleControl__is_created(role_num, role_datadb): print 'errors: role %s has been registed.' % (role_name) return False # 免输入验证 role_age = raw_input('please input your age: ').strip() role_sex = raw_input('please input your sex: ').strip() self.baserole.role_age = role_age self.baserole.role_sex = role_sex # 更新数据库 role_datadb.update({ str(role_num): self.baserole }) self.baserole.role_num += 1 return self.baserole.role_num-1 # 输出角色信息 def role_print(self, role_name, role_datadb): """Print all role info. Args: role_datadb: role database Returns: str """ for cur_index, cur_item in enumerate(role_datadb): print "user %s's role %s info:" % (role_name, cur_index) print u''' 角色名字: %s 角色性别: %s 角色年龄: %s 角色工资: %s 角色存款: %s 角色朋友: %s 角色工作: %s ''' % (getattr(self.baserole, 'role_name', None), getattr(self.baserole, 'role_sex', None), getattr(self.baserole, 'role_age', None), getattr(self.baserole, 'role_salary', None), getattr(self.baserole, 'role_assets', None), getattr(self.baserole, 'girl_friend', None), getattr(self.baserole, 'current_job', None)) # 删除角色信息 def role_delete(self, role_name, role_datadb): """Delete role info. Args: role_name : role name role_database: role database Returns: bool """ self.role_print(role_name, role_datadb) # 下拉选择 role_num = raw_input('please input role number: ') if not role_datadb.has_key(role_num): print "errors: user %s have not the role %s." % (role_name, role_num) return False return role_datadb.pop(role_num) # 选择角色 def role_select(self, role_name, role_datadb): """Select game role. Args: role_datadb: role database Returns: int """ if len(role_datadb) == 0: print 'errors: no roles in database to select.' return False self.role_print(role_name, role_datadb) select_id = raw_input('please input select id: ').strip() # 下拉框选择 if not select_id in role_datadb: print 'errors: selected invalid id, select again.' return False return select_id if __name__ == '__main__': pass
/xm-workspace/xm-pyss/auto_python/xmdevops_limanman/GameSceneControl.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://my.oschina.net/pydevops/ # Purpose: # """ import pprint from CommonPyutils import pkl_load_dump class SceneControl(object): """ Attributes: user_hash : user hash role_id : role_datadb: role database """ work_menu = [u'LINUX 运维 - 5000', u'PYTHON开发 - 6000', u'JAVA 开发 - 10000', u'基础 网管 - 3500'] def __init__(self, user_hash, role_id, role_datadb): self.role_id = role_id self.user_hash = user_hash self.role_datadb = role_datadb @staticmethod def scene_showmenu(menu_list): """Show scene menu. Args: menu_list: menu list Returns: None """ for cur_index, cur_item in enumerate(menu_list): print '''\ %s. %s''' % (cur_index, cur_item) @staticmethod def split_money(work_choice, work_menu): """Split cursors and money. Args: work_item: work item. Returns: tuple """ work_tuples = work_menu[work_choice].split('-') current_job = work_tuples[0].strip() role_salary = int(work_tuples[-1].strip()) return work_choice, current_job, role_salary # 学习技能 def scene_studyskill(self): assets = self.role_datadb[self.user_hash]['useroles'][self.role_id].role_assets if assets < 6000: print 'errors: you have no enouth money to study, work first.' return False while True: self.scene_showmenu(self.work_menu) study_choice = raw_input('please input work choice: ') if study_choice not in map(str, range(len(self.work_menu))): print 'errors: invalid work select id, try again.' continue study_choice = int(study_choice) wid, stu, mny = self.split_money(study_choice, self.work_menu) break self.role_datadb[self.user_hash]['useroles'][self.role_id].role_assets -= mny assets = self.role_datadb[self.user_hash]['useroles'][self.role_id].role_assets print 'notice: you success learnd %s cursor, cost %s money, superplus %s money.' % (stu, mny, assets) return wid, stu, mny # 换个工作 def scene_changework(self): # 零时选择 while True: self.scene_showmenu(self.work_menu) work_choice = raw_input('please input work choice: ') if work_choice not in map(str, range(len(self.work_menu))): print 'errors: invalid work select id, try again.' continue work_choice = int(work_choice) wid, job, mny = self.split_money(work_choice, self.work_menu) self.role_datadb[self.user_hash]['useroles'][self.role_id].current_job = job self.role_datadb[self.user_hash]['useroles'][self.role_id].role_salary = mny print 'notice: you success change your work %s and %s money every month' % (job, mny) return wid, job, mny # 交个朋友 def scene_makefriend(self, firend): # 交朋友化钱略 self.role_datadb[self.user_hash]['useroles'][self.role_id].girl_friend = firend print 'notice: you success make firend with %s.' % (firend) # 努力赚钱 def scene_makemoney(self, ): job = self.role_datadb[self.user_hash]['useroles'][self.role_id].current_job if not job: print 'errors: you have not job for make money, get a job first.' return False # 已经有工作了 salary = self.role_datadb[self.user_hash]['useroles'][self.role_id].role_salary self.role_datadb[self.user_hash]['useroles'][self.role_id].role_assets += salary assets = self.role_datadb[self.user_hash]['useroles'][self.role_id].role_assets print 'notice: you make %d money, your total money is %s.' % (salary, assets) # 查看信息 def scene_printinfo(self): game_role = self.role_datadb[self.user_hash]['useroles'][self.role_id] print u''' 角色名字: %s 角色性别: %s 角色年龄: %s 角色工资: %s 角色存款: %s 角色朋友: %s 角色工作: %s ''' % (getattr(game_role, 'role_name', None), getattr(game_role, 'role_sex', None), getattr(game_role, 'role_age', None), getattr(game_role, 'role_salary', None), getattr(game_role, 'role_assets', None), getattr(game_role, 'girl_friend', None), getattr(game_role, 'current_job', None)) if __name__ == '__main__': pass
/xm-workspace/xm-pyss/auto_python/xmdevops_limanman/GameUserControl.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://my.oschina.net/pydevops/ # Purpose: # """ import os import random import pprint import string import hashlib import traceback from CommonPyutils import pkl_load_dump # 回调写入用户文件 def called_userdb_back(func): """Write user pickle data back to file. """ def wrapper(self, *args): user_hash = func(self, *args) if user_hash: pkl_load_dump(self.user_pkfile, 'dump', self.user_pkl_db) return user_hash else: return False return wrapper # 回调写入锁定文件 def called_lockdb_back(func): """Write user pickle data back to file. """ def wrapper(self, *args): user_hash = func(self, *args) if not user_hash: pkl_load_dump(self.user_lkfile, 'dump', self.user_lck_db) return False else: return user_hash return wrapper class UserControl(object): """ Attributes: user_pkfile: user login database file user_lkfile: user lock database file """ # 加载用户数据 def __init__(self, user_pkfile, user_lkfile): self.user_pkfile = user_pkfile self.user_lkfile = user_lkfile self.user_pkl_db = pkl_load_dump(self.user_pkfile, 'load') self.user_lck_db = pkl_load_dump(self.user_pkfile, 'load') # 生成加密key @staticmethod def generate_keys(user_name): """Generate user_name of md5. Args: user_name: user name that registed Returns: str """ md5 = hashlib.md5() md5.update(user_name) try: hash(user_name) except TypeError: return False return md5.hexdigest() # 用户是否注册 def __is_registed(self, user_name): """ Args: user_name: registed user name Returns: bool """ user_hash = self.generate_keys(user_name) if not user_hash: print 'errors: user name %s is not valid.' % (user_name) return False if self.user_pkl_db.has_key(user_hash): return True else: return False # 注册新的用户 def user_register(self, user_name, user_pass): """User register. Args: user_name: user name for register user_pass: user name for register Returns: bool """ if self._UserControl__is_registed(user_name): print 'errors: user name %s has been registed.' % (user_name) return False user_hash = self.generate_keys(user_name) self.user_pkl_db.update({ user_hash: { 'username': user_name, 'userpass': user_pass, 'useroles': {} } }) print ('notice: registed success,' 'keep in mind account and pass (%s, %s).') % (user_name, user_pass) return user_hash # 模拟数据来源 @called_userdb_back def register_verification(self): while True: user_name = raw_input('please input user name: ') user_pass = raw_input('please input user pass: ') user_hash = self.user_register(user_name, user_pass) if not user_hash: return False else: return user_hash # 用户登陆验证 def user_login(self, user_name, user_pass): """User login verification. Args: user_name: user name for verification user_pass: user pass for verification Returns: bool """ if not self._UserControl__is_registed(user_name): print 'errors: user %s has not been registed.' % (user_name) return False user_hash = self.generate_keys(user_name) if not user_pass == self.user_pkl_db[user_hash]['userpass']: print 'errors: user %s with wrong password.' % (user_name) return False else: return user_hash # 模拟数据来源 @called_lockdb_back def login_verification(self): retry_count = 3 retry_set = set() while retry_count > 0: user_name = raw_input('please input user name: ') user_pass = raw_input('please input user pass: ') user_hash = self.generate_keys(user_name) # 用户不存在直接返回 if not self._UserControl__is_registed(user_name): print 'errors: user %s have not been registed.' % (user_name) return False # 登陆成功返回用户ID if self.user_login(user_name, user_pass): print 'notice: welcome user %s to login.' % (user_name) return user_hash retry_set.add(user_hash) retry_count -= 1 else: if len(retry_set) == 1: self.user_lck_db.update({ user_hash: { 'username': user_name, 'userpass': user_pass, 'useroles': {} } }) print 'notice: user %s wrong pass 3 times, locked.' % (user_name) return False if __name__ == '__main__': pass
有图有像: