110
社区成员
发帖
与我相关
我的任务
分享20232318 王天昊 2023-2024-2 《Python程序设计》实验四报告
课程:《Python程序设计》
班级: 2323班
姓名: 王天昊
学号: 20232318
实验教师:王志强
实验日期:2024年5月15日
必修/选修: 公选课
1.实验内容
【1】实验整体内容:
Python综合应用:爬虫、数据处理、可视化、机器学习、神经网络、游戏、网络安全等。
课代表和各小组负责人收集作业(源代码、视频、综合实践报告)
例如:编写从社交网络爬取数据,实现可视化舆情监控或者情感分析。
例如:利用公开数据集,开展图像分类、恶意软件检测等
例如:利用Python库,基于OCR技术实现自动化提取图片中数据,并填入excel中。
例如:爬取天气数据,实现自动化微信提醒
例如:利用爬虫,实现自动化下载网站视频、文件等。
例如:编写小游戏:坦克大战、贪吃蛇、扫雷等等
注:在Windows/Linux系统上使用VIM、PDB、IDLE、Pycharm等工具编程实现。
【2】本实验聚焦内容:
(1)通过python编写飞鸟躲避黑点游戏
from random import *
from turtle import *
from freegames import vector
(2)初始化变量,bird代表玩家的鸟的位置,初始位置为(0, 0);balls为一个列表,用于存储所有球的位置。bird = vector(0, 0)
balls = []
(3)函数定义:fly(x, y)、inside(point)、 draw(alive)、move()fly(x,y):当屏幕被点击时调用,使得bird向上移动30个单位
def fly(x, y):
"""Move bird up in response to screen tap."""
up = vector(0, 30)
bird.move(up)
inside(point):判断一个点是否在屏幕上,如果点在(-200, 200) x (-200, 200)的范围内则返回True
def inside(point):
return -200 < point.x < 200 and -200 < point.y < 200
draw(alive):清除屏幕并绘制所有的对象,如果alive为True,鸟是绿色的;否则是红色的,并遍历balls列表并绘制所有的球
def draw(alive):
clear()
goto(bird.x, bird.y)
if alive:
dot(10, 'green')
else:
dot(10, 'red')
for ball in balls:
goto(ball.x, ball.y)
dot(20, 'black')
update()
move():使鸟不断向下掉,给予重力,并且每个球会不断向左移动。同时添加新的球,检查球是否和鸟碰撞。
def move():
bird.y -= 5
for ball in balls:
ball.x -= 3
if randrange(10) == 0:
y = randrange(-199, 199)
ball = vector(199, y)
balls.append(ball)
while len(balls) > 0 and not inside(balls[0]):
balls.pop(0)
if not inside(bird):
draw(False)
return
for ball in balls:
if abs(ball - bird) < 15:
draw(False)
return
draw(True)
ontimer(move, 50)
(4)设置和初始化turtle:设置窗口大小、箭头痕迹、屏幕点击时调用fly函数、开始游戏功能等等
setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(fly)
move()
done()
3.实验完整项目源代码
from random import *
from turtle import *
from freegames import vector
bird = vector(0, 0)
balls = []
def fly(x, y):
up = vector(0, 30)
bird.move(up)
def inside(point):
return -200 < point.x < 200 and -200 < point.y < 200
def draw(alive):
clear()
goto(bird.x, bird.y)
if alive:
dot(10, 'green')
else:
dot(10, 'red')
for ball in balls:
goto(ball.x, ball.y)
dot(20, 'black')
update()
def move():
bird.y -= 5
for ball in balls:
ball.x -= 3
if randrange(10) == 0:
y = randrange(-199, 199)
ball = vector(199, y)
balls.append(ball)
while len(balls) > 0 and not inside(balls[0]):
balls.pop(0)
if not inside(bird):
draw(False)
return
for ball in balls:
if abs(ball - bird) < 15:
draw(False)
return
draw(True)
ontimer(move, 50)
setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(fly)
move()
done()