0 Fundamentals python-3.6 Improve our game based on the modular structure

Source: Internet
Author: User

Look back at our game:

#建立游戏的核心玩法类class core (object): version=1.0 def guessnum (self): Try:secret=random.randint (1,100) #生 Random number #print (secret) time=6# guess number of times guess=0# input number minnum=0# minimum random number Max num=100# Max random number print ("---------Welcome to the place where you guessed the numbers, start---------") Print ("Hint: enter-1 can exit the game at any time") while Gu Ess!=secret and time>=0: #条件 guess=int (Input ("* Number range 0-100, please enter your guess number:")) Print ("You enter the number is:", gues s) if Guess==secret:return (7-time) #为什么是7, because the condition above us is 0-6, so it is 7 times print (                "Guess right, really good") elif Guess==-1:print ("Hint: you forcibly quit, this time do not record results") return ' exit '                        else: #当不等于的时候, you also need to print out the appropriate intervals to make it easier for users to use if Guess<secret:                                If minnum<guess:minnum=guess print ("Hint: your guess number is less than the correct answer")    Print ("Hint: the correct number range is:", Minnum, "-", Maxnum) else:if maxnum>guess: Maxnum=guess print ("Hint: your guess is greater than the correct answer") Print ("Hint: the correct number range is:", MI        Nnum, "-", Maxnum) print ("Too sorry, you guessed wrong, you have", Time, "chance") guess=0 Time-=1 Except TypeError as E:print ("You entered the wrong, the result is void") return ' exit ' except ValueError as E:p Rint ("You entered the wrong, the result is void") Return ' Exit ' class User (object): Username= "" #用户名 resultdict={} #结果列表 PLA Ytime=1# played by Def Setusername (self,name= ' Ray '): Self.username=name def setresultdict (self,guesstime): s Elf.resultdict[self.playtime]=guesstime self.playtime+=1 #下面是运行代码, Java-like main function import Randomimport datetimeexit alltag=0# record whether all exit the game, 1: Exit exitgametag=0# record whether to exit the Personal games section, 1: Exit userdict={} #记录用户组数据result = ' #猜数字游戏返回的结果 # processing logic: #1. Enter a name first, If you are not exiting, you can go directly to Game # #. The process of playing, you can always play, can also be strongBack, strong return did not score # # #. When the user finishes the game, record the results of the user # #. Cable all of the user exits, print all the scores while exitalltag!=1:username=input ("Please enter your name:") #设置用户的名字 User=u    Ser () user.setusername (userName) exitgametag=0 if username== ' exit ': Exitalltag=1 break;            else: #进行游戏 while Exitgametag!=1:result=core (). Guessnum () #这里存在性能问题, preferably using singleton mode If result== ' exit ': Exitgametag=1 #当用户退出时, record the score Userdict[username]=user.                Resultdict; Break Else: #设置用户的结果 user.setresultdict (Result) for E in User.resu    Ltdict:print (E,user.resultdict[e]) print ("Game Over") #输出所有人的成绩for name in Userdict:print ("User's name:" +name) For E in Userdict[name]: print (e,userdict[name][e]) try:handler=open ("Results.txt", ' W ') for name in Userdi Ct:now = Now.strftime ("%y-%m-%d%h:%m:%s") Handler.write ("Recorded Time:" +now) handler.write ("User's name:" +name) for E in Userdict[name]: Handler.write (e) handler.write (Userdict[name][e]) handler.close () except IOError as E:print (e)

Areas of Improvement:

1. Encapsulate the print score as a function

2. Encapsulation of persistence results into functions

3. Add a document string where the class and function are, making it clearer

' guessnum.py--guess number game ' Import Randomimport time# build the game's core gameplay class core (object): ' Core--core class ' version=1.0 def guessnum            (self): ' Guessnum--guess digital Core method ' Try:secret=random.randint (1,100) #生成随机数 #print (Secret) time=6# guess number of times guess=0# input number minnum=0# minimum random number maxnum=100# max random number print ("                ---------Welcome to the place where you guessed the numbers, start---------") Print (" Hint: input-1 can exit the game at any time ") while Guess!=secret and time>=0: #条件 Guess=int (Input ("* Number range 0-100, please enter your guess number:")) Print ("You enter the number is:", guess) if GUESS==SECR Et:return (7-time) #为什么是7, because the condition above us is 0-6, so it is 7 times print ("guessed right, really good") elif g                    Uess==-1:print ("Hint: you forcibly quit, this time do not record results") return ' exit ' else:                            #当不等于的时候, you also need to print out the appropriate intervals to make it easier for users to use if Guess<secret:if minnum<guess:Minnum=guess print ("Hint: your guess is less than the correct answer") Print ("Hint: the correct number range is:", Minnum,                        "-", Maxnum) else:if maxnum>guess:maxnum=guess                    Print ("Hint: your guess is greater than the correct answer") Print ("Hint: the correct number range is:", Minnum, "-", Maxnum)            Print ("Too sorry, you guessed wrong, you still have", Time, "chance") guess=0 time-=1 except TypeError as E:            Print (e) print ("You entered the wrong, the result is void") return ' exit ' except ValueError as E:print (e)    Print ("You entered the wrong, the result is void") Return ' Exit ' class User (object): ' User--record the subscriber data ' username= ' #用户名 resultdict={} #结果列表 playtime=1# played def setusername (Self,name= ' Ray '): Self.username=name def SETRESULTDI     CT (self,guesstime): Self.resultdict[self.playtime]=guesstime self.playtime+=1 def printresults (userDict): ' Printresults--Output allPerson's score ' for Name ' in Userdict:print ("User's name:" +name) for E in Userdict[name]: print (E,userdict[nam E][e]) def persistresults (filename,userdict): ' Persistence score ' try:handler=open (FileName, ' W ') for name in UserD Ict:now = Time.strftime ("%y-%m-%d%h:%m:%s") Handler.write ("Recorded Time:" +now) Handler.write (" User's name: "+name) for E in Userdict[name]: Handler.write (e) handler.write (Userdict[na Me][e]) handler.close () except IOError as E:print (e) if __name__== ' __main__ ': ' Below is the main program ' Exitallt ag=0# record whether all exit the game, 1: Exit exitgametag=0# record whether to exit the Personal games section, 1: Exit userdict={} #记录用户组数据 result= ' #猜数字游戏返回的结果 #处理逻辑: #1. Enter first Name, if not exit, can go directly into the game #2. The process of the game, you can always play, you can also strong back, strong back #3. When you finish the game, record the results of your user #4. Cable all of the clients are out and print all the scores while exitalltag!=1 : Username=input ("Please enter your name:") #设置用户的名字 User=user () user.setusername (userName) Exitgam etag=0 if Username== ' exit ': Exitalltag=1 break; else: #进行游戏 while Exitgametag!=1:result=core (). Guessnum () #这里存在性能问题, preferably using a single                    Example mode if result== ' exit ': Exitgametag=1 #当用户退出时, record your scores.                    Userdict[username]=user.resultdict; Break Else: #设置用户的结果 user.setresultdict (Result) fo R e in User.resultDict:print (E,user.resultdict[e]) print ("Game Over") #输出所有人的成绩 printresults (U    SERDICT); #持久化成绩 persistresults ("Results.txt", userdict);





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

0 Fundamentals python-3.6 Improve our game based on the modular structure

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.