如何用Python写贪吃蛇
时间: 2024-03-06 18:51:16 浏览: 57
用python写的简易贪吃蛇
可以使用Python中的Pygame模块来实现贪吃蛇游戏。以下是一个简单的贪吃蛇游戏的代码示例:
```python
import pygame
import time
import random
pygame.init()
# 设置窗口大小
window_width = 800
window_height = 600
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏区域大小
block_size = 20
game_area_width = window_width - block_size * 2
game_area_height = window_height - block_size * 2
# 初始化游戏区域
game_area = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇游戏')
# 设置字体
font = pygame.font.SysFont(None, 25)
# 定义函数,显示消息
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_area.blit(screen_text, [window_width / 2, window_height / 2])
# 定义函数,绘制蛇
def draw_snake(snake_list, block_size):
for xys in snake_list:
pygame.draw.rect(game_area, black, [xys[0], xys[1], block_size, block_size])
# 定义函数,运行游戏
def game_loop():
game_over = False
game_close = False
# 初始化蛇的位置和长度
lead_x = game_area_width / 2
lead_y = game_area_height / 2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 初始化食物的位置
food_x = round(random.randrange(block_size, game_area_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(block_size, game_area_height - block_size) / 10.0) * 10.0
while not game_over:
while game_close == True:
game_area.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:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
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 >= game_area_width or lead_x < 0 or lead_y >= game_area_height or lead_y < 0:
game_close = True
# 移动蛇的位置
lead_x += lead_x_change
lead_y += lead_y_change
game_area.fill(white)
pygame.draw.rect(game_area, 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) > snake_length:
del snake_list[0]
for each_segment in snake_list[:-1]:
if each_segment == snake_head:
game_close = True
draw_snake(snake_list, block_size)
pygame.display.update()
# 如果蛇吃到了食物,更新食物的位置,并增加蛇的长度
if lead_x == food_x and lead_y == food_y:
food_x = round(random.randrange(block_size, game_area_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(block_size, game_area_height - block_size) / 10.0) * 10.0
snake_length += 1
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(15)
pygame.quit()
quit()
game_loop()
```
运行上述代码,即可打开一个简单的贪吃蛇游戏窗口。玩家可以使用方向键控制蛇的移动,蛇吃到食物后会增加长度,当蛇碰到边界或自己时游戏结束。
阅读全文