用Python如何写一个贪吃蛇游戏
时间: 2024-04-25 18:06:29 浏览: 91
Python编写一个贪吃蛇游戏
你可以使用Python的pygame模块来编写贪吃蛇游戏。以下是一个简单的示例代码:
```
import pygame
import time
import random
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏窗口
width = 800
height = 600
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇游戏')
# 设置游戏时钟
clock = pygame.time.Clock()
block_size = 10
# 定义字体
font_style = pygame.font.SysFont(None, 50)
def message(msg, color):
"""
显示消息
:param msg: 消息
:param color: 字体颜色
"""
message_surface = font_style.render(msg, True, color)
gameDisplay.blit(message_surface, [width / 6, height / 3])
def gameLoop():
# 初始化贪吃蛇位置和移动方向
lead_x = width / 2
lead_y = height / 2
lead_x_change = 0
lead_y_change = 0
# 初始化食物位置
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0
gameExit = False
gameOver = False
while not gameExit:
while gameOver:
gameDisplay.fill(white)
message("游戏结束,按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
if 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 >= width or lead_x < 0 or lead_y >= height or lead_y < 0:
gameOver = True
# 移动贪吃蛇
lead_x += lead_x_change
lead_y += lead_y_change
# 填充背景色
gameDisplay.fill(white)
# 画食物
pygame.draw.rect(gameDisplay, red, [food_x, food_y, block_size, block_size])
# 画贪吃蛇
pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
# 判断贪吃蛇是否吃到了食物
if lead_x == food_x and lead_y == food_y:
food_x = round(random.randrange(0, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0
pygame.display.update()
# 设置游戏时钟,控制游戏速度
clock.tick(15)
# 退出pygame
pygame.quit()
# 退出程序
quit()
gameLoop()
```
希望能对你有所帮助!
阅读全文