20212214 《Python程序设计》实验四 Python综合实践实验报告

 

 20212214 《Python程序设计》实验四 Python综合实践实验报告

 

课程:        《Python程序设计》
班级:        2122
姓名:        蒋贞志
学号:        20212214
实验教师:  王志强
实验日期:  2022年5月25日
必修/选修: 公选课

 

实验内容

Python综合应用:爬虫、数据处理、可视化、机器学习、神经网络、游戏、网络安全等。

注:在华为ECS服务器(OpenOuler系统)和物理机(Windows/Linux系统)上使用VIM、PDB、IDLE、Pycharm等工具编程实现

一、实验程序

       (一)、实验项目内容

                          运用Python写 “ 俄罗斯方块 ” 小游戏 。以前喜欢玩一些小游戏,其中俄罗斯方块带来很多乐趣,所以想自己来看看怎么用Python代码执行俄罗斯方块小游戏.

      (二)、实验项目实现过程

                         首先购买华为云服务器

 

 

                  然后,由于我是写游戏,于是我在云端上先下载好pygame

 

 

由于需要在云端上运行,在尝试几次在云端上执行代码之后,发现不行,询问同学,发现要下载xming,xterm配置远程桌面

 

安装好xming之后,在云端上建立一个新的目录,我将代码上传至云端

 

 

 

 

配置好xlaunch之后,在云端Xming上执行自己的代码命令 

 

 

在本机上运行代码

 

 

 

 

 

(三)代码分析过程

               核心思路:

                  1.图像由“核心变量”完全控制,图像变化的本质是 变量的改变。

                  2,自上而下式的思考,图像变化的问题将一步步转为 一系列具体的变量修改。

 

                         导入pygame游戏模块,sys模块,time模块。

 

然后创建画面

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

方块

 

是否开始,当start = True,game_over = True 时,才显示 GAME OVER

 

 

计算消除
计算得分
 旋转,这是我遇到的最大的麻烦,手机资料,发现很多其他人执行的都是不可以旋转的,缺乏体验,所以,观看教程视频,不断收集资料
最终实现旋转,
在形状设计的时候做了很多的空白,这样只需要规定整个形状包括空白部分全部在游戏区域内时才可以旋转

 

 

 

 

按向下的键是加速,不用旋转。

 

画当前下落方块
画背景

  

 填充背景色
画游戏区域分隔线
画已经落下的方块
画单个方块

 最后画得分等信息

 

最后完善导入的库函数

 

 

方块形状的设计,最初我是做成 4 × 4,因为长宽最长都是4,这样旋转的时候就不考虑怎么转了,就是从一个图形替换成另一个
 
其实要实现这个功能,只需要固定左上角的坐标就可以了
 
我们先完成旋转,然后检查旋转后的俄罗斯方块是否与已有方块重合,如果有,则再让方块逆方向旋转一次。最后绘制旋转后的俄罗斯方块。
 
在blocks里导入random

 

 

根据自己以前观看的俄罗斯方块,来画不同种类的方块

“s”形方块

Z形方块

I型方块
O型方块
J型方块
L型方块

 

T型方块

 

 

源代码

 

import sys
import time
import pygame
from pygame.locals import *
import blocks

SIZE = 30  
BLOCK_HEIGHT = 25  
BLOCK_WIDTH = 10   
BORDER_WIDTH = 4   
BORDER_COLOR = (40, 40, 200) 
SCREEN_WIDTH = SIZE * (BLOCK_WIDTH + 5)  
SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT      
BG_COLOR = (40, 40, 60)  
BLOCK_COLOR = (20, 128, 200)  
BLACK = (0, 0, 0)
RED = (200, 30, 30)      # GAME OVER 的字体颜色


def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
    imgText = font.render(text, True, fcolor)
    screen.blit(imgText, (x, y))


def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('俄罗斯方块')

    font1 = pygame.font.SysFont('SimHei', 24)  # 黑体24
    font2 = pygame.font.Font(None, 72)  # GAME OVER 的字体
    font_pos_x = BLOCK_WIDTH * SIZE + BORDER_WIDTH + 10  # 右侧信息显示区域字体位置的X坐标
    gameover_size = font2.size('GAME OVER')
    font1_height = int(font1.size('得分')[1])

    cur_block = None   # 当前下落方块
    next_block = None  # 下一个方块
    cur_pos_x, cur_pos_y = 0, 0

    game_area = None    
    game_over = True
    start = False      
    score = 0           
    orispeed = 0.5     
    speed = orispeed    
    pause = False     
    last_drop_time = None   
    last_press_time = None  

    def _dock():
        nonlocal cur_block, next_block, game_area, cur_pos_x, cur_pos_y, game_over, score, speed
        for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
            for _j in range(cur_block.start_pos.X, cur_block.end_pos.X + 1):
                if cur_block.template[_i][_j] != '.':
                    game_area[cur_pos_y + _i][cur_pos_x + _j] = '0'
        if cur_pos_y + cur_block.start_pos.Y <= 0:
            game_over = True
        else:
            # 计算消除
            remove_idxs = []
            for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
                if all(_x == '0' for _x in game_area[cur_pos_y + _i]):
                    remove_idxs.append(cur_pos_y + _i)
            if remove_idxs:
                # 计算得分
                remove_count = len(remove_idxs)
                if remove_count == 1:
                    score += 100
                elif remove_count == 2:
                    score += 300
                elif remove_count == 3:
                    score += 700
                elif remove_count == 4:
                    score += 1500
                speed = orispeed - 0.03 * (score // 10000)
                # 消除
                _i = _j = remove_idxs[-1]
                while _i >= 0:
                    while _j in remove_idxs:
                        _j -= 1
                    if _j < 0:
                        game_area[_i] = ['.'] * BLOCK_WIDTH
                    else:
                        game_area[_i] = game_area[_j]
                    _i -= 1
                    _j -= 1
            cur_block = next_block
            next_block = blocks.get_block()
            cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y

    def _judge(pos_x, pos_y, block):
        nonlocal game_area
        for _i in range(block.start_pos.Y, block.end_pos.Y + 1):
            if pos_y + block.end_pos.Y >= BLOCK_HEIGHT:
                return False
            for _j in range(block.start_pos.X, block.end_pos.X + 1):
                if pos_y + _i >= 0 and block.template[_i][_j] != '.' and game_area[pos_y + _i][pos_x + _j] != '.':
                    return False
        return True

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_RETURN:
                    if game_over:
                        start = True
                        game_over = False
                        score = 0
                        last_drop_time = time.time()
                        last_press_time = time.time()
                        game_area = [['.'] * BLOCK_WIDTH for _ in range(BLOCK_HEIGHT)]
                        cur_block = blocks.get_block()
                        next_block = blocks.get_block()
                        cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y
                elif event.key == K_SPACE:
                    if not game_over:
                        pause = not pause
                elif event.key in (K_w, K_UP):
                   
                    if 0 <= cur_pos_x <= BLOCK_WIDTH - len(cur_block.template[0]):
                        _next_block = blocks.get_next_block(cur_block)
                        if _judge(cur_pos_x, cur_pos_y, _next_block):
                            cur_block = _next_block

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                if not game_over and not pause:
                    if time.time() - last_press_time > 0.1:
                        last_press_time = time.time()
                        if cur_pos_x > - cur_block.start_pos.X:
                            if _judge(cur_pos_x - 1, cur_pos_y, cur_block):
                                cur_pos_x -= 1
            if event.key == pygame.K_RIGHT:
                if not game_over and not pause:
                    if time.time() - last_press_time > 0.1:
                        last_press_time = time.time()
                        # 不能移除右边框
                        if cur_pos_x + cur_block.end_pos.X + 1 < BLOCK_WIDTH:
                            if _judge(cur_pos_x + 1, cur_pos_y, cur_block):
                                cur_pos_x += 1
            if event.key == pygame.K_DOWN:
                if not game_over and not pause:
                    if time.time() - last_press_time > 0.1:
                        last_press_time = time.time()
                        if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
                            _dock()
                        else:
                            last_drop_time = time.time()
                            cur_pos_y += 1

        _draw_background(screen)

        _draw_game_area(screen, game_area)

        _draw_gridlines(screen)

        _draw_info(screen, font1, font_pos_x, font1_height, score)
        # 画显示信息中的下一个方块
        _draw_block(screen, next_block, font_pos_x, 30 + (font1_height + 6) * 5, 0, 0)

        if not game_over:
            cur_drop_time = time.time()
            if cur_drop_time - last_drop_time > speed:
                if not pause:
                    if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
                        _dock()
                    else:
                        last_drop_time = cur_drop_time
                        cur_pos_y += 1
        else:
            if start:
                print_text(screen, font2,
                           (SCREEN_WIDTH - gameover_size[0]) // 2, (SCREEN_HEIGHT - gameover_size[1]) // 2,
                           'GAME OVER', RED)

 
        _draw_block(screen, cur_block, 0, 0, cur_pos_x, cur_pos_y)

        pygame.display.flip()


# 画背景
def _draw_background(screen):
    # 填充背景色
    screen.fill(BG_COLOR)
    # 画游戏区域分隔线
    pygame.draw.line(screen, BORDER_COLOR,
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
                     (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)


# 画网格线
def _draw_gridlines(screen):
    # 画网格线 竖线
    for x in range(BLOCK_WIDTH):
        pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1)
    # 画网格线 横线
    for y in range(BLOCK_HEIGHT):
        pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1)


# 画已经落下的方块
def _draw_game_area(screen, game_area):
    if game_area:
        for i, row in enumerate(game_area):
            for j, cell in enumerate(row):
                if cell != '.':
                    pygame.draw.rect(screen, BLOCK_COLOR, (j * SIZE, i * SIZE, SIZE, SIZE), 0)


# 画单个方块
def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):
    if block:
        for i in range(block.start_pos.Y, block.end_pos.Y + 1):
            for j in range(block.start_pos.X, block.end_pos.X + 1):
                if block.template[i][j] != '.':
                    pygame.draw.rect(screen, BLOCK_COLOR,
                                     (offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + i) * SIZE, SIZE, SIZE), 0)


# 画得分等信息
def _draw_info(screen, font, pos_x, font_height, score):
    print_text(screen, font, pos_x, 10, f'得分: ')
    print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')
    print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')
    print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')
    print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一个:')


if __name__ == '__main__':
    main()
 
 
在本机上运行结果

 

 

在云端上运行结果

 

二、 实验过程中遇到的问题和解决过程

问题一:不会将Python代码上传至云服务器

解决方法:询问已经学会的同学,通过观看bibi上面的视频,成功将代码上传至云端。

 

 

问题二:云端上没有屏幕,不能运行自己的小游戏

解决方法:询问同学,安装Xming。

 

 

问题三:Xming在云服务器上运行失败

 

解决方法:观看视频,在网上查找资料,询问基础好的同学。成功解决问题

自己没有更新,执行 systemctl restart sshd.service 命令

 

 

 

三、对Python全课的总结与感想体会

上个学期,选Python是因为我觉得这个学期需要学C,可以二者相互补充,相互提高。

学了之后,Python和C还是有很大的区别。

代码层面看C与python所谓不同编程语言,在代码层面来看,主要不同之处在于它们的语法规则,掌握了一种编程语言的语法规则,就可以写出一种代码。

C语言中有源文件、目标文件、可执行文件这些概念,python中只有脚本及解释器 。

在王志强老师的教授下,我也学会了很多Python知识。Python知识特点就不过多赘述。

首先,学习任何语言,都得勤加练习,Python课程之前我查找过资料书,之前就已经接触过一点,在上Python课的期间,我也练习Python代码编写。

 

 初步认识Python,到python语言基础,流程控制语句,序列的应用,字符串与正则表达式,函数,面向对象程序设计,文件操作及异常处理,Python操作数据库,

Python网络编程及爬虫开发。在经过一个学期Python课程的学习,我对Python也有了一定的掌握。

通过志强老师布置的几次实验任务,也使我对Python技能更加熟悉,在几次实验的操作过程中,我也遇到了各种不同的麻烦,但最后也是通过询问其他同学,上网搜查资料,最终实现代码的运行,完成实验。一次次的实验,使我面对不同问题,不再害怕,尝试去解决问题,寻找各种方案去解决问题。通过使用自己的各种手段最终解决问题,最后获得的也是很大的满足感。很高兴选择了Python课程,在这里我学到了很多东西与技能。

 

Python课程的意见和建议

老师上课的代码可以分享到班群里面,可能会有同学上课来不及跟上老师的节奏,将代码发群里面可以让同学更好地学习,参考与借鉴。

 

 

 

参考资料:

_tkinter.TclError: no display name and no $DISPLAY environment variable - 简书 (jianshu.com)

 

(1条消息) 华为鲲鹏云服务器上安装Python-3.6.2并安装第三方库详细步骤_半树海棠的博客-CSDN博客_华为云安装python

 

(1条消息) wsl安装xrdp(可视化界面并远程),解决闪退、黑屏_daboluo520的博客-CSDN博客_xrdp 黑屏闪退

 

Xming-6-9-0-31-setup.exe_免费高速下载|百度网盘-分享无限制 (baidu.com)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

                          

posted @ 2022-05-29 13:00  ℒℴѵℯ  阅读(624)  评论(0编辑  收藏  举报