Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import art
- import random
- import time
- from enum import IntEnum
- class GameState (IntEnum):
- NOT_STARTED = -1
- PLAY_HIGHER = 1
- PLAY_LOWER = 2
- FINISHED = 3
- #class GameState
- #guess_number.py
- """
- The computer randomly picks a number from
- some range 1..10K
- A human player will try to guess the number
- picked by the computer
- It will be a guided process, allowing some
- rational playing
- score
- ++++++++++++++++++++++++ = amplitude
- ------------------------ = attempts, time
- """
- class GuessTheNumberGame:
- def __init__ (
- self,
- pMin=1,
- pMax=10000
- ):
- self.mMin = pMin
- self.mMax = pMax
- self.mStart = None
- self.mEnd = None
- #self.mAttempts = 0
- #historic of the played numbers
- #QUEU => FIFO => First In First Out
- self.mListOfPlays = []
- #self.mListOfAttempts = list()
- #historic of the times (in seconds) when the numbers were played
- self.mListOfPlaySeconds = []
- #this is the number that the human player must guess
- self.mGuessMe = random.randint(
- self.mMin,
- self.mMax
- )
- self.mState = GameState.NOT_STARTED
- #def __init__
- def __str__(self):
- strAll = ""
- strAll+="min: %d ; max: %d ; guessMe: %d\n"
- strAll+="plays: %s ; time (seconds): %s\n"
- strAll+="state: %s\n"
- strAll = strAll%(
- self.mMin, self.mMax, self.mGuessMe,
- self.mListOfPlays.__str__(),
- self.mListOfPlaySeconds.__str__(),
- self.mState.__str__()
- )
- return strAll
- #def __str__
- #assuming FIFO for plays
- def getHumanPlayerLastPlay(self):
- #return self.mListOfAttempts[len(self.mListOfAttempts)-1]
- if (len(self.mListOfPlays)>0):
- return self.mListOfPlays[-1]
- else:
- return None
- #def getHumanPlayerLastPlay
- def getNumberOfAttempts(self):
- return len(self.mListOfPlays)
- #def getNumberOfAttempts
- def play(self, piPlayerNumber):
- bCanPlay = self.mState!=GameState.FINISHED
- if (bCanPlay):
- bFirstPlay = len(self.mListOfPlays)==0
- if (bFirstPlay):
- self.mStart = time.time()
- #if
- iHowManySecondsSinceStart = time.time()-self.mStart
- self.mListOfPlays.append(piPlayerNumber)
- self.mListOfPlaySeconds.append(iHowManySecondsSinceStart)
- if(piPlayerNumber < self.mGuessMe):
- # suggest PLAY HIGHER
- self.mState = GameState.PLAY_HIGHER
- pass
- elif (piPlayerNumber > self.mGuessMe):
- #suggest PLAY LOWER
- self.mState = GameState.PLAY_LOWER
- pass
- else:
- #congratulations
- self.mState = GameState.FINISHED
- self.mEnd = time.time()
- strFeedback = self.feedback()
- print (strFeedback)
- #if can play
- else: #could not play, but played
- #TODO
- pass
- #def play
- def feedback(self):
- strF = self.__str__()+"\n"
- if (self.mState==GameState.NOT_STARTED):
- pass
- elif (self.mState==GameState.PLAY_HIGHER):
- strF+=\
- "Your number %d is LOWER than mine, play HIGHER"\
- %(self.getHumanPlayerLastPlay())
- elif (self.mState==GameState.PLAY_LOWER):
- strF += \
- "Your number %d is HIGHER than mine, play LOWER" \
- % (self.getHumanPlayerLastPlay())
- else:
- #congratulations
- strF += art.text2art("Congratulations!!")
- pass
- #if
- strF+="\n"+("-"*40)
- return strF
- #def feedback
- def gameFinished(self):
- return self.mState==GameState.FINISHED
- #def
- #class GuessTheNumberGame
- #g1.instructions()
- g1 = GuessTheNumberGame(1, 5000)
- #print (g1)
- while (not g1.gameFinished()):
- g1.play(int(input("Your number: ")))
- #while
- import matplotlib.pyplot as plt
- x = g1.mListOfPlays
- y = g1.mListOfPlaySeconds
- plt.plot(x, y)
- plt.show()
- ***************************************
- #mylist.py
- class MyList:
- #dunder double underscore
- BATATA = "batata frita"
- #initializer of instances of the MyList datatype
- def __init__(
- self,
- pValues = None
- ):
- if (pValues is None):
- self.mList = []
- else:
- self.mList = pValues
- #def __init__
- #how instances of type MyList should be
- #represented as string
- def __str__(self):
- strAll = ""
- strAll+=self.mList.__str__()
- return strAll
- #def __str__
- #dynamic
- def min (self):
- theSmallest = None
- for v in self.mList:
- if (theSmallest is None):
- theSmallest = v
- else:
- if (v<theSmallest):
- theSmallest = v
- #if
- #else
- #for
- return theSmallest
- #def min
- def max(self):
- theGreatest = None
- for v in self.mList:
- if (theGreatest is None):
- theGreatest = v
- else:
- if(v>theGreatest):
- theGreatest = v
- #if
- #else
- #for
- return theGreatest
- #def max
- def howManyValues(self):
- return len(self.mList)
- #def howManyValues
- #mean / average / média
- def mean (self):
- howMany = self.howManyValues()
- if (howMany>0):
- theSum = 0
- for v in self.mList:
- #theSum = theSum+v
- #cumulative sum +=
- theSum+=v
- #for
- theMean = theSum / howMany
- return theMean
- else:
- return None
- #def mean
- """
- p1 p2 p3 ... pn
- pM
- sum = (p1-pM)^2 + (p2-pM)^2 + (p3-pM)^2 ... (pn-pM)^2
- sum/howMany
- """
- def variance(self):
- howMany = self.howManyValues()
- theMean = self.mean()
- theSum = 0
- if (howMany>0 and (theMean!=None)):
- for v in self.mList:
- diff = v-theMean
- diffSquared = diff**2
- theSum += diffSquared
- #for
- theVariance = theSum / howMany
- return theVariance
- else:
- return None
- #def variance
- #stdevp = sqrt(variance)
- #stdevp = variance ** (1/2)
- def standardDeviation(self):
- if (self.howManyValues()>0):
- #return self.variance()**(1/2)
- variance = self.variance()
- squareRoot = variance**(1/2)
- return squareRoot
- else:
- return None
- #else
- #def standardDeviation
- """
- example:
- working on list [10, 20, 40, 40]
- set([10, 20, 40, 40]) --> [10, 20, 40]
- working over a collection without repetitions...
- set
- the return should be this dictionary:
- {10:1, 20:1, 40:2}
- """
- def absoluteFrequencyOfElements(self):
- retDict = {}
- if (self.howManyValues()>0):
- setWithoutRepitions = set(self.mList) #[10, 20, 40] #optimization => does not question repeated elements
- #for v in self.mList: #[10, 20, 40, 40] #would count 40 twice
- for v in setWithoutRepitions:
- iCount = self.count(v)
- retDict[v] = iCount
- #retDict[v] = self.count(v)
- #for
- return retDict
- else:
- return None
- #def absoluteFrequencyOfElements
- def count(self, pEl):
- bShouldWork = self.howManyValues() and \
- pEl!=None
- if (bShouldWork):
- iCounter = 0
- for v in self.mList:
- if (pEl==v):
- iCounter+=1
- #if
- #for
- return iCounter
- else:
- return 0
- #def count
- def mostFrequentValues (self):
- #dictionary of absolute frequencies
- daf = self.absoluteFrequencyOfElements()
- if (daf!=None):
- theKeys = daf.keys()
- theGreatest = None
- for k in theKeys:
- v = daf[k]
- if (theGreatest is None):
- theGreatest = v
- else:
- if (v>theGreatest):
- theGreatest = v
- #if
- #else
- #for
- #what do I have?????
- #in var theGreatest we capture the most
- #frequent value in the collection (self.mList)
- listMode = []
- for k in theKeys:
- if (daf[k]==theGreatest):
- listMode.append(k)
- #if
- #for
- return listMode
- else:
- return None
- #def mostFrequentValues
- #TPC: leastFrequentValues
- def mode(self):
- return self.mostFrequentValues()
- #def
- def add(self, pEl):
- self.mList.append(pEl)
- #@head?
- def removeHead(self):
- removedElement = None
- if (len(self.mList)>0):
- removedElement = self.mList[0]
- self.mList = self.mList[1:]
- return removedElement
- # @head?
- def removeHead(self):
- removedElement = None
- if (len(self.mList) > 0):
- removedElement = self.mList[0]
- self.mList = self.mList[1:]
- return removedElement
- #def removeHead
- # @tail?
- def removeTail(self):
- removedElement = None
- if (len(self.mList) > 0):
- removedElement = self.mList[-1]
- #[start:end-exclusive]
- self.mList = self.mList[0:-1]
- return removedElement
- #def removeTail
- #class MyList
- l1 = MyList()
- l2 = MyList([10, 20, 30])
- smallestInL1 = l1.min()
- greatestInL2 = l2.max()
- print ("l1: ", l1)
- print ("l2: ", l2)
- print ("smallest in l1: ", smallestInL1)
- print ("greatest in l2: ", greatestInL2)
- print ("How many elements in l1: ",
- l1.howManyValues()
- )
- print ("How many elements in l2: ",
- l2.howManyValues()
- )
- theMeanL1 = l1.mean()
- theMeanL2 = l2.mean()
- print ("The mean of l1: ", theMeanL1)
- print ("The mean of l2: ", theMeanL2)
- l3 = MyList([20, 20, 40, 40, 50, 50, 50])
- v3 = l3.variance()
- dp3 = l3.standardDeviation()
- print("The variance of {} is {}".format(l3, v3))
- print("The standard deviation of {} is {}".\
- format(l3, dp3))
- daf = l3.absoluteFrequencyOfElements()
- print (daf)
- theModeList = l3.mode()
- print ("The mode (as a list) for {} is {}".\
- format(l3, theModeList))
- l2 = MyList()
- l44 = MyList([44, 44, 44])
- l2.mode()
- l44.mode()
- #the left-operand is NOT an instance of the class
- #but the class's name
- print(MyList.BATATA) #static
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement