具有多种功能的组装软件

这是将最近学习的Python内容组合到一个程序中,具有画图,看天气,玩游戏的功能,最后一个画图部分具有选择方向和控制旋转角度的功能.
# 开发时间: 2021/10/8 10:04
# 开发人:张鹏翔
# 功能:
import easygui as g

g.msgbox(msg='欢迎使用!!!' , title='你好!',ok_button='OK')
g.buttonbox(msg='今天的心情如何?',title='心情选择',choices=('一般',
            '还好','不错','很好'   ))
g.msgbox(msg='明天还需继续努力',title='自动回复',ok_button='Ok')
choice=g.buttonbox(msg='请选择你需要的服务内容:',title='模式选择',choices=('看天气',
            '玩游戏','看图画'      ))
if choice=='看天气':
    from tkinter import *
    import urllib.request
    import gzip
    import json
    from tkinter import messagebox
    root = Tk()
    def main():
        # 输入窗口
        root.title('天气查询')  # 窗口标题
        Label(root, text='请输入城市').grid(row=0, column=0)  # 设置标签并调整位置
        enter = Entry(root)  # 输入框
        enter.grid(row=0, column=1, padx=20, pady=20)  # 调整位置
        enter.delete(0, END)  # 清空输入框
        enter.insert(0, '齐齐哈尔')  # 设置默认文本
        # enter_text = enter.get()#获取输入框的内容
        running = 1
        def get_weather_data():  # 获取网站数据
            city_name = enter.get()  # 获取输入框的内容
            url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name)
            url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
            # 网址1只需要输入城市名,网址2需要输入城市代码
            # print(url1)
            weather_data = urllib.request.urlopen(url1).read()
            # 读取网页数据
            weather_data = gzip.decompress(weather_data).decode('utf-8')
            # 解压网页数据
            weather_dict = json.loads(weather_data)
            # 将json数据转换为dict数据
            if weather_dict.get('desc') == 'invilad-citykey':
                print(messagebox.askokcancel("xing", "你输入的城市名有误,或者天气中心未收录你所在城市"))
            else:
                # print(messagebox.askokcancel('xing','bingguo'))
                show_data(weather_dict, city_name)
        def show_data(weather_dict, city_name):  # 显示数据
            forecast = weather_dict.get('data').get('forecast')  # 获取数据块
            root1 = Tk()  # 副窗口
            root1.geometry('650x280')  # 修改窗口大小
            root1.title(city_name + '天气状况')  # 副窗口标题
            # 设置日期列表
            for i in range(5):  # 将每一天的数据放入列表中
                LANGS = [(forecast[i].get('date'), '日期'),
                         (forecast[i].get('fengxiang'), '风向'),
                         (str(forecast[i].get('fengji')), '风级'),
                         (forecast[i].get('high'), '最高温'),
                         (forecast[i].get('low'), '最低温'),
                         (forecast[i].get('type'), '天气')]
                group = LabelFrame(root1, text='天气状况', padx=0, pady=0)  # 框架
                group.pack(padx=11, pady=0, side=LEFT)  # 放置框架
                for lang, value in LANGS:  # 将数据放入框架中
                    c = Label(group, text=value + ': ' + lang)
                    c.pack(anchor=W)
            Label(root1, text='今日' + weather_dict.get('data').get('ganmao'),
                  fg='green').place(x=40, y=20, height=40)  # 温馨提示

            Button(root1, text='确认并退出', width=10, command=root1.quit).place(x=500, y=230, width=80, height=40)  # 退出按钮
            root1.mainloop()
        # 布置按键
        Button(root, text="确认", width=10, command=get_weather_data) \
            .grid(row=3, column=0, sticky=W, padx=10, pady=5)
        Button(root, text='退出', width=10, command=root.quit) \
            .grid(row=3, column=1, sticky=E, padx=10, pady=5)
        if running == 1:
            root.mainloop()
    if __name__ == '__main__':
        main()
elif choice=='玩游戏':
    choice1=g.buttonbox(msg='选择要玩的游戏:',title='游戏选择',choices=('俄罗斯方块','2048','猜字游戏','贪吃蛇'))
    if choice1=='俄罗斯方块':
        from tkinter import *
        import random
        import time
        import tkinter.messagebox

        # 俄罗斯方块界面的高度
        HEIGHT = 20

        # 俄罗斯方块界面的宽度
        WIDTH = 10
        ACTIVE = 1
        PASSIVE = 0
        TRUE = 1
        FALSE = 0

        style = [
            [[(0, 0), (0, 1), (1, 1), (2, 1)], [(1, 0), (1, 1), (1, 2), (0, 2)], [(0, 1), (1, 1), (2, 1), (2, 2)],
             [(1, 0), (2, 0), (1, 1), (1, 2)]],  # j
            [[(1, 0), (1, 1), (1, 2), (2, 1)], [(1, 0), (0, 1), (1, 1), (2, 1)], [(1, 0), (1, 1), (1, 2), (0, 1)],
             [(0, 1), (1, 1), (2, 1), (1, 2)]],  # T
            [[(0, 1), (1, 1), (2, 1), (2, 0)], [(0, 0), (1, 0), (1, 1), (1, 2)], [(0, 1), (1, 1), (2, 1), (0, 2)],
             [(1, 0), (1, 1), (1, 2), (2, 2)]],  # 反L
            [[(0, 0), (0, 1), (1, 1), (1, 2)], [(2, 1), (1, 1), (1, 2), (0, 2)], [(0, 0), (0, 1), (1, 1), (1, 2)],
             [(2, 1), (1, 1), (1, 2), (0, 2)]],  # Z
            [[(1, 0), (1, 1), (0, 1), (0, 2)], [(0, 1), (1, 1), (1, 2), (2, 2)], [(1, 0), (1, 1), (0, 1), (0, 2)],
             [(0, 1), (1, 1), (1, 2), (2, 2)]],  # 反Z
            [[(0, 0), (0, 1), (1, 1), (1, 0)], [(0, 0), (0, 1), (1, 1), (1, 0)], [(0, 0), (0, 1), (1, 1), (1, 0)],
             [(0, 0), (0, 1), (1, 1), (1, 0)]],  # 田
            [[(1, 0), (1, 1), (1, 2), (1, 3)], [(0, 1), (1, 1), (2, 1), (3, 1)], [(1, 0), (1, 1), (1, 2), (1, 3)],
             [(0, 1), (1, 1), (2, 1), (3, 1)]]  # 长条
        ]

        root = Tk();
        root.title('俄罗斯方块')

        class App(Frame):
            def __init__(self, master):
                Frame.__init__(self)
                master.bind('<Up>', self.Up)
                master.bind('<Left>', self.Left)
                master.bind('<Right>', self.Right)
                master.bind('<Down>', self.Down)

                master.bind('<space>', self.Space)
                master.bind('<Control-Shift-Key-F12>', self.Play)
                master.bind('<Key-P>', self.Pause)
                master.bind('<Key-S>', self.StartByS)

                # rgb颜色值
                self.backg = "#%02x%02x%02x" % (36, 222, 82)  # 大背景
                self.frontg = "#%02x%02x%02x" % (40, 120, 150)  # 下一个形状颜色
                self.nextg = "#%02x%02x%02x" % (0, 255, 255)  # 小背景
                self.flashg = "#%02x%02x%02x" % (222, 36, 92)  # 炸的颜色

                self.LineDisplay = Label(master, text='Lines: ', bg='white', fg='red')
                self.Line = Label(master, text='0', bg='white', fg='red')
                self.ScoreDisplay = Label(master, text='Score: ', bg='white', fg='red')
                self.Score = Label(master, text='0', bg='white', fg='red')
                self.SpendTimeDisplay = Label(master, text='Time: ', bg='white', fg='red')
                self.SpendTime = Label(master, text='0.0', bg='white', fg='red')

                self.LineDisplay.grid(row=HEIGHT - 2, column=WIDTH, columnspan=2)
                self.Line.grid(row=HEIGHT - 2, column=WIDTH + 2, columnspan=3)
                self.ScoreDisplay.grid(row=HEIGHT - 1, column=WIDTH, columnspan=2)
                self.Score.grid(row=HEIGHT - 1, column=WIDTH + 2, columnspan=3)
                self.SpendTimeDisplay.grid(row=HEIGHT - 4, column=WIDTH, columnspan=2)
                self.SpendTime.grid(row=HEIGHT - 4, column=WIDTH + 2, columnspan=3)

                self.TotalTime = 0.0
                self.TotalLine = 0
                self.TotalScore = 0

                # 游戏结束
                self.isgameover = FALSE
                # 暂停
                self.isPause = FALSE
                # 开始
                self.isStart = FALSE
                self.NextList = []  # 整个小背景
                self.NextRowList = []  # 一行小背景

                self.px = 0
                self.py = 0  # 记录方块参考点

                # 渲染小背景
                r = 0;
                c = 0
                for k in range(4 * 4):
                    LN = Label(master, text='    ', bg=str(self.nextg), fg='white', relief=FLAT, bd=3)
                    LN.grid(row=r, column=WIDTH + c, sticky=N + E + S + W)
                    self.NextRowList.append(LN)
                    c = c + 1
                    if c >= 4:
                        r = r + 1;
                        c = 0
                        self.NextList.append(self.NextRowList)
                        self.NextRowList = []

                # 渲染大背景
                self.BlockList = []
                self.BlockRowList = []
                self.LabelList = []
                self.LabelRowList = []
                row = 0;
                col = 0
                for i in range(HEIGHT * WIDTH):
                    L = Label(master, text='    ', bg=str(self.backg), fg='white', relief=FLAT, bd=4)
                    L.grid(row=row, column=col, sticky=N + E + S + W)
                    L.row = row;
                    L.col = col;
                    L.isactive = PASSIVE
                    self.BlockRowList.append(0);  # 大背景每个格子初始化为0值
                    self.LabelRowList.append(L)
                    col = col + 1
                    if col >= WIDTH:
                        row = row + 1;
                        col = 0
                        self.BlockList.append(self.BlockRowList)
                        self.LabelList.append(self.LabelRowList)
                        self.BlockRowList = []
                        self.LabelRowList = []

                # file
                fw = open('text.txt', 'a')
                fw.close()
                hasHead = FALSE
                f = open('text.txt', 'r')
                if f.read(5) == 'score':
                    hasHead = TRUE
                f.close()
                self.file = open('text.txt', 'a')
                if hasHead == FALSE:
                    self.file.write('score    line    time    scorePtime    linePtime    scorePline    date/n')
                    self.file.flush()

                self.time = 1000
                self.OnTimer()

            def __del__(self):
                # self.file.close()
                pass

            def Pause(self, event):
                self.isPause = 1 - self.isPause

            def Up(self, event):
                BL = self.BlockList  # 格子的值
                LL = self.LabelList  # 格子Label

                Moveable = TRUE  # 是否可旋转

                # 代码编写开始
                nowStyle = style[self.xnow][(self.ynow)]
                newStyle = style[self.xnow][(self.ynow + 1) % 4]  # 算出下一俄罗斯方块
                self.ynow = (self.ynow + 1) % 4  # 此行代码非常重要,否则响应UP时,只能变第一次

                print("nowStyle:" + str(nowStyle) + "=====>>newStyle:" + str(newStyle))

                # 根据现有形状中每个label的坐标计算出旋转后目标坐标(x,y)
                SourceList = [];
                DestList = []

                for i in range(4):
                    SourceList.append([nowStyle[i][0] + self.px, nowStyle[i][1] + self.py])
                    x = newStyle[i][0] + self.px
                    y = newStyle[i][1] + self.py
                    DestList.append([x, y])

                    if x < 0 or x >= HEIGHT or y < 0 or y >= WIDTH:  # or BL[x][y]==1 or LL[x][y].isactive==PASSIVE
                        Moveable = FALSE

                if Moveable == TRUE:
                    for i in range(len(SourceList)):
                        self.Empty(SourceList[i][0], SourceList[i][1])
                    for i in range(len(DestList)):
                        self.Fill(DestList[i][0], DestList[i][1])

            def Left(self, event):
                BL = self.BlockList;
                LL = self.LabelList
                Moveable = TRUE
                for i in range(HEIGHT):
                    for j in range(WIDTH):
                        if LL[i][j].isactive == ACTIVE and j - 1 < 0: Moveable = FALSE
                        if LL[i][j].isactive == ACTIVE and j - 1 >= 0 and BL[i][j - 1] == 1 and LL[i][
                            j - 1].isactive == PASSIVE: Moveable = FALSE
                if Moveable == TRUE:
                    self.py -= 1
                    for i in range(HEIGHT):
                        for j in range(WIDTH):
                            if j - 1 >= 0 and LL[i][j].isactive == ACTIVE and BL[i][j - 1] == 0:
                                self.Fill(i, j - 1);
                                self.Empty(i, j)

            def Right(self, event):
                BL = self.BlockList;
                LL = self.LabelList
                Moveable = TRUE
                for i in range(HEIGHT):
                    for j in range(WIDTH):
                        if LL[i][j].isactive == ACTIVE and j + 1 >= WIDTH: Moveable = FALSE
                        if LL[i][j].isactive == ACTIVE and j + 1 < WIDTH and BL[i][j + 1] == 1 and LL[i][
                            j + 1].isactive == PASSIVE: Moveable = FALSE
                if Moveable == TRUE:
                    self.py += 1
                    for i in range(HEIGHT - 1, -1, -1):
                        for j in range(WIDTH - 1, -1, -1):
                            if j + 1 < WIDTH and LL[i][j].isactive == ACTIVE and BL[i][j + 1] == 0:
                                self.Fill(i, j + 1);
                                self.Empty(i, j)

            def Down(self, event):
                BL = self.BlockList;
                LL = self.LabelList
                Moveable = TRUE
                for i in range(HEIGHT):
                    for j in range(WIDTH):
                        if LL[i][j].isactive == ACTIVE and i + 1 >= HEIGHT: Moveable = FALSE
                        if LL[i][j].isactive == ACTIVE and i + 1 < HEIGHT and BL[i + 1][j] == 1 and LL[i + 1][
                            j].isactive == PASSIVE: Moveable = FALSE
                if Moveable == TRUE and self.isStart:
                    self.px += 1
                    for i in range(HEIGHT - 1, -1, -1):
                        for j in range(WIDTH - 1, -1, -1):
                            if i + 1 < HEIGHT and LL[i][j].isactive == ACTIVE and BL[i + 1][j] == 0:
                                self.Fill(i + 1, j);
                                self.Empty(i, j);
                if Moveable == FALSE:
                    for i in range(HEIGHT):
                        for j in range(WIDTH):
                            LL[i][j].isactive = PASSIVE
                    self.JudgeLineFill()
                    self.Start()
                    if self.isgameover == TRUE: showinfo('T_T', 'The game is over!');self.Distroy();return FALSE
                    for i in range(4):
                        for j in range(4):
                            self.NextEmpty(i, j)
                    self.Rnd()
                return Moveable

            def Space(self, event):
                while 1:
                    if self.Down(0) == FALSE: break

            def OnTimer(self):
                if self.isStart == TRUE and self.isPause == FALSE:
                    self.TotalTime = self.TotalTime + float(self.time) / 1000
                    self.SpendTime.config(text=str(self.TotalTime))

                if self.isPause == FALSE:
                    self.Down(0)
                if self.TotalScore >= 1000: self.time = 900
                if self.TotalScore >= 2000: self.time = 750
                if self.TotalScore >= 3000: self.time = 600
                if self.TotalScore >= 4000: self.time = 400
                self.after(self.time, self.OnTimer)  # 随着分数增大,俄罗斯方块下降速度加快

            def JudgeLineFill(self):
                BL = self.BlockList;
                LL = self.LabelList
                count = 0;
                LineList = []
                for i in range(WIDTH): LineList.append(1)
                # display flash
                for i in range(HEIGHT):
                    if BL[i] == LineList:
                        count = count + 1
                        for k in range(WIDTH):
                            LL[i][k].config(bg=str(self.flashg))
                            LL[i][k].update()
                if count != 0: self.after(100)
                # delete block
                for i in range(HEIGHT):
                    if BL[i] == LineList:
                        # count=count+1
                        for j in range(i, 0, -1):
                            for k in range(WIDTH):
                                BL[j][k] = BL[j - 1][k]
                                LL[j][k]['relief'] = LL[j - 1][k].cget('relief')
                                LL[j][k]['bg'] = LL[j - 1][k].cget('bg')
                        for l in range(WIDTH):
                            BL[0][l] = 0
                            LL[0][l].config(relief=FLAT, bg=str(self.backg))
                self.TotalLine = self.TotalLine + count
                if count == 1: self.TotalScore = self.TotalScore + 1 * WIDTH
                if count == 2: self.TotalScore = self.TotalScore + 3 * WIDTH
                if count == 3: self.TotalScore = self.TotalScore + 6 * WIDTH
                if count == 4: self.TotalScore = self.TotalScore + 10 * WIDTH
                self.Line.config(text=str(self.TotalLine))
                self.Score.config(text=str(self.TotalScore))

            def Fill(self, i, j):
                if j < 0: return
                if self.BlockList[i][j] == 1: self.isgameover = TRUE
                self.BlockList[i][j] = 1
                self.LabelList[i][j].isactive = ACTIVE
                self.LabelList[i][j].config(relief=RAISED, bg=str(self.frontg))

            def Empty(self, i, j):
                self.BlockList[i][j] = 0
                self.LabelList[i][j].isactive = PASSIVE
                self.LabelList[i][j].config(relief=FLAT, bg=str(self.backg))

            def Play(self, event):
                showinfo('Made in China', '^_^')

            def NextFill(self, i, j):
                self.NextList[i][j].config(relief=RAISED, bg=str(self.frontg))

            def NextEmpty(self, i, j):
                self.NextList[i][j].config(relief=FLAT, bg=str(self.nextg))

            def Distroy(self):
                # save
                if self.TotalScore != 0:
                    # cehkongfu
                    savestr = '%-9u%-8u%-8.2f%-14.2f%-13.2f%-14.2f%s/n' % (
                        self.TotalScore, self.TotalLine, self.TotalTime
                        , self.TotalScore / self.TotalTime
                        , self.TotalLine / self.TotalTime
                        , float(self.TotalScore) / self.TotalLine
                        , time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
                    self.file.seek(0, 2)
                    self.file.write(savestr)
                    self.file.flush()

                for i in range(HEIGHT):
                    for j in range(WIDTH):
                        self.Empty(i, j)
                self.TotalLine = 0;
                self.TotalScore = 0;
                self.TotalTime = 0.0
                self.Line.config(text=str(self.TotalLine))
                self.Score.config(text=str(self.TotalScore))
                self.SpendTime.config(text=str(self.TotalTime))
                self.isgameover = FALSE
                self.isStart = FALSE
                self.time = 1000
                for i in range(4):
                    for j in range(4):
                        self.NextEmpty(i, j)

            # 游戏开始方块
            def Start(self):
                nextStyle = style[self.x][self.y]  # 下一形状
                self.xnow = self.x
                self.ynow = self.y  # 记录大背景中的方块
                self.py = random.randint(0, 6)
                print("给py赋任意值:" + str(self.py))
                self.px = 0
                for ii in range(4):
                    self.Fill(int(nextStyle[ii][0]), int(nextStyle[ii][1]) + self.py)
                self.isStart = TRUE  # 游戏开始

            # 预处理方块
            def Rnd(self):
                self.x = random.randint(0, 6)
                self.y = random.randint(0, 3)
                nextStyle = style[self.x][self.y]  # 下一形状
                for ii in range(4):
                    self.NextFill(int(nextStyle[ii][0]), int(nextStyle[ii][1]))

            # 游戏开始给出一次任意形状的方块
            def RndFirst(self):
                self.x = random.randint(0, 6)  # 选择第一个方块style
                self.y = random.randint(0, 3)

            def Show(self):
                self.file.seek(0)
                strHeadLine = self.file.readline()
                dictLine = {}
                strTotalLine = ''
                for OneLine in self.file.readlines():
                    temp = int(OneLine[:5])
                    dictLine[temp] = OneLine

                list = sorted(dictLine.items(), key=lambda d: d[0])
                ii = 0
                for onerecord in reversed(list):
                    ii = ii + 1
                    if ii < 11:
                        strTotalLine += onerecord[1]
                showinfo('Ranking', strHeadLine + strTotalLine)

            def StartByS(self, event):
                self.RndFirst()
                self.Start()
                self.Rnd()

        def Start():
            app.RndFirst()
            app.Start()
            app.Rnd()

        def End():
            app.Distroy()

        def Set():
            print("设置功能待完善...")

        def Show():
            app.Show()

        # 主菜单
        mainmenu = Menu(root)
        root['menu'] = mainmenu

        # 二级菜单:game
        gamemenu = Menu(mainmenu)
        mainmenu.add_cascade(label='游戏', menu=gamemenu)
        gamemenu.add_command(label='开始', command=Start)
        gamemenu.add_command(label='结束', command=End)
        gamemenu.add_separator()
        gamemenu.add_command(label='退出', command=root.quit)

        # 二级菜单:set
        setmenu = Menu(mainmenu)
        mainmenu.add_cascade(label='设置', menu=setmenu)
        setmenu.add_command(label='设置', command=Set)

        # 二级菜单:show
        showmenu = Menu(mainmenu)
        mainmenu.add_cascade(label='展示', menu=showmenu)
        showmenu.add_command(label='展示', command=Show)

        # 绑定功能
        app = App(root)
        # 程序入口
        root.mainloop()
    elif choice1=='2048':
        import random, pygame, sys
        from pygame.locals import *
        from random import randint
        import copy
        import math

        # 定义窗口大小和其他大小
        FPS = 5
        WINDOWWIDTH = 640  # 宽度
        WINDOWHEIGHT = 640  # 高度
        boxsize = min(WINDOWWIDTH, WINDOWHEIGHT) // 4;  # 大小  平均分为
        margin = 5  # 边缘
        thickness = 0  # 线条粗细
        # 定义所使用的的各种颜色的RGP
        WHITE = (255, 255, 255)
        BLACK = (0, 0, 0)
        RED = (255, 0, 0)
        GREEN = (0, 255, 0)
        DARKGREEN = (0, 155, 0)
        DARKGRAY = (40, 40, 40)
        LIGHTSALMON = (255, 160, 122)
        ORANGE = (221, 118, 7)
        LIGHTORANGE = (227, 155, 78)
        CORAL = (255, 127, 80)
        BLUE = (0, 0, 255)
        LIGHTBLUE = (0, 0, 150)
        colorback = (189, 174, 158)
        colorblank = (205, 193, 180)
        colorlight = (249, 246, 242)
        colordark = (119, 110, 101)

        fontSize = [100, 85, 70, 55, 40]  # 字体大小

        dictcolor1 = {
            0: colorblank,
            2: (238, 228, 218),
            4: (237, 224, 200),
            8: (242, 177, 121),
            16: (245, 149, 99),
            32: (246, 124, 95),
            64: (246, 95, 59),
            128: (237, 207, 114),
            256: (237, 204, 97),
            512: (237, 200, 80),
            1024: (237, 197, 63),
            2048: (237, 194, 46),
            4096: (237, 190, 30),
            8192: (239, 180, 25)}

        dictcolor2 = {
            2: colordark,
            4: colordark,
            8: colorlight,
            16: colorlight,
            32: colorlight,
            64: colorlight,
            128: colorlight,
            256: colorlight,
            512: colorlight,
            1024: colorlight,
            2048: colorlight,
            4096: colorlight,
            8192: colorlight}
        BGCOLOR = LIGHTORANGE  # 设置背景颜色
        UP = 'up'
        DOWN = 'down'
        LEFT = 'left'
        RIGHT = 'right'

        TABLE = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

        def main():
            global FPSCLOCK, screen, BASICFONT

            pygame.init()
            FPSCLOCK = pygame.time.Clock()
            screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
            BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
            pygame.display.set_caption('2048 2.0')  # 屏幕标题

            showStartScreen()

            while True:
                runGame(TABLE)
                gameOver()

        def createButton(text, x, y, width, height, action=None):
            mouse = pygame.mouse.get_pos()  # 返回鼠标的当前位置
            click = pygame.mouse.get_pressed()  # 获取所有被按下的键值,对应的就是键是否被按下
            if x + width > mouse[0] > x and y + height > mouse[1] > y:
                pygame.draw.rect(screen, LIGHTBLUE, (x, y, width, height))  # 绘制矩形
                if click[0] == 1 and action != None:
                    action()
            else:
                pygame.draw.rect(screen, BLUE, (x, y, width, height))

            smallText = pygame.font.Font('freesansbold.ttf', 50)  # 设置字体
            # render(text(文本内容), antialias(抗锯齿), color(RGB)),返回文字对象
            TextSurf = smallText.render(text, True, WHITE)
            # 设置文字矩形对象位置
            TextRect = TextSurf.get_rect()
            TextRect.center = ((x + (width / 2)), (y + (height / 2)))
            # 在指定位置绘制指定文字对象
            screen.blit(TextSurf, TextRect)

        def showStartScreen():
            # 启动屏幕
            titleFont = pygame.font.Font('freesansbold.ttf', 100)  # 标题字体
            titleSurf1 = titleFont.render('2048', True, WHITE, ORANGE)

            while True:
                screen.fill(BGCOLOR)
                display_rect = pygame.transform.rotate(titleSurf1, 0)  # 旋转图像
                rectangle = display_rect.get_rect()
                rectangle.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 8)
                screen.blit(display_rect, rectangle)

                createButton("Run game", 80, 180, 480, 80, newGame)
                createButton("scores", 80, 340, 480, 80, leaderboard)
                createButton("quit", 80, 500, 480, 80, terminate)

                if checkForKeyPress():
                    pygame.event.get()
                    return
                pygame.display.update()
                FPSCLOCK.tick(FPS)

        def newGame():
            runGame(TABLE)

        def randomfill(TABLE):
            # 找到没有数字的位置 并进行随机填充
            flatTABLE = sum(TABLE, [])
            if 0 not in flatTABLE:
                return TABLE
            empty = False
            w = 0
            while not empty:
                w = randint(0, 15)
                if TABLE[w // 4][w % 4] == 0:
                    empty = True
            z = randint(1, 5)
            if z == 5:
                TABLE[w // 4][w % 4] = 4
            else:
                TABLE[w // 4][w % 4] = 2
            return TABLE

        def gameOver(TABLE):
            # 如果一个框为空或者只有两个框可以合并 返回False
            x = [-1, 0, 1, 0]
            y = [0, 1, 0, -1]
            for pi in range(4):
                for pj in range(4):
                    if TABLE[pi][pj] == 0:  # 只剩一个格子
                        return False
                    for point in range(4):  # 0123
                        if pi + x[point] > -1 and pi + x[point] < 4 and pj + y[point] > -1 and pj + y[point] < 4 and \
                                TABLE[pi][
                                    pj] == TABLE[pi + x[point]][pj + y[point]]:
                            return False
            return True

        def showGameOverMessage():
            # 屏幕上显示游戏结束
            titleFont = pygame.font.Font('freesansbold.ttf', 60)
            titleSurf1 = titleFont.render('Game Over', True, WHITE, ORANGE)
            showMainMenu()

            while True:
                screen.fill(BGCOLOR)
                display_rect = pygame.transform.rotate(titleSurf1, 0)
                rectangle = display_rect.get_rect()
                rectangle.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
                screen.blit(display_rect, rectangle)

                showMainMenu()
                pygame.display.update()
                if checkForKeyPress():
                    if len(pygame.event.get()) > 0:  # 摁任意键继续
                        main()
                FPSCLOCK.tick(FPS)

        def showMainMenu():
            # 显示画面
            pressKeySurf = BASICFONT.render('Press a key for main menu', True, WHITE)
            pressKeyRect = pressKeySurf.get_rect()
            pressKeyRect.topleft = (WINDOWWIDTH - 250, WINDOWHEIGHT - 30)
            screen.blit(pressKeySurf, pressKeyRect)

        def checkForKeyPress():
            # 检测是否摁了按键
            if len(pygame.event.get(QUIT)) > 0:
                terminate()  # 结束

            keyUpEvents = pygame.event.get(KEYUP)
            if len(keyUpEvents) == 0:
                return None
            if keyUpEvents[0].key == K_ESCAPE:
                terminate()
            return keyUpEvents[0].key

        def show(TABLE):
            # 显示格子
            screen.fill(colorback)
            myfont = pygame.font.SysFont("Arial", 60, bold=True)
            for i in range(4):
                for j in range(4):
                    '''
                    #参数1:Surface对象,在此对象上绘制
                    #参数2:颜色
                    #参数3:矩形区域
                    #参数4:线条的粗细,单位为像素;默认值为0,表示填充矩形内部
                    '''
                    pygame.draw.rect(screen, dictcolor1[TABLE[i][j]], (j * boxsize + margin,
                                                                       i * boxsize + margin,
                                                                       boxsize - 2 * margin,
                                                                       boxsize - 2 * margin),
                                     thickness)
                    if TABLE[i][j] != 0:
                        order = int(math.log10(TABLE[i][j]))
                        myfont = pygame.font.SysFont("Arial", fontSize[order], bold=True)
                        label = myfont.render("%4s" % (TABLE[i][j]), 1, dictcolor2[TABLE[i][j]])
                        screen.blit(label, (j * boxsize + 2 * margin, i * boxsize + 9 * margin))

            pygame.display.update()

        def runGame(TABLE):
            TABLE = randomfill(TABLE)
            TABLE = randomfill(TABLE)
            show(TABLE)
            running = True

            while True:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        print("quit")
                        pygame.quit();
                        sys.exit()
                    if event.type == pygame.KEYDOWN:
                        if running:
                            desired_key = None
                            if event.key == pygame.K_UP: desired_key = "w"
                            if event.key == pygame.K_DOWN: desired_key = "s"
                            if event.key == pygame.K_LEFT: desired_key = "a"
                            if event.key == pygame.K_RIGHT: desired_key = "d"

                            if desired_key is None:
                                continue

                            new_table = key(desired_key, copy.deepcopy(TABLE))
                            if new_table != TABLE:
                                TABLE = randomfill(new_table)
                                show(TABLE)
                            if gameOver(TABLE):
                                showGameOverMessage()

        def key(DIRECTION, TABLE):
            if DIRECTION == 'w':
                for pi in range(1, 4):
                    for pj in range(4):
                        if TABLE[pi][pj] != 0: TABLE = moveup(pi, pj, TABLE)
            elif DIRECTION == 's':
                for pi in range(2, -1, -1):
                    for pj in range(4):
                        if TABLE[pi][pj] != 0: TABLE = movedown(pi, pj, TABLE)
            elif DIRECTION == 'a':
                for pj in range(1, 4):
                    for pi in range(4):
                        if TABLE[pi][pj] != 0: TABLE = moveleft(pi, pj, TABLE)
            elif DIRECTION == 'd':
                for pj in range(2, -1, -1):
                    for pi in range(4):
                        if TABLE[pi][pj] != 0: TABLE = moveright(pi, pj, TABLE)
            return TABLE

        def movedown(pi, pj, T):
            justcomb = False
            while pi < 3 and (T[pi + 1][pj] == 0 or (T[pi + 1][pj] == T[pi][pj] and not justcomb)):
                if T[pi + 1][pj] == 0:
                    T[pi + 1][pj] = T[pi][pj]
                elif T[pi + 1][pj] == T[pi][pj]:
                    T[pi + 1][pj] += T[pi][pj]
                    justcomb = True
                T[pi][pj] = 0
                pi += 1
            return T

        def moveleft(pi, pj, T):
            justcomb = False
            while pj > 0 and (T[pi][pj - 1] == 0 or (T[pi][pj - 1] == T[pi][pj] and not justcomb)):
                if T[pi][pj - 1] == 0:
                    T[pi][pj - 1] = T[pi][pj]
                elif T[pi][pj - 1] == T[pi][pj]:
                    T[pi][pj - 1] += T[pi][pj]
                    justcomb = True
                T[pi][pj] = 0
                pj -= 1
            return T

        def moveright(pi, pj, T):
            justcomb = False
            while pj < 3 and (T[pi][pj + 1] == 0 or (T[pi][pj + 1] == T[pi][pj] and not justcomb)):
                if T[pi][pj + 1] == 0:
                    T[pi][pj + 1] = T[pi][pj]
                elif T[pi][pj + 1] == T[pi][pj]:
                    T[pi][pj + 1] += T[pi][pj]
                    justcomb = True
                T[pi][pj] = 0
                pj += 1
            return T

        def moveup(pi, pj, T):
            justcomb = False
            while pi > 0 and (T[pi - 1][pj] == 0 or (T[pi - 1][pj] == T[pi][pj] and not justcomb)):
                if T[pi - 1][pj] == 0:
                    T[pi - 1][pj] = T[pi][pj]
                elif T[pi - 1][pj] == T[pi][pj]:
                    T[pi - 1][pj] += T[pi][pj]
                    justcomb = True
                T[pi][pj] = 0
                pi -= 1
            return T

        def leaderboard():
            s = 'to show leaderboard'

        def terminate():
            pygame.quit()
            sys.exit()

        main()
    elif choice1=='贪吃蛇':
        import random
        import pygame
        import sys
        from pygame.locals import *

        Snakespeed = 9
        Window_Width = 800
        Window_Height = 500
        Cell_Size = 20  # Width and height of the cells
        # Ensuring that the cells fit perfectly in the window. eg if cell size was
        # 10     and window width or window height were 15 only 1.5 cells would
        # fit.
        assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
        # Ensuring that only whole integer number of cells fit perfectly in the window.
        assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
        Cell_W = int(Window_Width / Cell_Size)  # Cell Width
        Cell_H = int(Window_Height / Cell_Size)  # Cell Height

        White = (255, 255, 255)
        Black = (0, 0, 0)
        Red = (255, 0, 0)  # Defining element colors for the program.
        Green = (0, 255, 0)
        DARKGreen = (0, 155, 0)
        DARKGRAY = (40, 40, 40)
        YELLOW = (255, 255, 0)
        Red_DARK = (150, 0, 0)
        BLUE = (0, 0, 255)
        BLUE_DARK = (0, 0, 150)

        BGCOLOR = Black  # Background color

        UP = 'up'
        DOWN = 'down'  # Defining keyboard keys.
        LEFT = 'left'
        RIGHT = 'right'

        HEAD = 0  # Syntactic sugar: index of the snake's head

        def main():
            global SnakespeedCLOCK, DISPLAYSURF, BASICFONT

            pygame.init()
            SnakespeedCLOCK = pygame.time.Clock()
            DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
            BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
            pygame.display.set_caption('Snake')

            showStartScreen()
            while True:
                runGame()
                showGameOverScreen()

        def runGame():
            # Set a random start point.
            startx = random.randint(5, Cell_W - 6)
            starty = random.randint(5, Cell_H - 6)
            wormCoords = [{'x': startx, 'y': starty},
                          {'x': startx - 1, 'y': starty},
                          {'x': startx - 2, 'y': starty}]
            direction = RIGHT

            # Start the apple in a random place.
            apple = getRandomLocation()

            while True:  # main game loop
                for event in pygame.event.get():  # event handling loop
                    if event.type == QUIT:
                        terminate()
                    elif event.type == KEYDOWN:
                        if (event.key == K_LEFT) and direction != RIGHT:
                            direction = LEFT
                        elif (event.key == K_RIGHT) and direction != LEFT:
                            direction = RIGHT
                        elif (event.key == K_UP) and direction != DOWN:
                            direction = UP
                        elif (event.key == K_DOWN) and direction != UP:
                            direction = DOWN
                        elif event.key == K_ESCAPE:
                            terminate()

                # check if the Snake has hit itself or the edge
                if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or \
                        wormCoords[HEAD]['y'] == Cell_H:
                    return  # game over
                for wormBody in wormCoords[1:]:
                    if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
                        return  # game over

                # check if Snake has eaten an apply
                if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
                    # don't remove worm's tail segment
                    apple = getRandomLocation()  # set a new apple somewhere
                else:
                    del wormCoords[-1]  # remove worm's tail segment

                # move the worm by adding a segment in the direction it is moving
                if direction == UP:
                    newHead = {'x': wormCoords[HEAD]['x'],
                               'y': wormCoords[HEAD]['y'] - 1}
                elif direction == DOWN:
                    newHead = {'x': wormCoords[HEAD]['x'],
                               'y': wormCoords[HEAD]['y'] + 1}
                elif direction == LEFT:
                    newHead = {'x': wormCoords[HEAD][
                                        'x'] - 1, 'y': wormCoords[HEAD]['y']}
                elif direction == RIGHT:
                    newHead = {'x': wormCoords[HEAD][
                                        'x'] + 1, 'y': wormCoords[HEAD]['y']}
                wormCoords.insert(0, newHead)
                DISPLAYSURF.fill(BGCOLOR)
                drawGrid()
                drawWorm(wormCoords)
                drawApple(apple)
                drawScore(len(wormCoords) - 3)
                pygame.display.update()
                SnakespeedCLOCK.tick(Snakespeed)

        def drawPressKeyMsg():
            pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
            pressKeyRect = pressKeySurf.get_rect()
            pressKeyRect.topleft = (Window_Width - 200, Window_Height - 30)
            DISPLAYSURF.blit(pressKeySurf, pressKeyRect)

        def checkForKeyPress():
            if len(pygame.event.get(QUIT)) > 0:
                terminate()
            keyUpEvents = pygame.event.get(KEYUP)
            if len(keyUpEvents) == 0:
                return None
            if keyUpEvents[0].key == K_ESCAPE:
                terminate()
            return keyUpEvents[0].key

        def showStartScreen():
            titleFont = pygame.font.Font('freesansbold.ttf', 100)
            titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
            degrees1 = 0
            degrees2 = 0
            while True:
                DISPLAYSURF.fill(BGCOLOR)
                rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
                rotatedRect1 = rotatedSurf1.get_rect()
                rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
                DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)

                drawPressKeyMsg()

                if checkForKeyPress():
                    pygame.event.get()  # clear event queue
                    return
                pygame.display.update()
                SnakespeedCLOCK.tick(Snakespeed)
                degrees1 += 3  # rotate by 3 degrees each frame
                degrees2 += 7  # rotate by 7 degrees each frame

        def terminate():
            pygame.quit()
            sys.exit()

        def getRandomLocation():
            return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}

        def showGameOverScreen():
            gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
            gameSurf = gameOverFont.render('Game', True, White)
            overSurf = gameOverFont.render('Over', True, White)
            gameRect = gameSurf.get_rect()
            overRect = overSurf.get_rect()
            gameRect.midtop = (Window_Width / 2, 10)
            overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)

            DISPLAYSURF.blit(gameSurf, gameRect)
            DISPLAYSURF.blit(overSurf, overRect)
            drawPressKeyMsg()
            pygame.display.update()
            pygame.time.wait(500)
            checkForKeyPress()  # clear out any key presses in the event queue

            while True:
                if checkForKeyPress():
                    pygame.event.get()  # clear event queue
                    return

        def drawScore(score):
            scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)
            scoreRect = scoreSurf.get_rect()
            scoreRect.topleft = (Window_Width - 120, 10)
            DISPLAYSURF.blit(scoreSurf, scoreRect)

        def drawWorm(wormCoords):
            for coord in wormCoords:
                x = coord['x'] * Cell_Size
                y = coord['y'] * Cell_Size
                wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
                pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
                wormInnerSegmentRect = pygame.Rect(
                    x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
                pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)

        def drawApple(coord):
            x = coord['x'] * Cell_Size

            y = coord['y'] * Cell_Size
            appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
            pygame.draw.rect(DISPLAYSURF, Red, appleRect)

        def drawGrid():
            for x in range(0, Window_Width, Cell_Size):  # draw vertical lines
                pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
            for y in range(0, Window_Height, Cell_Size):  # draw horizontal lines
                pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))

        if __name__ == '__main__':
            try:
                main()
            except SystemExit:
                pass
    elif choice1=='猜字游戏':
        import easygui as a
        import sys
        import random

        while True:
            flage = 3
            a.msgbox("欢迎使用猜字游戏!")
            password = random.randint(0, 100)
            while flage:
                guess = a.integerbox(msg="请输入1-100之间的数字,有三次机会", title="猜字游戏", lowerbound=0, upperbound=100)
                if password == guess:
                    a.msgbox("恭喜你,猜中了")
                    break
                elif password > guess:
                    a.msgbox("猜小了还有%s次机会" % (flage - 1))
                else:
                    a.msgbox("猜大了还有%s次机会" % (flage - 1))
                flage - 1
            if flage == 0:
                a.msgbox("正确的答案为%s" % password)

            if a.ccbox(msg="是否需要重新开始?", title="请选择"):
                pass
            else:
                sys.exit()
elif choice=='看图画':
    choice2=g.buttonbox(msg='选择要看的图画名称',title='图画选择',choices=('线条','刺球','螺旋图'))
    if choice2=='线条':
        import turtle
        q = turtle.Pen()
        turtle.bgcolor("white")
        sides = 7
        colors = ["red", "orange", "yellow", "green", "cyan", "blue", "blue", "purple"]
        for x in range(360):
            q.pencolor(colors[x % sides])
            q.forward(x * 3 / sides + x)
            q.left(360 / sides + 1)
            q.width(x * sides / 200)
    elif choice2=='刺球':
        import turtle as t
        t.speed(10)
        t.color('cyan')
        t.bgcolor('black')
        b = 200
        while b > 0:
            t.left(b)
            t.forward(b * 3)
            b = b - 1
        t.done()
    elif choice2=='螺旋图':
       direction=g.buttonbox(msg='选择旋转的方向:左/右?',title='方向选择',choices=('左','右'))
       angle= g.integerbox(msg='请输入你想要旋转的角度:',title='角度输入',lowerbound=0,upperbound=360)
       import turtle as t
       from random import randint
       t.TurtleScreen._RUNNING = True
       t.pensize(0.9)  # 利用笔的粗细调整图形
       t.bgcolor("black")
       t.speed(0.1)
       t.setpos(-25, 25)
       t.colormode(255)
       cnt = 0
       while cnt < 500:
           r = randint(0, 255)
           g = randint(0, 255)
           b = randint(0, 255)
           t.pencolor(r, g, b)  # 随机产生颜色
           t.forward(50 + cnt)
           '''两种旋转方向 角度不能等于90  修改角度可得到不同的图形 '''
           if direction=='左':
               t.left(angle)
           elif direction=='右':
                t.right(angle)
           # 可用角度89 70 65 50 91  150
           cnt += 1
       t.done()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值