基本信息
源码名称:Python开发的24点游戏实例下载
源码大小:4.66KB
文件格式:.rar
开发语言:Python
更新时间:2013-01-08
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

用Python做的24点游戏


#!/usr/bin/env python
#--coding:utf-8--

import string,time,argparse,math
import traceback
from multiprocessing import Process, Lock,Pool

__author__="CHANG Tiangen"
__date__="20121102"
__copyright__="Copyright 2012, a game for fun"
__license__="GPL"
__version__="0.1"
__email__="changtiangen@gmail.com"
__status__="Prototype"
__credits__=[]

def create_help_parser():
      epilog_string="Any bug is welcome reported to changtiangen@gmail.com"
      description_string='The programe is going to caculate whether the line integer vector  in the data file can obtain 24 by combination of \' \',\'-\',\'*\',\'/\'.'
      parser = argparse.ArgumentParser(description=description_string,epilog=epilog_string)
      parser.add_argument('-f', '--file', dest='fnIn', help='input file name.', required=True)
      parser.add_argument('-o', '--output', dest='fnOut', help='output file name, default is pointSol.txt',default='pointSol.txt')
      parser.add_argument('-p','--Process Number',type=int,dest='process_number',required=True,help='Input the process number need for the programme, no default.')
      op=parser.parse_args()
      return op

def makeDictionary(rawData=[]):
    '''
    make a dictionary for raw input data [a,b,c,...], the dictionary is like[('a',a),('b',b),('c',c),...]
    '''
    Data=zip(map(str,rawData),rawData)    
    return Data

def rerange(dataForRerange=[]):
    '''
    rerange the dictionaried data, i.e. the full permutation of the data
    '''
    rerangedData=[]
    for i in range(len(dataForRerange)): 
        for j in range(i 1,len(dataForRerange)):
            tempData=dataForRerange[:]            
            tempData[0],tempData[i]=tempData[i],tempData[0]
            tempData[1],tempData[j]=tempData[j],tempData[1]
            if tempData not in rerangedData:
                rerangedData.append(tempData)
    return rerangedData
    

def calculate(data=[]):
    '''
    calculate the " , - ,*,/" result between data[0][1] and data[1][1] and replace data[0],data[1] with it. 
    '''
    result=[]
    temp=[('(' data[0][0] ' ' data[1][0] ')',data[0][1] data[1][1])] data[2:]
    if temp not in result:
        result.append(temp)
    temp=[('(' data[0][0] '*' data[1][0] ')',data[0][1]*data[1][1])] data[2:]
    if temp not in result:
        result.append(temp)    
    if (data[1][1]>0.00001)|(data[1][1]<-0.00001) :
        temp=[('(' data[0][0] '/' data[1][0] ')',float(data[0][1])/data[1][1])] data[2:]
        if temp not in result:
            result.append(temp)
    if (data[0][1]>0.00001)|(data[0][1]<-0.00001) :
        temp=[('(' data[1][0] '/' data[0][0] ')',float(data[1][1])/data[0][1])] data[2:]
        if temp not in result:
            result.append(temp)         
    if data[0][1]>=data[1][1]:
        temp=[('(' data[0][0] '-' data[1][0] ')',data[0][1]-data[1][1])] data[2:]
        if temp not in result:
            result.append(temp)
    else:
        temp=[('(' data[1][0] '-' data[0][0] ')',data[1][1]-data[0][1])] data[2:]
        if temp not in result:
            result.append(temp)         
    return result

def findSolution(final=[]):
    '''
    if result equals to 24, is a solution
    '''
    solution=[]
    if (final[0][1]<=24.0001)&(final[0][1]>=23.9999):
        solution=final[0][0]
    if len(solution)>0:
        return solution

def merge(lineStr='',pool=0,fileOut='output.txt'):
    '''
    merge all the function above and write the final result to file
    '''
    solution=open(fileOut,'a')
    solution.write(lineStr ':' '\n')
    p=Pool(pool)#multiprocessing
    row = lineStr.split()       
    rowData=map(string.atoi,row)# turn string element in row to int type
    Data=makeDictionary(rawData=rowData)
    Data=[Data]
    if len(Data)>0:
        while len(Data[0])>1:#if len(Data[0])=1, that means we get the final result of all permutation, e.g. Data[0]=['(((a b)-c)/d)',(((a b)-c)/d))]
            CalculateData=map(rerange,Data)
            CalculateData=[j for i in CalculateData for j in i]#reduce the dimension of 'CalculateData'
            result=p.map(calculate,CalculateData)
            Data=[j for i in result for j in i ]
        if len(Data[0])==1:
            rawSolution=p.map(findSolution,Data)
        rawSolution=list(set(rawSolution))#delete the identical pattern in raw solution
        for i in range(len(rawSolution)):            
            if rawSolution[i]!=None:                
                solution.write(rawSolution[i] '\n')#write result to file
        solution.close()

    
def main_process():
    '''
    function for all the progress
    '''
    op=create_help_parser()
    tempF=open(op.fnOut,'w')
    tempF.close()#remove all the exist data in the output file
    allData=open(op.fnIn,'r')
    for line in allData:
        line=line.strip()
        Process(target=merge,args=(line,op.process_number,op.fnOut)).start()

if __name__=='__main__':
      start_time=time.clock()
      main_process()
      elapsed=time.clock()-start_time
      print "The process is done"
      print "Time used:",elapsed