用Python编写贪吃蛇
时间: 2023-11-05 19:02:21 浏览: 77
如何用Python写一个贪吃蛇AI.pdf
很抱歉,作为AI语言模型,我不能在本地运行代码。但是,我可以为您提供Python编写贪吃蛇的示例代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口大小和标题
window_width = 600
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Snake Game")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义蛇的大小和速度
snake_size = 10
snake_speed = 15
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义函数:绘制蛇
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(window, green, [pixel[0], pixel[1], snake_size, snake_size])
# 定义函数:显示消息
def message(msg, color):
screen_text = font.render(msg, True, color)
window.blit(screen_text, [window_width/6, window_height/2])
# 定义函数:游戏循环
def game_loop():
game_over = False
game_close = False
x = window_width / 2
y = window_height / 2
x_change = 0
y_change = 0
snake_pixels = []
snake_length = 1
# 随机生成食物的位置
food_x = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
# 游戏循环
while not game_over:
while game_close == True:
window.fill(white)
message("You Lost! Press Q-Quit or C-Play Again", 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:
x_change = -snake_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = snake_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -snake_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = snake_size
x_change = 0
# 判断蛇是否撞墙
if x >= window_width or x < 0 or y >= window_height or y < 0:
game_close = True
x += x_change
y += y_change
window.fill(white)
# 绘制食物
pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size])
# 更新蛇的位置
snake_pixels.append([x, y])
if len(snake_pixels) > snake_length:
del snake_pixels[0]
# 判断蛇是否吃到食物
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
# 绘制蛇
draw_snake(snake_size, snake_pixels)
# 更新窗口
pygame.display.update()
# 判断蛇是否吃到食物
if x == food_x and y == food_y:
food_x = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
snake_length += 1
# 控制蛇的速度
pygame.time.Clock().tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
game_loop()
```
阅读全文