使用Python编写包含有import pygame的简洁贪吃蛇代码,并显示运行结果
时间: 2024-02-24 21:59:28 浏览: 100
用Python和Pygame做的一个简单贪吃蛇游戏
好的,以下是一个简洁的贪吃蛇游戏代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口尺寸
window_width = 640
window_height = 480
# 初始化游戏窗口
game_window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption('简洁贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_list = []
snake_length = 1
snake_pos_x = window_width / 2
snake_pos_y = window_height / 2
# 定义食物初始位置和大小
food_block_size = 10
food_pos_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_pos_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
# 定义蛇的移动速度
snake_speed = 15
# 定义游戏结束的函数
def game_over():
font_style = pygame.font.SysFont(None, 50)
message = font_style.render('游戏结束!', True, red)
game_window.blit(message, [window_width / 3, window_height / 3])
pygame.display.update()
pygame.time.delay(2000)
# 游戏循环
game_running = True
while game_running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
# 处理按键事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_pos_x -= snake_block_size
elif keys[pygame.K_RIGHT]:
snake_pos_x += snake_block_size
elif keys[pygame.K_UP]:
snake_pos_y -= snake_block_size
elif keys[pygame.K_DOWN]:
snake_pos_y += snake_block_size
# 判断蛇是否吃到食物
if snake_pos_x == food_pos_x and snake_pos_y == food_pos_y:
food_pos_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_pos_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
snake_length += 1
# 更新蛇的位置
snake_head = []
snake_head.append(snake_pos_x)
snake_head.append(snake_pos_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断蛇是否碰到边界或自己
for block in snake_list[:-1]:
if block == snake_head:
game_over()
game_running = False
if snake_pos_x < 0 or snake_pos_x >= window_width or snake_pos_y < 0 or snake_pos_y >= window_height:
game_over()
game_running = False
# 绘制游戏界面
game_window.fill(white)
pygame.draw.rect(game_window, black, [snake_pos_x, snake_pos_y, snake_block_size, snake_block_size])
for block in snake_list[:-1]:
pygame.draw.rect(game_window, black, [block[0], block[1], snake_block_size, snake_block_size])
pygame.draw.rect(game_window, red, [food_pos_x, food_pos_y, food_block_size, food_block_size])
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出Pygame
pygame.quit()
```
你可以将上述代码保存为一个.py文件,然后运行即可看到简洁贪吃蛇游戏的运行结果。
阅读全文