zoukankan      html  css  js  c++  java
  • python学习(四)五数连珠

    中午有段时间,模仿《五子连珠》写了一段代码,运行截图如下:

    import random      # for random.randrange()
    import os          # for input()
    
    ballColorNum = 7  # 7 colors
    padRowNum = 10    # chesspad have 10 rows
    padColNum = 10    # chesspad have 10 cols
    
    chPad = []        # save chesspad state
    threeBall = []    # generate 3 balls one time 
    
    class ball():
        def __init__(self):
            self.color = random.randrange(1,ballColorNum)
            self.x = random.randrange(0,padRowNum)
            self.y = random.randrange(0,padColNum)
        
    # initial chesspad state, all 0, 10*10
    def chesspad_init():
        chPad = [[0 for x in range(10)] for x in range(10)]
        return chPad
        
    def chesspad_update(chPad, ball):
        chPad[ball.x][ball.y] = ball.color
        return chPad
    
    def chesspad_flash(chPad):
        for i in range(10):
            print('- ', end=' ')
        print('
    ')
        for i in range(len(chPad)):
            for c in chPad[i]:
                print('33[1;%dm%d '%(30+c,c),end=' ')
            print('
    ')
        for i in range(10):
            print('- ', end=' ')
        print('
    ')
    
    def countNull(chPad):
        n = 0
        for i in range(len(chPad)):
            for j in range(len(chPad[i])):
                if chPad[i][j] == 0:
                    n += 1
        return n    
    
    # move a ball from x1,y1 to x2,y2
    def move_from_XY1_to_XY2():
        pass
    
    def calculate_Score():
        pass
    
    def auto_eliminate():
        pass
    
        
    def main():
        print('
    -------------------GAME------------------
    ')
        pad = chesspad_init()
        while 1:
            n = 1
            while 1:
                b = ball()
                if pad[b.x][b.y] == 0:
                    print('Ball%d:(%d,%d:%c)'%(n, b.x, b.y, b.color),end=' ')
                    pad = chesspad_update(pad, b)
                    if countNull(pad) == 0:
                        print("
    
    GAME OVER!")
                        exit()
                    n += 1
                if n > 3:
                    break            
            print('
    ')
            chesspad_flash(pad)    
            
            if input('MoveTo:(x1,y1)(x2,y2)=>'):
                pass
                
            chesspad_flash(pad)                
    
    if __name__=='__main__':
        main()
        

    这里的chesspad_flash()函数参考了《python在linux中输出带颜色的文字的方法》,其他没有什么技巧可言。随机函数random.randrange(),需要random模块支持。用os模块中的input()函数,表现“按回车键继续.....”的效果。

    下一步,还有三个函数没写。想好再说吧!:)

  • 相关阅读:
    FTP 协议和 HTTP 协议的比较
    HttpURLConnection的post请求,什么时候发出,writeData存在什么地方
    装饰器
    函数参数以及名称空间作用域
    函数的调用
    函数的返回值
    定义函数的三种方式
    函数
    day05
    day04
  • 原文地址:https://www.cnblogs.com/py520ziyi/p/5567125.html
Copyright © 2011-2022 走看看