python代码完成贪吃蛇
时间: 2023-07-02 17:10:52 浏览: 91
150行python代码实现贪吃蛇游戏
好的,以下是一个简单的 Python 贪吃蛇游戏代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口大小
width = 500
height = 500
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 创建游戏窗口
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义蛇的大小
block_size = 10
# 定义字体
font = pygame.font.SysFont(None, 25)
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_display.blit(screen_text, [width / 6, height / 3])
def game_loop():
game_exit = False
game_over = False
# 蛇头的位置
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
# 蛇的长度
snake_list = []
snake_length = 1
# 游戏循环
while not game_exit:
while game_over:
game_display.fill(white)
message_to_screen('Game over! Press Q to quit or C to play again', red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = 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:
game_over = True
# 更新蛇头的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制食物
game_display.fill(white)
pygame.draw.rect(game_display, blue, [food_x, food_y, block_size, block_size])
# 绘制蛇身体
snake_head = [lead_x, lead_y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
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(game_display, green, [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, width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - block_size) / 10.0) * 10.0
snake_length += 1
# 设置游戏帧率
clock.tick(15)
# 退出Pygame
pygame.quit()
# 退出Python
quit()
game_loop()
```
运行代码后,你就可以开始玩贪吃蛇了!
阅读全文