用python写一个贪吃蛇的游戏代码
时间: 2024-04-23 13:04:08 浏览: 93
好的,下面是一个简单的Python贪吃蛇游戏代码示例,使用Python 3和Pygame库:
```
import pygame
import random
# 初始化Pygame
pygame.init()
# 定义游戏画面大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 创建游戏画面
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义贪吃蛇和食物的大小
BLOCK_SIZE = 20
# 定义字体
font = pygame.font.SysFont(None, 25)
def snake(block_size, snake_list):
for x_y in snake_list:
pygame.draw.rect(screen, GREEN, [x_y[0], x_y[1], block_size, block_size])
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [SCREEN_WIDTH/2, SCREEN_HEIGHT/2])
# 游戏循环
def gameLoop():
gameExit = False
gameOver = False
# 定义贪吃蛇初始位置和长度
lead_x = SCREEN_WIDTH/2
lead_y = SCREEN_HEIGHT/2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 定义食物初始位置
randAppleX = round(random.randrange(0, SCREEN_WIDTH - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
randAppleY = round(random.randrange(0, SCREEN_HEIGHT - BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE
while not gameExit:
while gameOver == True:
screen.fill(WHITE)
message_to_screen("游戏结束,按Q退出或者按C重新开始游戏", RED)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
elif event.key == pygame.K_c:
gameLoop()
# 处理键盘事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = 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 >= SCREEN_WIDTH or lead_x < 0 or lead_y >= SCREEN_HEIGHT or lead_y < 0:
gameOver = True
# 更新贪吃蛇的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制背
阅读全文