20231304 2023-2024-2 《Python程序设计》实验四报告
课程:《Python程序设计》
班级: 2313
姓名: 王星婷
学号:20231304
实验教师:王志强
实验日期:2024年5月29日
必修/选修: 公选课
1.实验内容
Python综合应用:爬虫、数据处理、可视化、机器学习、神经网络、游戏、网络安全等。
课代表和各小组负责人收集作业(源代码、视频、综合实践报告)
例如:编写从社交网络爬取数据,实现可视化舆情监控或者情感分析。
例如:利用公开数据集,开展图像分类、恶意软件检测等
例如:利用Python库,基于OCR技术实现自动化提取图片中数据,并填入excel中。
例如:爬取天气数据,实现自动化微信提醒
例如:利用爬虫,实现自动化下载网站视频、文件等。
例如:编写小游戏:坦克大战、贪吃蛇、扫雷等等
2. 实验过程及结果
1.创建蛇和立方体
import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox
class cube(object):
rows = 20
w = 500
def __init__(self, start, dirnx=1, dirny=0, color=(255, 0, 0)):
pass
def move(self, dirnx, dirny):
pass
def draw(self, surface, eyes=False):
pass
class snake(object):
def __init__(self, color, pos):
pass
def move(self):
pass
def reset(self, pos):
pass
def addCube(self):
pass
def draw(self, surface):
pass
def drawGrid(w, rows, surface):
pass
def redrawWindow(surface):
pass
def randomSnack(rows, item):
pass
def message_box(subject, content):
pass
def main():
pass
main()
###2.创造游戏循环:
在main()功能。在函数的顶部声明一些变量,然后进入while循环。
def main():
global width, rows, s
width = 500 # Width of our screen
height = 500 # Height of our screen
rows = 20 # Amount of rows
win = pygame.display.set_mode((width, height)) # Creates our screen object
s = snake((255, 0, 0), (10, 10)) # Creates a snake object which we will code later
clock = pygame.time.Clock() # creating a clock object
flag = True
# STARTING MAIN LOOP
while flag:
pygame.time.delay(50) # This will delay the game so it doesn't run too quickly
clock.tick(10) # Will ensure our game runs at 10 FPS
redrawWindow(win) # This will refresh our screen
3.更新屏幕,在游戏循环中每一帧调用这个函数,并简单绘制网格线
def redrawWindow(surface):
surface.fill((0,0,0)) # Fills the screen with black
drawGrid(surface) # Will draw our grid lines
pygame.display.update() # Updates the screen
4.绘制网格:20*20
def drawGrid(w, rows, surface):
sizeBtwn = w // rows # Gives us the distance between the lines
x = 0 # Keeps track of the current x
y = 0 # Keeps track of the current y
for l in range(rows): # We will draw one vertical and one horizontal line each loop
x = x + sizeBtwn
y = y + sizeBtwn
pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, w))
pygame.draw.line(surface, (255, 255, 255), (0, y), (w, y))
5.运行程序时,即可看到网格线
6.制作贪吃蛇
将蛇作为一个立方体列表,将这些立方体存在body列表中,成为一个类变量。
class snake(object):
body = []
turns = {}
def __init__(self, color, pos):
self.color = color
self.head = cube(pos) # The head will be the front of the snake
self.body.append(self.head) # We will add head (which is a cube object)
# to our body list
# These will represent the direction our snake is moving
self.dirnx = 0
self.dirny = 1
7.制作蛇的转弯动作
我们需要记住我们把我们的蛇转向了哪里和哪个方向,这样当头部后面的立方体到达那个位置时,我们也可以把它们转向。这就是为什么每当我们转向时,我们会将头部的位置添加到转向字典中,其中值是我们转向的方向。这样,当其他立方体到达这个位置时,我们就知道如何转动它们了。
class snake(object):
...
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed()
for key in keys:
if keys[pygame.K_LEFT]:
self.dirnx = -1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_RIGHT]:
self.dirnx = 1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_UP]:
self.dirnx = 0
self.dirny = -1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_DOWN]:
self.dirnx = 0
self.dirny = 1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
for i, c in enumerate(self.body): # Loop through every cube in our body
p = c.pos[:] # This stores the cubes position on the grid
if p in self.turns: # If the cubes current position is one where we turned
turn = self.turns[p] # Get the direction we should turn
c.move(turn[0], turn[1]) # Move our cube in that direction
if i == len(self.body) - 1: # If this is the last cube in our body remove the turn from the dict
self.turns.pop(p)
else: # If we are not turning the cube
# If the cube reaches the edge of the screen we will make it appear on the opposite side
if c.dirnx == -1 and c.pos[0] <= 0:
c.pos = (c.rows - 1, c.pos[1])
elif c.dirnx == 1 and c.pos[0] >= c.rows - 1:
c.pos = (0, c.pos[1])
elif c.dirny == 1 and c.pos[1] >= c.rows - 1:
c.pos = (c.pos[0], 0)
elif c.dirny == -1 and c.pos[1] <= 0:
c.pos = (c.pos[0], c.rows - 1)
else:
c.move(c.dirnx, c.dirny) # If we haven't reached the edge just move in our current direction
8.画蛇
画出蛇的立方体,用draw()
class snake(object):
...
def draw(self):
for i, c in enumerate(self.body):
if i == 0: # for the first cube in the list we want to draw eyes
c.draw(surface, True) # adding the true as an argument will tell us to draw eyes
else:
c.draw(surface) # otherwise we will just draw a cube
9.当蛇与自己碰撞时游戏结束
for x in range(len(s.body)):
if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])): # This will check if any of the positions in our body list overlap
print('Score: ', len(s.body))
message_box('You Lost!', 'Play again...')
s.reset((10,10))
break
10.重置你的小蛇
这样我们可以再次玩
class snake():
...
def reset(self, pos):
self.head = cube(pos)
self.body = []
self.body.append(self.head)
self.turns = {}
self.dirnx = 0
self.dirny = 1
过程中遇到的问题和解决过程
- 问题1:下载pygame网站要求必须使用python2.7版本
- 问题1解决方案:直接在cmd中安装pygame和cfg2
- 问题2:小蛇转弯时动作出问题
- 问题2解决方案:每次重新测试小蛇的转向,避免方向错误
- …
其他(感悟、思考等)
1.学习一学期的python,python要比C语言更简单便捷,更容易理解,王老师的讲解也很详细,学到了很多;
2.学习python时很容易遇到与C语言类似的问题,要学会各科学习之间的互通。