python写贪吃蛇游戏
时间: 2023-07-07 19:44:36 浏览: 38
Python编写一个贪吃蛇游戏
好的,以下是一个简单的 Python 贪吃蛇游戏的代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
window_width = 500
window_height = 500
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇和食物的大小
block_size = 10
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义函数,用于显示文字
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
window.blit(screen_text, [window_width/2, window_height/2])
# 定义主函数
def gameLoop():
# 定义游戏结束变量
game_over = False
# 定义蛇的初始位置和长度
lead_x = window_width/2
lead_y = window_height/2
lead_x_change = 0
lead_y_change = 0
snake_List = []
Length_of_snake = 1
# 定义食物的初始位置
food_x = round(random.randrange(0, window_width-block_size)/10.0)*10.0
food_y = round(random.randrange(0, window_height-block_size)/10.0)*10.0
# 游戏循环
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:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
# 判断蛇是否撞到边界
if lead_x >= window_width or lead_x < 0 or lead_y >= window_height or lead_y < 0:
game_over = True
# 移动蛇的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制背景和食物
window.fill(white)
pygame.draw.rect(window, red, [food_x, food_y, block_size, block_size])
# 绘制蛇
snake_Head = []
snake_Head.append(lead_x)
snake_Head.append(lead_y)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for segment in snake_List[:-1]:
if segment == snake_Head:
game_over = True
for segment in snake_List:
pygame.draw.rect(window, black, [segment[0], segment[1], block_size, block_size])
pygame.display.update()
# 判断是否吃到了食物
if lead_x == food_x and lead_y == food_y:
food_x = round(random.randrange(0, window_width-block_size)/10.0)*10.0
food_y = round(random.randrange(0, window_height-block_size)/10.0)*10.0
Length_of_snake += 1
# 设置游戏帧率
clock = pygame.time.Clock()
clock.tick(15)
# 退出 Pygame
pygame.quit()
quit()
# 运行游戏
gameLoop()
```
这个程序使用 Pygame 模块实现了一个简单的贪吃蛇游戏。玩家通过控制方向键移动蛇,吃掉食物来增加蛇的长度,直到蛇撞到边界或者自己的身体时游戏结束。
阅读全文