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后的最大感受是,实用性很强,可以在多种场景进行应用,虽然课程告一段落,但我相信它在我未来的学习和工作中将发挥更多作用。还有就是王老师讲课风格非常让人舒服,一系列现场例子让晦涩的知识变得灵动起来,留下了深刻印象。

...全文
215 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
在CAD(计算机辅助设计)软件中,线性是构建采矿工程图的重要元素。"cad采矿用各种线性"指的是在CAD环境下,为了精确地表示采矿工程的地质结构、开采路径、巷道布局等,所使用的一系列特定线型。这些线型通常包括连续线、虚线、点划线以及定制的特殊线型,以便清晰地标识不同类型的地质特征、开采边界和安全区域。 线型在CAD中起到区分和标识不同对象的作用。例如,连续线可能用于表示巷道的实际走向,虚线可能用于表示规划中的巷道或尚未施工的部分,点划线则可能用于显示支撑结构或危险区域。通过选择合适的线型,工程师们可以更直观地理解采矿工程的设计和进度。 `.lin`文件是CAD中的线型文件,它包含了线型的定义。用户可以自定义线型,如设置线型的比例因子、每个线段的长度和间隔,以及它们的组合方式。`.lin`文件可以被CAD软件读取,使得用户在绘图时能够选择并应用这些预定义的线型。 `.shp`和`.shx`文件则是与CAD中的形状文件相关的。`.shp`文件是一种存储地理空间数据的标准格式,通常包含几何对象(如点、线和多边形)的信息。在采矿领域,这些文件可能用于表示矿体的边界、巷道的位置或其他地质特征。`.shx`文件是`.shp`文件的索引,用于快速访问和处理数据,提高软件的性能。 结合这些文件,我们可以创建一个全面的采矿工程图,其中包括了各种定制的线性表示,使设计和分析工作更为准确高效。在实际操作中,工程师首先会根据需求定义或导入`.lin`文件,然后在绘制巷道、矿体和其他元素时选择相应的线型。同时,他们会利用`.shp`和`.shx`文件来加载和管理地理空间数据,以便在CAD环境中呈现采矿区域的三维视图和二维平面图。 通过熟练掌握CAD中的线性操作,采矿工程师能够更好地进行规划、模拟和沟通,确保采矿作业的安全性和经济性。此外,这些技术也可以应用于其他工程领域,如土木工程、地质调查等,因为线型的使用是通用的,旨在提供清晰的视觉表示和专业信息的传递。因此,深入理解和应用CAD中的线性是现代工程设计不可或缺的一部分。
资源下载链接为: https://pan.quark.cn/s/f989b9092fc5 以下是关于“LUST中文操作手册-s.pdf”文档的知识点解析: 标题与描述:文档标题为“LUST中文操作手册-s.pdf”,从标题来看,这是一份关于LUST系统的中文操作手册,其描述与标题相同,推测是直接以文件名作为描述。 标签:“11”可能是手册中的章节编号或特定功能模块编号,需结合文档内容确定具体含义。 内容分析:手册涉及LUST系统的多个方面,如伺服控制、系统配置、参数设置等。以下是详细解析: 1.1部分:介绍LUST系统的基本概念或功能特性。提到夜晚的概念,可能指系统工作环境或某种工作模式;还涉及操作或配置命令,以及电源或供电部分,如230V/460V电压等级,推测在介绍硬件基础配置。 2.1至2.2.2部分:涉及系统内部功能模块,包括驱动控制等。提到驱动器或控制器的电源部分,以及具体的配置步骤或参数设置指南。 4部分:提到伺服控制系统(ServoC),是手册的重要内容之一。详细介绍了如何配置和使用伺服控制系统,包括不同配置步骤或使用场景。 3部分:关于系统的总体配置或设置指南。可能提供了系统核心组件或主要配置项的设定方法。 5.1至5.2.3部分:涉及系统的工作原理或操作流程。可能详细介绍了系统的具体工作流程或操作模式。 6部分:介绍LUST系统中某个特定功能模块的操作指南,例如高级设置或特定应用场景下的操作指导。 7.1至7.3.4部分:涉及系统的配置管理或特定组件的使用指南,详细介绍了配置管理的不同方面,包括配置工具的使用、特定组件的配置指南等。 8.1至8.5.1部分:涵盖系统的其他高级功能或特定应用场景下的操作指南。 综上所述,LUST系统是一套复杂的自动化控制系统,涉及伺服控制、系统配置等多个方面。该手册详细地介绍了如何使用和配置这套系统,是用户宝贵的参考资料。

144

社区成员

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

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