其他一些小程序

落爺英雄遲暮 提交于 2020-02-12 15:08:04

1 区间数字判断

  1 import time
  2 
  3 # 计算一定区间内内的相关操作数据
  4 print('\033[1;33m================> 请输入计算区间,区间长度请勿超过3万,否则老夫的计算机...... <=====================\033[0m')
  5 start = int(input('\033[1;32m请输入计算前端区间:\033[0m').strip())
  6 end = int(input('\033[1;32m请输入计算后端区间:\033[0m').strip())
  7 while True:
  8     cho_dic = """
  9     '1':'质数、合数'
 10     '2':'偶数、奇数'
 11     '3':'完全数'
 12     '4':'斐波那契数列'
 13     'QUIT':'退出系统'
 14     """
 15     print(cho_dic)
 16     cho = input('请输入将要进行的操作代号:')
 17     # 质数、合数
 18     if cho == '1':
 19         str_time = time.time()
 20         print('正在计算中,请稍等...\n')
 21         zhi_li = []
 22         for num in range(start, end):
 23             for i in range(2, num):
 24                 if num % i == 0:
 25                     break
 26             else:
 27                 if num >= 2:
 28                     zhi_li.append(num)
 29         if start == 0 or start == 1:
 30             he_li = [i for i in range(2, end)]
 31         else:
 32             he_li = [i for i in range(start, end)]
 33         for i in zhi_li:
 34             if i in he_li:
 35                 he_li.remove(i)
 36         print('区间{0}-{1}的质数一共有{2}位,分别为:\n{3}'.format(start, end, len(zhi_li), zhi_li))
 37         print('区间{0}-{1}的合数一共有{2}位,分别为:\n{3}'.format(start, end, len(he_li), he_li))
 38         end_time = time.time()
 39         time_ac = round(end_time - str_time, 4)
 40         print('\n本次计算共耗时[%s]秒\n' % time_ac)
 41     # 偶数、奇数
 42     if cho == '2':
 43         str_time = time.time()
 44         print('正在计算中,请稍等...\n')
 45         ji_li = []
 46         ou_li = []
 47         for i in range(start, end):
 48             if i % 2 == 0:
 49                 ou_li.append(i)
 50             else:
 51                 ji_li.append(i)
 52         print('区间{0}-{1}的偶数一共有{2}位,分别为:\n{3}'.format(start, end, len(ou_li), ou_li))
 53         print('区间{0}-{1}的奇数一共有{2}位,分别为:\n{3}'.format(start, end, len(ji_li), ji_li))
 54         end_time = time.time()
 55         time_ac = round(end_time - str_time, 4)
 56         print('\n本次计算共耗时[%s]秒\n' % time_ac)
 57     # 完全数
 58     def s(aa, bb):
 59         l = []
 60         for n in range(aa, bb):
 61             s = 0
 62             for a in range(1, n):
 63                 if n % a == 0:
 64                     s = s + a
 65             if n == s:
 66                 l.append(n)
 67         return l
 68     if cho == '3':
 69         str_time = time.time()
 70         print('正在计算中,请稍等...\n')
 71         o = s(start, end)
 72         if 0 in o:
 73             o.remove(0)
 74         print('区间{0}-{1}的完全数一共有{2}位,分别为:\n{3}'.format(start, end, len(o), o))
 75         end_time = time.time()
 76         time_ac = round(end_time - str_time, 4)
 77         print('\n本次计算共耗时[%s]秒\n' % time_ac)
 78     # 斐波那契数列
 79     def feiBo():
 80         num = end - start + 1
 81         a = 0
 82         b = 1
 83         m = 0
 84         li = []
 85         while m < num:
 86             a, b = b, a + b
 87             m += 1
 88             if a >= start and a <= end:
 89                 li.append(a)
 90         return li
 91     if cho == '4':
 92         str_time = time.time()
 93         print('正在计算中,请稍等...\n')
 94         ll = feiBo()
 95         print('区间{0}-{1}的斐波那契数列一共有{2}位,分别为:\n{3}'.format(start, end, len(ll), ll))
 96         end_time = time.time()
 97         time_ac = round(end_time - str_time, 4)
 98         print('\n本次计算共耗时[%s]秒\n' % time_ac)
 99     # 退出
100     if str.upper(cho) == 'QUIT':
101         print('\n\n\033[1;33m系统退出成功...\033[0m\n\n')
102         break
View Code

2 随机图片验证码

 1 import random
 2 from PIL import Image, ImageDraw, ImageFont
 3 
 4 
 5 width = 160
 6 height = 45
 7 # 生成随机颜色
 8 def getRandomColor():
 9     r = random.randint(0, 255)
10     g = random.randint(0, 255)
11     b = random.randint(0, 255)
12     return (r, g ,b)
13 
14 
15 # 生成随机字符
16 def getRandomChar():
17     num = str(random.randint(0, 9))
18     lower = str(chr(random.randint(97, 122)))
19     upper = str(chr(random.randint(65, 90)))
20     random_char = random.choice([num, lower, upper])
21     return random_char
22 
23 
24 
25 # 干扰元素(随机点、随机线条)
26 def drawLine(draw):
27     for i in range(5):
28         x1 = random.randint(0, width)
29         x2 = random.randint(0, width)
30         y1 = random.randint(0, height)
31         y2 = random.randint(0, height)
32         draw.line((x1, y1, x2, y2), fill=getRandomColor())
33 
34 
35 
36 def drawPoint(draw):
37     for i in range(40):
38         x = random.randint(0, width)
39         y = random.randint(0, height)
40         draw.point((x, y), fill=getRandomColor())
41 
42 
43 # 最终图片生成
44 def creatImg():
45     bg_color = getRandomColor()
46     # 创建一张随机背景色图片
47     img = Image.new(mode='RGB', size=(width, height), color=bg_color)
48     # 创建图片画笔,用于描述文字
49     draw = ImageDraw.Draw(img)
50     # 修改字体
51     font = ImageFont.truetype(font='arial.ttf', size=34)
52     for i in range(5):
53         # 随机生成五种颜色和五种字符
54         random_txt = getRandomChar()
55         txt_color = getRandomColor()
56         # 保证字符颜色和背景色不一致
57         while txt_color == bg_color:
58             txt_color = getRandomColor()
59         # 根据坐标填充文字
60         draw.text((10 + 30 * i , 3), text = random_txt, fill=txt_color, font=font)
61         drawLine(draw)
62         drawPoint(draw)
63         with open('test.png', 'wb') as f:
64             img.save(f, format='png')
65 
66 
67 creatImg()
View Code

3 随机文字验证码

 

 1 import random
 2 import tkinter
 3 
 4 
 5 root = tkinter.Tk()
 6 root.geometry('400x400')
 7 root.title('SkyGrass random')
 8 root.resizable(width=False, height=False)
 9 
10 # # 随机码位数选择
11 label = tkinter.Label(root,text='请在文本框中填入操作的代号',font=('黑体',12),fg='#4F4F4F')
12 label.place(x=75, y=10, width=250, height=30)
13 label_three = tkinter.Label(root,text='1.三位数随机码',font=('黑体',13),fg='#4F4F4F')
14 label_three.place(x=10, y=60)
15 label_four = tkinter.Label(root,text='2.四位数随机码',font=('黑体',13),fg='#4F4F4F')
16 label_four.place(x=210, y=60)
17 label_five = tkinter.Label(root,text='3.五位数随机码',font=('黑体',13),fg='#4F4F4F')
18 label_five.place(x=10, y=100)
19 label_six = tkinter.Label(root,text='4.六位数随机码',font=('黑体',13),fg='#4F4F4F')
20 label_six.place(x=210, y=100)
21 label_change1 = tkinter.Label(root,text='请选择随机码位数:',font=('黑体',12),fg='#4F4F4F')
22 label_change1.place(x=10, y=140)
23 var_num = tkinter.Variable()
24 entry_1 = tkinter.Entry(root,textvariable=var_num,).place(x=155, y=140)
25 
26 # # 是否生成有字母的随机码
27 label_true = tkinter.Label(root,text='A.有字母',font=('黑体',13),fg='#4F4F4F')
28 label_true.place(x=10, y=180)
29 label_false = tkinter.Label(root,text='B.无字母',font=('黑体',13),fg='#4F4F4F')
30 label_false.place(x=210, y=180)
31 label_change2 = tkinter.Label(root,text='请选择有无字母',font=('黑体',12),fg='#4F4F4F')
32 label_change2.place(x=10, y=220)
33 var_mul = tkinter.Variable()
34 entry_2 = tkinter.Entry(root,textvariable=var_mul,).place(x=150, y=220)
35 
36 # # 运行按钮
37 but_run = tkinter.Button(root,text='生成随机码',font=('黑体',11),fg='black',bg='orange',command=lambda:Change_Random())
38 but_run.place(width=120,height=30, x=140, y=260)
39 
40 # # 结果返回界面
41 result = tkinter.Variable()
42 result.set('')
43 label_result = tkinter.Entry(root,font=('黑体',25),textvariable=result)
44 label_result.place(x=50, y=300, width=300, height=80)
45 
46 
47 
48 
49 # # 随机码生成函数
50 def Change_Random():
51     num = var_num.get()
52     mul = var_mul.get()
53     res = ''
54     nn = int(num) + 2
55     for i in range(nn):
56         if mul == 'A':
57             n = random.randint(0, 9)
58             s1 = chr(random.randint(65, 90))
59             s2 = chr(random.randint(97, 122))
60             bar = str(random.choice([n, s1, s2]))
61             res += bar
62             result.set(res)
63         elif mul == 'B':
64             n1 = random.randint(0, 9)
65             n2 = random.randint(0, 9)
66             bar = str(random.choice([n1, n2]))
67             res += bar
68             result.set(res)
69 
70 root.mainloop()
View Code

 

4 24点游戏

  1 import random
  2 
  3 func1 = []      # 存储用户数据
  4 func2 = []      # 数据全排列
  5 op2 = []        # 运算符全排列
  6 func_op2 = []   # 数据+运算符全排列
  7 result1 = []    # 加上一对括号(括两个数)的全排列
  8 result2 = []    # 加上一对括号(括三个数)的全排列
  9 result3 = []    # 加上两对括号的全排列
 10 result = []     # 最终结果输出列表
 11 result_end = []
 12 result_out = []
 13 
 14 
 15 # 产生四个随机数
 16 def randomNum():
 17     usr = []
 18     num_li = range(1, 13)
 19     usr = random.sample(num_li, 4)
 20     return usr
 21 
 22 
 23 
 24 def gameStart():
 25     # 用户输入的数字全排列并去重后存储进列表func2
 26     func1 = randomNum()
 27     func_dic = {
 28         1:'A', 2:'2', 3:'3', 4:'4', 5:'5',
 29         6:'6', 7:'7', 8:'8', 9:'9', 10:'10',
 30         11:'J', 12:'Q', 13:'K'
 31     }
 32     da = []
 33     name = ['梅花', '黑桃', '红桃', '方片']
 34     for i in func1:
 35         name_num = random.randint(0, 3)
 36         d = name[name_num] + func_dic[i]
 37         da.append(d)
 38     print('卡牌为:\n', da)
 39     for i in func1:
 40         for j in func1:
 41             for k in func1:
 42                 for l in func1:
 43                     if i != j and i != k and i!= l and j != k and j != l and k != l:
 44                         func2.append([i, j, k, l])
 45     # 运算符全排列后去重并存储进列表op2
 46     op1 = ['+', '-', '*', '/']
 47     op = []
 48     for i in op1:
 49         for j in op1:
 50             for k in op1:
 51                 if i != j and i !=j and i !=k and j != k:
 52                     op2.append([i, j ,k])
 53     # 数字+运算符全排列
 54     for num in func2:
 55         for ope in op2:
 56             # 将三个运算符插入到数字列表中
 57             num1 = num.copy()
 58             num1.insert(1, ope[0])
 59             num1.insert(3, ope[1])
 60             num1.insert(5, ope[2])
 61             func_op2.append(num1)
 62     # 加入一对括号后全排列
 63     # 括两个数的括号
 64     for i in range(0, 5, 2):
 65         for res in func_op2:
 66             res1 = res.copy()
 67             res1.insert(i, '(')
 68             res1.insert(i+4, ')')
 69             result1.append(res1)
 70     # 括三个数的括号
 71     for i in range(0, 3, 2):
 72         for res in func_op2:
 73             res2 = res.copy()
 74             res2.insert(i, '(')
 75             res2.insert(i+6, ')')
 76             result2.append(res2)
 77     # 加入两对括号的排列
 78     for res in func_op2:
 79         res3 = res.copy()
 80         res3.insert(0, '(')
 81         res3.insert(4, ')')
 82         res3.insert(6, '(')
 83         res3.insert(10, ')')
 84         result3.append(res3)
 85     # 综合整理
 86     result = result1 + result2 + result3
 87     for res in result:
 88         res = [str(i) for i in res]
 89         result_end.append(''.join(res))
 90     # 计算结果
 91     for end in result_end:
 92         try:
 93             if eval(end) == 24:
 94                 result_out.append(end)
 95         except:
 96             pass
 97     cont = len(result_out) + 1
 98     if len(result_out) == 0:
 99         print('此组卡牌无法得出24点\n请换一组卡牌再次尝试...')
100     else:
101         for i in range(cont):
102             endd = '({0}):{1} = 24'.format(i+1, result_out[i-1])
103             print(endd)
104 
105 
106 gameStart()
View Code

5 简易五子棋

 

 1 # 创建棋盘的程序
 2 def initBoard():
 3     global board  # 调用全局的board
 4     board = [None] * 16
 5     for i in range(len(board)):
 6         board[i] = ["+ "] * 16
 7 
 8 
 9 # 打印棋盘的程序
10 def printBoard():
11     global board
12     for i in range(len(board)):
13         for j in range(len(board[i])):
14             print(board[i][j], end=" ")
15         print("")
16 
17 
18 # 开始下棋的程序
19 def startGame():
20     global board
21     player = 0
22     while isGameContinue():
23         if player % 2 == 0:
24             # 黑方下棋
25             print("==>黑方下棋")
26             if not playChess("●"):
27                 continue
28         else:
29             # 白方下棋
30             print("==>白方下棋")
31             if not playChess("○"):
32                 continue
33         player += 1
34 
35 
36 def playChess(chess):
37     # 获取位置
38     x = int(input("==> X=")) - 1
39     y = int(input("==> Y=")) - 1
40     if board[x][y] == "+ ":
41         board[x][y] = chess
42         printBoard()
43         return True  # 落子成功
44     else:
45         print("==> 已有棋子 请重新落子\a")
46         printBoard()
47         return False  # 落子失败
48 
49 
50 def isGameContinue():
51     for i in range(len(board)):
52         for j in range(len(board[i])):
53             if board[i][j] != "+ ":
54                 # 横向
55                 if j <= 11:
56                     if board[i][j] == board[i][j + 1] == board[i][j + 2] == board[i][j + 3] == board[i][j + 4]:
57                         whoWin(i, j)
58                         return False
59                 # 竖向
60                 if i <= 11:
61                     if board[i][j] == board[i + 1][j] == board[i + 2][j] == board[i + 3][j] == board[i + 4][j]:
62                         whoWin(i, j)
63                         return False
64                 # 反斜
65                 if i <= 11 and j <= 11:
66                     if board[i][j] == board[i + 1][j + 1] == board[i + 2][j + 2] == board[i + 3][j + 3] == board[i + 4][
67                         j + 4]:
68                         whoWin(i, j)
69                         return False
70                 # 正斜
71                 if i >= 4 and j <= 11:
72                     if board[i][j] == board[i - 1][j + 1] == board[i - 2][j + 2] == board[i - 3][j + 3] == board[i - 4][
73                         j + 4]:
74                         whoWin(i, j)
75                         return False
76     return True
77 
78 
79 def whoWin(i, j):
80     if board[i][j] == "●":
81         print("黑方胜!")
82     else:
83         print("白方胜!")
84     for i in range(10):
85         print("\a")
86 
87 
88 board = []
89 initBoard()
90 printBoard()
91 startGame()
View Code

 

6 摇骰子猜大小

 

 1 import random
 2 
 3 
 4 # 产生随机数并且判断大小
 5 def roll_game(roll_poi=None):
 6     while True:
 7         print('\033[4;33m  The Game Is Start... \033[0m')
 8         print('\033[4;33m  You Can Enter 0 To Exit Game... \033[0m')
 9         roll = int(input('Please Enter The Number Of The Roll:\n'))
10         if roll_poi is None:
11             roll_poi = []
12         if roll == 0:
13             print('Exit Game Successful...')
14             break
15         num_li = []
16         for i in range(roll):
17             roll_num = random.randint(1, 6)
18             num_li.append(roll_num)
19         cont = 0
20         for i in num_li:
21             cont = cont + i
22         if cont > 0 and cont < roll * 3 + 1:
23             roll_poi = ['小']
24         elif cont > roll * 3 and cont < roll * 6 + 1:
25             roll_poi = ['大']
26         # 用户判断
27         usr_in = input('Please enter your chose:\n')
28         if usr_in == roll_poi[0]:
29             print('\033[0;33mThe All Numbers Is %s\033[0m' % num_li)
30             print('\033[0;34mPerfect! You Are Right!\033[0m\n\033[0;34mThe Number_Adds Is %s\033[0m' % cont)
31         elif usr_in != roll_poi[0]:
32             print('\033[0;33mThe All Numbers Is %s\033[0m' % num_li)
33             print('\033[0;31mOh...No! You Are False!\033[0m\n\033[0;31mThe Number_Adds Is %s\033[0m' % cont)
34         roll_poi.clear()
35         print('\n\n=================== PLAY AGAIN ================\n\n')
36 
37 
38 roll_game()
View Code

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!