Python课程设计贪吃蛇游戏
时间: 2023-12-14 11:33:24 浏览: 186
贪食蛇游戏课程设计
以下是Python课程设计贪吃蛇游戏的简要介绍:
贪吃蛇游戏是一款经典的游戏,玩家通过控制蛇的移动方向,使其吃到食物并不断变长,直到撞到墙壁或自己的身体为止。Python可以使用Pygame等库来实现贪吃蛇游戏。
以下是一个简单的Python贪吃蛇游戏的代码示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义游戏窗口大小
width = 600
height = 400
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')
# 定义蛇的初始位置和大小
snake_block = 10
snake_speed = 15
x1 = width / 2
y1 = height / 2
# 定义食物的初始位置
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
# 定义蛇的移动方向
x1_change = 0
y1_change = 0
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义显示分数的函数
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [width / 6, height / 6])
# 游戏循环
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 判断蛇是否撞到墙壁
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_over = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制游戏窗口
screen.fill(black)
pygame.draw.rect(screen, red, [foodx, foody, snake_block, snake_block])
pygame.draw.rect(screen, white, [x1, y1, snake_block, snake_block])
pygame.display.update()
# 判断蛇是否吃到食物
if x1 == foodx and y1 == foody:
print('Yummy!!')
pygame.display.update()
# 退出Pygame
pygame.quit()
```
阅读全文