20221325杨筱 2022-2023-2 《Python程序设计》实验四报告

怣忈雪 2023-05-25 21:39:28

20221325杨筱 2022-2023-2 《Python程序设计》实验四报告
课程:《Python程序设计》
班级: 2213
姓名: 杨筱
学号:20221325
实验教师:王志强
实验日期:2023年5月11日
必修/选修: 公选课
一).实验内容
Python综合应用:爬虫、数据处理、可视化、机器学习、神经网络、游戏、网络安全等。
python代码实现2048小游戏

(二).实验过程及结果
实验设计分析
从网上找到合适图片画出棋盘,游戏初始或结束时重置棋盘
获取用户输入,根据用户的输入进行上/下/左/右的移动
记录每次步骤,判断输赢,显示每次成绩和记录并保存最高成绩
代码实现
实现动画的代码

import random
import pygame
import sys
from pygame.locals import *

Snakespeed = 17
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 windowheight 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)  # Cellc 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


运行结果:


三)实验心得体会
本次实验是选择用Python实现贪吃蛇。虽然不太完美,但观赏性还是可以的,和上架的那些游戏也大差不差。通过本次实验,实现了自己做一个游戏的小愿望,虽然不算创新,但也是很有趣也比较有成就感,本次实验的过程虽然有些长,但结果成功的呈现所带来的的感觉还是非常香的。在其中也是借鉴了不少网上的思虑和逻辑,自己的能力还是有些欠缺,在今后还会进一步学习提高自己的Python水平。
四)全课总结
上学期在必修课上学习了C语言,进入了编程的大门,在这学期中,通过选修python课上的基础知识学习,我对python也有了一定的认识。
学到了不少有用的特色的内容包括一些简单的如:基础语法和流程控制语句,还有序列(:列表,元组,字典,集合),字符串与正则表达式,以及老师多次提到的面向对象三要素:封装、继承、多态,一些难度较大如:文件及目录操作,socket编程技术,数据库,Python网络爬虫技术等。在学习Python后的最大感受是,实用性很强,可以在多种场景进行应用,虽然课程告一段落,但我相信它在我未来的学习和工作中将发挥更多作用。还有就是王老师讲课风格非常让人舒服,一系列现场例子让晦涩的知识变得灵动起来,留下了深刻印象。

...全文
492 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文围绕“阶梯碳下考虑P2G-CCS与供需灵活响应的IES优化调度”展开,基于Matlab平台构建综合能源系统(IES)在阶梯式碳交易机制下的优化调度模型。研究深度融合电制气(P2G)与碳捕集、利用与封存(CCS)技术,结合需求侧灵活响应机制,旨在提升系统的低碳运行能力与经济性。通过建立多能流耦合的优化模型,协调电力、天然气、热力等多种能源形式的协同调度,有效降低系统碳排放强度,并借助YALIMIP工具包调用求解器进行高效求解。文档提供了完整的代码实现、模型构建流程与结果分析方法,涵盖从问题建模到仿真实现的全过程,具备较强的可复现性与科研参考价值。; 适合人群:具备电力系统、能源系统或优化建模相关背景的研究生、高校教师及工程技术人员,尤其适合从事综合能源系统、碳减排策略、P2G与CCS技术集成研究的专业人员,需熟练掌握Matlab编程与基本的数学规划知识。; 使用场景及目标:①用于研究阶梯式碳交易政策下综合能源系统的低碳经济调度策略;②支撑P2G-CCS技术与需求响应机制在IES中的仿真集成与性能评估;③作为撰写高水平学术论文(如EI/SCI收录)的技术基础与复现资源,推动碳中和背景下能源系统优化方向的创新研究。; 阅读建议:建议结合百度网盘提供的完整代码与资料包,按照模块逐步调试程序,重点理解目标函数的设计逻辑、碳交易成本的建模方式、约束条件的数学表达及求解器的配置方法,同时关注多能耦合设备的建模细节,配合公众号“荔枝科研社”获取持续的技术支持与案例拓展。
内容概要:本文系统研究了基于卷积神经网络(CNN)与支持向量机(SVM)融合的CNN-SVM混合模型在数据分类预测中的应用,尤其聚焦于工业故障识别领域。通过Matlab平台实现,该方法首先利用CNN强大的多层次特征提取能力对原始输入数据进行深度特征学习,自动捕获关键局部模式与空间结构信息,随后将提取的高层特征作为输入传递至SVM分类器,借助SVM在高维空间中小样本条件下卓越的分类性能与泛化能力完成最终判别任务。文中详尽阐述了模型的整体架构设计、网络参数配置、训练优化流程及特征迁移机制,充分结合了深度学习在特征表达上的优势与传统机器学习在分类决策上的稳健性。实验部分通过实际故障数据集验证了该混合模型相较于单一CNN或SVM模型在分类准确率、鲁棒性和抗过拟合能力方面的显著提升,证明了其在复杂故障诊断任务中的有效性与先进性; 适合人群:具备一定机器学习与深度学习理论基础,熟悉Matlab编程环境,从事故障诊断、模式识别、智能制造、电力系统监控或工业数据分析等相关领域的研究生、科研人员及工程技术开发者; 使用场景及目标:① 应用于旋转机械、电力设备、航空航天等领域的多类别故障识别与状态监测;② 掌握深度特征提取与传统分类器融合的技术路径,提升小样本、高噪声环境下数据分类的精度与可靠性;③ 为撰写高水平学术论文、开展科研项目或工程实践提供可复现的算法框架与完整代码支持; 阅读建议:读者应深入理解CNN与SVM的协同工作机制,重点分析特征提取层与分类层之间的接口设计,建议动手运行并调试所提供的Matlab代码,尝试在不同数据集上进行迁移实验与参数调优,以全面掌握该混合模型的应用技巧与优化策略。

144

社区成员

发帖
与我相关
我的任务
社区描述
开展Python教学和技术交流
python 高校 北京·丰台区
社区管理员
  • blackwall0321
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧