144
社区成员
课程:《Python程序设计》
班级: 2233
姓名: 刘志轩
学号:20223326
实验教师:王志强
实验日期:2023年5月11日
必修/选修: 公选课
1.实验内容
Python综合应用:爬虫、数据处理、可视化、机器学习、神经网络、游戏、网络安全等
贪吃蛇
2.实验过程及结果
代码:
1.导入模块以及进行初始化
Import random
import pygame
import sys
from pygame. Locals import*
2.设置游戏界面的边框大小
Window_Width = 800
Window_Height = 500 # 屏幕大小
Display_Clock = 5 # 刷新频率
3.定义颜色
食物显示及颜色
def Show_Apple(coord):
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
apple_Rect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(Main_Display, (255, 0, 0), apple_Rect)
定义背景颜色画网格
# 画网格
def draw_Grid():
# 垂直方向
for x in range(0, Window_Width, Cell_Size):
pygame.draw.line(Main_Display, (40, 40, 40), (x, 0), (x, Window_Height))
# 水平方向
for y in range(0, Window_Height, Cell_Size):
pygame.draw.line(Main_Display, (40, 40, 40), (0, y), (Window_Width, y))
游戏结束字体以及分数字体颜色
title_Font = pygame.font.Font('simkai.ttf', 100)
title_game = title_Font.render('Game', True, (233, 150, 122))
title_over = title_Font.render('Over', True, (233, 150, 122))
game_Rect = title_game.get_rect()
over_Rect = title_over.get_rect() # 结束时显示GAME OVER
game_Rect.midtop = (Window_Width/2, 70)
over_Rect.midtop = (Window_Width/2, game_Rect.height+70+25)
Main_Display.blit(title_game, game_Rect)
Main_Display.blit(title_over, over_Rect)
pressKey_content = Main_Font.render('按任意键开始游戏!', True, (255, 255, 255))
pressKey_Rect = pressKey_content.get_rect()
pressKey_Rect.topleft = (Window_Width-200, Window_Height-30)
Main_Display.blit(pressKey_content, pressKey_Rect)
pygame.display.update()
pygame.time.wait(500)
Check_PressKey()
Cell_Size = 20 # 蛇身大小
assert Window_Width % Cell_Size == 0
assert Window_Height % Cell_Size == 0 # 断言预判
Cell_W = int(Window_Width/Cell_Size)
Cell_H = int(Window_Height/Cell_Size) # 等价的运动区域大小
Background_Color = (0, 0, 0) # 背景颜色
Head_index = 0 # 蛇头索引
# 关闭游戏界面
def close_game():
pygame.quit()
sys.exit()
# 检测按键
def Check_PressKey():
if len(pygame.event.get(QUIT)) > 0:
close_game() # 结束
KeyUp_Events = pygame.event.get(KEYUP)
if len(KeyUp_Events) == 0:
return None # 未响应
elif KeyUp_Events[0].key == K_ESCAPE:
close_game()
return KeyUp_Events[0].key
def Show_Score(score):
score_Content = Main_Font.render('得分:%s' % (score), True, (255, 255, 255))
score_Rect = score_Content.get_rect()
score_Rect.topleft = (Window_Width-120, 10) # 窗体位置
Main_Display.blit(score_Content, score_Rect)
title_Font = pygame.font.Font('simkai.ttf', 100)
title_game = title_Font.render('Game', True, (233, 150, 122))
title_over = title_Font.render('Over', True, (233, 150, 122))
game_Rect = title_game.get_rect()
over_Rect = title_over.get_rect() # 结束时显示GAME OVER
game_Rect.midtop = (Window_Width/2, 70)
over_Rect.midtop = (Window_Width/2, game_Rect.height+70+25)
Main_Display.blit(title_game, game_Rect)
Main_Display.blit(title_over, over_Rect)
pressKey_content = Main_Font.render('按任意键开始游戏!', True, (255, 255, 255))
pressKey_Rect = pressKey_content.get_rect()
pressKey_Rect.topleft = (Window_Width-200, Window_Height-30)
Main_Display.blit(pressKey_content, pressKey_Rect)
pygame.display.update()
pygame.time.wait(500)
Check_PressKey()
pygame.mixer.init() # 游戏背景音乐
pygame.mixer.music.load("D:\贪吃蛇小游戏/end.wav")
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
while True:
if Check_PressKey():
pygame.event.get()
return
return
按键检测
# 检测按键
def Check_PressKey():
if len(pygame.event.get(QUIT)) > 0:
close_game() # 结束
KeyUp_Events = pygame.event.get(KEYUP)
if len(KeyUp_Events) == 0:
return None # 未响应
elif KeyUp_Events[0].key == K_ESCAPE:
close_game()
return KeyUp_Events[0].key
def Run_Game():
# 蛇出生地
start_x = random.randint(5, Cell_W-6)
start_y = random.randint(5, Cell_H-6)
snake_Coords = [{'x': start_x, 'y': start_y},
{'x': start_x-1, 'y': start_y},
{'x': start_x-2, 'y': start_y}]
direction = 'right'
apple_location = Get_Apple_Location(snake_Coords)
while True:
for event in pygame.event.get():
if event.type == QUIT:
close_game()
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:
close_game()
确定方向,当蛇在运行时不可掉头
# 碰到墙壁或者自己则游戏结束
if (snake_Coords[Head_index]['x'] == -1) or (snake_Coords[Head_index]['x'] == Cell_W) or \
(snake_Coords[Head_index]['y'] == -1) or (snake_Coords[Head_index]['y'] == Cell_H):
return
if snake_Coords[Head_index] in snake_Coords[1:]:
return
if (snake_Coords[Head_index]['x'] == apple_location['x']) and (snake_Coords[Head_index]['y'] == apple_location['y']):
apple_location = Get_Apple_Location(snake_Coords)
else:
del snake_Coords[-1]
移动时的距离为一个食物或者一个蛇头的距离
if direction == 'up':
newHead = {'x': snake_Coords[Head_index]['x'],
'y': snake_Coords[Head_index]['y']-1}
elif direction == 'down':
newHead = {'x': snake_Coords[Head_index]['x'],
'y': snake_Coords[Head_index]['y']+1}
elif direction == 'left':
newHead = {'x': snake_Coords[Head_index]['x']-1,
'y': snake_Coords[Head_index]['y']}
elif direction == 'right':
newHead = {'x': snake_Coords[Head_index]['x']+1,
'y': snake_Coords[Head_index]['y']}
snake_Coords.insert(0, newHead)
Main_Display.fill(Background_Color)
draw_Grid()
Show_Snake(snake_Coords)
Show_Apple(apple_location)
Show_Score(len(snake_Coords)-3)
pygame.display.update() # 刷新
Snake_Clock.tick(Display_Clock)
8设置蛇通过与食物的位置重合判断是否吃了食物,此时蛇长度加一
snake_Coords.insert(0, newHead)
Main_Display.fill(Background_Color)
draw_Grid()
Show_Snake(snake_Coords)
Show_Apple(apple_location)
Show_Score(len(snake_Coords)-3)
pygame.display.update() # 刷新
Snake_Clock.tick(Display_Clock)
食物消失同时随机出现
# 获得食物位置
def Get_Apple_Location(snake_Coords):
flag = True
while flag:
apple_location = {'x': random.randint(0, Cell_W-1),
random.randint(0, Cell_H-1)}
if apple_location not in snake_Coords: # 若食物不在界面返回再生成
flag = False
return apple_location
# 显示食物
def Show_Apple(coord):
x = coord['x'] * Cell_Size
y = coord['y'] * Cell_Size
apple_Rect = pygame.Rect(x, y, Cell_Size, Cell_Size)
pygame.draw.rect(Main_Display, (255, 0, 0), apple_Rect)
def main():
global Main_Display, Main_Font, Snake_Clock
pygame.init()
Snake_Clock = pygame.time.Clock()
Main_Display = pygame.display.set_mode((Window_Width, Window_Height))
Main_Font = pygame.font.Font('simkai.ttf', 18)
pygame.display.set_caption('贪吃蛇小游戏')
Show_Start_Interface()
while True:
Run_Game()
Show_End_Interface()
pygame.mixer.init() # 游戏背景音乐
pygame.mixer.music.load("D:\贪吃蛇小游戏/background.wav")
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
if __name__ == '__main__':
main()
运行结果:
上传至码云:
实验过程中遇到的问题和解决过程:
问题一:未安装pygame
解决方式:寻求老师帮助下载pygame
问题二:对一些函数不是太清楚
解决方式:通过在网上查阅资料解决
三、 总结体会:
通过这阶段的学习,随着对Python学习的不断深入,python语言的逻辑规则和上学期学习的C语言存在很大的相似之处,在对数据进行处理时有种似曾相识之感。用python实现贪吃蛇游戏 ,发现python非常灵活,应用比较广泛,通过加载模块,可以完成许多功能。看了一些关于基于贪吃蛇的python的各种方法,最后进行的完整的实现,当然,本游戏也有一些的不足,比如没有随着时间流动蛇的速度应该有所增加、未能实现高分榜等等,总的来说,不论哪种语言,编写不同场景下的应用都是快速提升的不二法门,以后要多动手,强化自己的思维,提升能力,为以后的学习奠定基础。