用python编写一个贪吃蛇游戏,要求要有主函数,且各模块功能由不同函数实现
时间: 2024-02-22 18:00:21 浏览: 51
基于python的贪吃蛇源码.zip
好的,我可以为您提供一个简单的贪吃蛇游戏的代码,如下所示:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义游戏窗口的宽度和高度
width, height = 640, 480
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义贪吃蛇的初始位置和大小
snake_pos = [100, 50]
snake_size = [20, 20]
# 定义食物的初始位置和大小
food_pos = [random.randrange(1, width // 20) * 20, random.randrange(1, height // 20) * 20]
food_size = [20, 20]
# 定义贪吃蛇的移动速度
snake_speed = 20
# 定义贪吃蛇的初始移动方向
direction = "right"
# 定义贪吃蛇的身体列表
snake_body = [snake_pos]
# 定义游戏结束的标志
game_over = False
# 定义得分
score = 0
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义主函数
def main():
global game_over, direction, snake_pos, food_pos, snake_body, score
# 游戏循环
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:
direction = "left"
elif event.key == pygame.K_RIGHT:
direction = "right"
elif event.key == pygame.K_UP:
direction = "up"
elif event.key == pygame.K_DOWN:
direction = "down"
# 移动贪吃蛇
if direction == "right":
snake_pos[0] += snake_speed
elif direction == "left":
snake_pos[0] -= snake_speed
elif direction == "up":
snake_pos[1] -= snake_speed
elif direction == "down":
snake_pos[1] += snake_speed
# 判断贪吃蛇是否吃到食物
if snake_pos == food_pos:
food_pos = [random.randrange(1, width // 20) * 20, random.randrange(1, height // 20) * 20]
score += 1
snake_body.append(snake_pos)
# 更新贪吃蛇的身体列表
snake_body.insert(0, list(snake_pos))
if len(snake_body) > score + 1:
snake_body.pop()
# 检测贪吃蛇是否碰到墙壁或自己
if snake_pos[0] < 0 or snake_pos[0] > width - snake_size[0] or snake_pos[1] < 0 or snake_pos[1] > height - snake_size[1]:
game_over = True
for block in snake_body[1:]:
if snake_pos == block:
game_over = True
# 绘制游戏界面
screen.fill(white)
pygame.draw.rect(screen, green, [food_pos[0], food_pos[1], food_size[0], food_size[1]])
for block in snake_body:
pygame.draw.rect(screen, black, [block[0], block[1], snake_size[0], snake_size[1]])
text = font.render("Score: " + str(score), True, black)
screen.blit(text, [0, 0])
pygame.display.update()
# 退出pygame
pygame.quit()
# 调用主函数
if __name__ == "__main__":
main()
```
以上代码使用pygame库实现了一个简单的贪吃蛇游戏。在游戏中,玩家通过控制贪吃蛇的移动方向,让它吃到食物,得到分数。如果贪吃蛇碰到墙壁或自己,游戏结束。游戏界面中显示当前得分。
阅读全文