144
社区成员




课程:《Python程序设计》
班级: 2222
姓名: 陈彦竹
学号:20222220
实验教师:王志强
实验日期:2023年5月25日
必修/选修: 公选课
编写贪吃蛇小游戏
贪食蛇(也叫贪吃蛇)是一款经典的小游戏,它游戏操作简单,可玩性比较高。
在游戏中,玩家使用方向键操控一条长长的蛇不断吞下豆子,同时蛇身随着吞下的豆子不断变长,当蛇头撞到蛇身或障壁时游戏结束。
1.主函数
主要承担一些游戏窗口的初始化工作,以及调用相关函数运行游戏
def main():
pygame.init() # 模块初始化
snake_speed_clock = pygame.time.Clock()
screen = pygame.display.set_mode((windows_width, windows_height))
screen.fill(white)
pygame.display.set_caption("贪吃蛇")
show_start_info(screen)
while True:
running_game(screen, snake_speed_clock)
show_gameover_info(screen)
2.初始化界面
def show_start_info(screen):
font = pygame.font.Font('myfont.ttf', 40)
tip = font.render('按任意键开始游戏', True, (65, 105, 225))
gamestart = pygame.image.load('gamestart.png')
screen.blit(gamestart, (140, 30))
screen.blit(tip, (240, 550))
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_ESCAPE):
terminate()
else:
return
3.游戏运行主体
def running_game(screen,snake_speed_clock):
startx = random.randint(3, map_width - 8) #开始位置
starty = random.randint(3, map_height - 8)
snake_coords = [{'x': startx, 'y': starty}, #初始贪吃蛇
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]
direction = RIGHT # 开始时向右移动
food = get_random_location() #实物随机位置
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
move_snake(direction, snake_coords) #移动蛇
ret = snake_is_alive(snake_coords)
if not ret:
break #游戏结束
snake_is_eat_food(snake_coords, food) #判断蛇是否吃到食物
screen.fill(BG_COLOR)
#draw_grid(screen)
draw_snake(screen, snake_coords)
draw_food(screen, food)
draw_score(screen, len(snake_coords) - 3)
pygame.display.update()
snake_speed_clock.tick(snake_speed)
4.贪吃蛇的移动
def move_snake(direction, snake_coords):
if direction == UP:
newHead = {'x': snake_coords[HEAD]['x'], 'y': snake_coords[HEAD]['y'] - 1}
elif direction == DOWN:
newHead = {'x': snake_coords[HEAD]['x'], 'y': snake_coords[HEAD]['y'] + 1}
elif direction == LEFT:
newHead = {'x': snake_coords[HEAD]['x'] - 1, 'y': snake_coords[HEAD]['y']}
elif direction == RIGHT:
newHead = {'x': snake_coords[HEAD]['x'] + 1, 'y': snake_coords[HEAD]['y']}
snake_coords.insert(0, newHead)
5.判断贪吃蛇是否死亡
def snake_is_alive(snake_coords):
tag = True
if snake_coords[HEAD]['x'] == -1 or snake_coords[HEAD]['x'] == map_width or snake_coords[HEAD]['y'] == -1 or \
snake_coords[HEAD]['y'] == map_height:
tag = False # 蛇碰壁
for snake_body in snake_coords[1:]:
if snake_body['x'] == snake_coords[HEAD]['x'] and snake_body['y'] == snake_coords[HEAD]['y']:
tag = False # 蛇碰到自己身体
return tag
6.判断贪吃蛇是否吃到食物
def snake_is_eat_food(snake_coords, food):
if snake_coords[HEAD]['x'] == food['x'] and snake_coords[HEAD]['y'] == food['y']:
food['x'] = random.randint(0, map_width - 1)
food['y'] = random.randint(0, map_height - 1) # 实物位置重新设置
else:
del snake_coords[-1] # 如果没有吃到实物, 就向前移动, 那么尾部一格删掉
7.画出贪吃蛇
def draw_snake(screen, snake_coords):
for coord in snake_coords:
x = coord['x'] * cell_size
y = coord['y'] * cell_size
wormSegmentRect = pygame.Rect(x, y, cell_size, cell_size)
pygame.draw.rect(screen, dark_blue, wormSegmentRect)
wormInnerSegmentRect = pygame.Rect(
x + 4, y + 4, cell_size - 8, cell_size - 8)
pygame.draw.rect(screen, blue, wormInnerSegmentRect)
8.画出食物
def draw_food(screen, food):
x = food['x'] * cell_size
y = food['y'] * cell_size
appleRect = pygame.Rect(x, y, cell_size, cell_size)
pygame.draw.rect(screen, Red, appleRect)
9.计算并显示出成绩
def draw_score(screen,score):
font = pygame.font.Font('myfont.ttf', 30)
scoreSurf = font.render('得分: %s' % score, True, Green)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (windows_width - 120, 10)
screen.blit(scoreSurf, scoreRect)
完整代码
import random
import pygame
import sys
from pygame.locals import *
snake_speed = 15 #贪吃蛇的速度
windows_width = 800
windows_height = 600 #游戏窗口的大小
cell_size = 20 #贪吃蛇身体方块大小
#初始化区
map_width = int(windows_width / cell_size)
map_height = int(windows_height / cell_size)
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
gray = (230, 230, 230)
dark_gray = (40, 40, 40)
DARKGreen = (0, 155, 0)
Green = (0, 255, 0)
Red = (255, 0, 0)
blue = (0, 0, 255)
dark_blue =(0,0, 139)
BG_COLOR = black #游戏背景颜色
# 定义方向
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
HEAD = 0 #贪吃蛇头部下标
#主函数
def main():
pygame.init() # 模块初始化
snake_speed_clock = pygame.time.Clock() # 创建Pygame时钟对象
screen = pygame.display.set_mode((windows_width, windows_height)) #
screen.fill(white)
pygame.display.set_caption("Python 贪吃蛇小游戏") #设置标题
show_start_info(screen) #欢迎信息
while True:
running_game(screen, snake_speed_clock)
show_gameover_info(screen)
#游戏运行主体
def running_game(screen,snake_speed_clock):
startx = random.randint(3, map_width - 8) #开始位置
starty = random.randint(3, map_height - 8)
snake_coords = [{'x': startx, 'y': starty}, #初始贪吃蛇
{'x': startx - 1, 'y': starty},
{'x': startx - 2, 'y': starty}]
direction = RIGHT # 开始时向右移动
food = get_random_location()
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
move_snake(direction, snake_coords)
ret = snake_is_alive(snake_coords)
if not ret:
break #游戏结束
snake_is_eat_food(snake_coords, food) #判断蛇是否吃到食物
screen.fill(BG_COLOR)
#draw_grid(screen)
draw_snake(screen, snake_coords)
draw_food(screen, food)
draw_score(screen, len(snake_coords) - 3)
pygame.display.update()
snake_speed_clock.tick(snake_speed)
#将食物画出来
def draw_food(screen, food):
x = food['x'] * cell_size
y = food['y'] * cell_size
appleRect = pygame.Rect(x, y, cell_size, cell_size)
pygame.draw.rect(screen, Red, appleRect)
#将贪吃蛇画出来
def draw_snake(screen, snake_coords):
for coord in snake_coords:
x = coord['x'] * cell_size
y = coord['y'] * cell_size
wormSegmentRect = pygame.Rect(x, y, cell_size, cell_size)
pygame.draw.rect(screen, dark_blue, wormSegmentRect)
wormInnerSegmentRect = pygame.Rect( #蛇身子里面的第二层亮绿色
x + 4, y + 4, cell_size - 8, cell_size - 8)
pygame.draw.rect(screen, blue, wormInnerSegmentRect)
#画网格
def draw_grid(screen):
for x in range(0, windows_width, cell_size): # draw 水平 lines
pygame.draw.line(screen, dark_gray, (x, 0), (x, windows_height))
for y in range(0, windows_height, cell_size): # draw 垂直 lines
pygame.draw.line(screen, dark_gray, (0, y), (windows_width, y))
#移动贪吃蛇
def move_snake(direction, snake_coords):
if direction == UP:
newHead = {'x': snake_coords[HEAD]['x'], 'y': snake_coords[HEAD]['y'] - 1}
elif direction == DOWN:
newHead = {'x': snake_coords[HEAD]['x'], 'y': snake_coords[HEAD]['y'] + 1}
elif direction == LEFT:
newHead = {'x': snake_coords[HEAD]['x'] - 1, 'y': snake_coords[HEAD]['y']}
elif direction == RIGHT:
newHead = {'x': snake_coords[HEAD]['x'] + 1, 'y': snake_coords[HEAD]['y']}
snake_coords.insert(0, newHead)
#判断蛇死了没
def snake_is_alive(snake_coords):
tag = True
if snake_coords[HEAD]['x'] == -1 or snake_coords[HEAD]['x'] == map_width or snake_coords[HEAD]['y'] == -1 or \
snake_coords[HEAD]['y'] == map_height:
tag = False # 蛇碰壁
for snake_body in snake_coords[1:]:
if snake_body['x'] == snake_coords[HEAD]['x'] and snake_body['y'] == snake_coords[HEAD]['y']:
tag = False # 蛇碰到自己身体
return tag
#判断贪吃蛇是否吃到食物
def snake_is_eat_food(snake_coords, food):
if snake_coords[HEAD]['x'] == food['x'] and snake_coords[HEAD]['y'] == food['y']:
food['x'] = random.randint(0, map_width - 1)
food['y'] = random.randint(0, map_height - 1) # 实物位置重新设置
else:
del snake_coords[-1] # 如果没有吃到实物, 就向前移动, 那么尾部一格删掉
#食物随机生成
def get_random_location():
return {'x': random.randint(0, map_width - 1), 'y': random.randint(0, map_height - 1)}
#开始信息显示
def show_start_info(screen):
font = pygame.font.Font('myfont.ttf', 40)
tip = font.render('按任意键开始游戏~~~', True, (65, 105, 225))
gamestart = pygame.image.load('gamestart.png')
screen.blit(gamestart, (140, 30))
screen.blit(tip, (240, 550))
pygame.display.update()
while True: #键盘监听事件
for event in pygame.event.get(): # event handling loop
if event.type == QUIT:
terminate() #终止程序
elif event.type == KEYDOWN:
if (event.key == K_ESCAPE): #终止程序
terminate() #终止程序
else:
return #结束此函数, 开始游戏
#游戏结束信息显示
def show_gameover_info(screen):
font = pygame.font.Font('myfont.ttf', 40)
tip = font.render('按Q或者ESC退出游戏, 按任意键重新开始游戏', True, (65, 105, 225))
gamestart = pygame.image.load('gameover.png')
screen.blit(gamestart, (60, 0))
screen.blit(tip, (80, 300))
pygame.display.update()
while True:
for event in pygame.event.get(): # event handling loop
if event.type == QUIT:
terminate() #终止程序
elif event.type == KEYDOWN:
if event.key == K_ESCAPE or event.key == K_q: #终止程序
terminate() #终止程序
else:
return #结束此函数, 重新开始游戏
#画成绩
def draw_score(screen,score):
font = pygame.font.Font('myfont.ttf', 30)
scoreSurf = font.render('得分: %s' % score, True, Green)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (windows_width - 120, 10)
screen.blit(scoreSurf, scoreRect)
#程序终止
def terminate():
pygame.quit()
sys.exit()
main()
问题1:在实验的过程中,我发现自己对pycharm包的运用非常不熟悉
问题1解决方案:多多看书,同时借鉴网上的一些资料
...
实验四感想体会
这一次的实验是这个学期Python公选课的最后一次实验,它的实验时间与前三次实验的时间想必也是最长的。这次我选择做的是贪吃蛇小游戏的程序,因为我自己也很喜欢完贪吃蛇这个游戏,所以想要去更多的了解它,而不仅仅是知道或熟悉它的玩法,了解它的技巧。经过这一次的实验,我对最最基础的贪吃蛇游戏的程序有了一个基础的了解,知道了如何编写多个函数来完成贪吃蛇小游戏的基本操作。
这次试验的过程中,我对Python各个知识点也有了更深的理解,因为在程序的编写过程中需要不断地去运用这些课堂上讲过的知识。通过这次试验,我能更好地、更熟练地运用这些知识了。
课程感想体会
最开始在选择选修课的时候,我抱着试一试的心态报名了Python这门课程。后来在课堂的学习过程中,我学习到了Python的很多知识,从最基础的 if-else语句、函数定义到后面的爬虫、socket编程技术等知识,收获颇丰。
通过这一学期的学习,我主要了解了以下知识:
(1)Python的流程控制语句(包括选择语句(if、if-else等)、循环语句(while循环、for循环等))
(2)对序列、列表、元组、字典、集合的学习和运用
(3)对字符串,以及正则表达式的学习和运用
(4)面向对象的程序设计(类、属性、封装、继承、多态)
(5)对于模块的学习以及运用(Python包、异常处理(try...except...finally语句、raise语句、assert语句)等内容)
(6)Socket网络编程技术
(7)文件及目录的操作(文件的打开和关闭、写入内容等操作)
(8)数据库的学习(增、删、改、查)
(9)网络爬虫技术
在刚刚开始学习的过程中,我就发现Python和C语言有很多相似之处,也有很多不同点。例如Python中有如for、while这样的选择语句,C语言中也有;但又如Python中的循环嵌套语句为“while 条件表达式: ”,而C语言中循环嵌套语句则表示为“while (条件表达式)”,这些细微的差别在第一节课就给我留下了深刻的印象。
后来随着学习的深入,我对Python有了更多的、更深入的了解和认识,课堂上老师的讲解很细致,课堂中也穿插了很多有趣的元素,让课堂氛围不那么压抑,比较轻松活跃。推送,后面几节课所介绍的内容(Socket编程技术,数据库,网络爬虫技术等)都与现实生活有较多的较大的联系,也激发了我对这些知识的好奇心与学习的积极性。