用python写一个贪吃蛇程序
时间: 2023-11-23 20:07:55 浏览: 54
好的,下面是一个简单的贪吃蛇程序:
```python
import pygame
from pygame.locals import *
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小和标题
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义贪吃蛇方块大小和速度
BLOCK_SIZE = 20
SNAKE_SPEED = 5
# 定义字体和字体大小
FONT = pygame.font.SysFont(None, 48)
# 定义贪吃蛇初始位置和长度
snake_head = [100, 100]
snake_body = [[100, 100], [80, 100], [60, 100]]
# 定义食物位置
food_pos = [random.randrange(1, (WINDOW_WIDTH // BLOCK_SIZE)) * BLOCK_SIZE,
random.randrange(1, (WINDOW_HEIGHT // BLOCK_SIZE)) * BLOCK_SIZE]
# 定义初始方向
direction = 'RIGHT'
# 定义游戏结束标志
game_over = False
# 定义更新贪吃蛇位置函数
def update_snake():
global snake_head
global snake_body
global food_pos
global direction
if direction == 'RIGHT':
snake_head[0] += BLOCK_SIZE
elif direction == 'LEFT':
snake_head[0] -= BLOCK_SIZE
elif direction == 'UP':
snake_head[1] -= BLOCK_SIZE
elif direction == 'DOWN':
snake_head[1] += BLOCK_SIZE
snake_body.insert(0, list(snake_head))
if snake_head == food_pos:
food_pos = [random.randrange(1, (WINDOW_WIDTH // BLOCK_SIZE)) * BLOCK_SIZE,
random.randrange(1, (WINDOW_HEIGHT // BLOCK_SIZE)) * BLOCK_SIZE]
else:
snake_body.pop()
# 定义检查贪吃蛇是否撞到墙或自己的函数
def check_collision():
global snake_head
global snake_body
global game_over
if snake_head[0] >= WINDOW_WIDTH or snake_head[0] < 0 or snake_head[1] >= WINDOW_HEIGHT or snake_head[1] < 0:
game_over = True
for block in snake_body[1:]:
if snake_head == block:
game_over = True
# 定义绘制贪吃蛇和食物的函数
def draw_snake_and_food():
global snake_head
global snake_body
global food_pos
window.fill(BLACK)
for block in snake_body:
pygame.draw.rect(window, GREEN, Rect(block[0], block[1], BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(window, RED, Rect(food_pos[0], food_pos[1], BLOCK_SIZE, BLOCK_SIZE))
# 定义游戏循环
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT and direction != 'LEFT':
direction = 'RIGHT'
elif event.key == K_LEFT and direction != 'RIGHT':
direction = 'LEFT'
elif event.key == K_UP and direction != 'DOWN':
direction = 'UP'
elif event.key == K_DOWN and direction != 'UP':
direction = 'DOWN'
update_snake()
check_collision()
draw_snake_and_food()
if game_over:
text = FONT.render('Game Over', True, WHITE)
window.blit(text, (WINDOW_WIDTH // 2 - text.get_width() // 2, WINDOW_HEIGHT // 2 - text.get_height() // 2))
pygame.display.update()
pygame.time.wait(3000)
pygame.quit()
exit()
pygame.display.update()
pygame.time.Clock().tick(SNAKE_SPEED)
```
运行程序后,按方向键控制贪吃蛇的移动。当贪吃蛇撞到墙或自己时,游戏结束并显示“Game Over”。
阅读全文