用python写一个贪吃蛇
时间: 2024-01-07 07:04:53 浏览: 97
代码示例:
```python
import pygame
import random
# 初始化pygame模块
pygame.init()
# 游戏窗口的大小
window_width = 400
window_height = 400
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置游戏窗口
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的尺寸
block_size = 10
# 导入字体
font_style = pygame.font.SysFont(None, 30)
# 显示得分
def our_score(score):
value = font_style.render("得分:" + str(score), True, white)
game_display.blit(value, [0, 0])
# 绘制蛇的形状
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, green, [x[0], x[1], snake_block, snake_block])
# 游戏循环
def game_loop():
# 定义蛇的初始位置
x1 = window_width / 2
y1 = window_height / 2
x1_change = 0
y1_change = 0
# 定义蛇的长度
snake_list = []
length_of_snake = 1
# 定义食物的位置
foodx = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
# 游戏是否结束的标志
game_exit = False
# 得分
score = 0
# 游戏主循环
while not game_exit:
# 处理事件
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:
x1_change = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = block_size
x1_change = 0
# 判断蛇是否撞墙
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_exit = True
# 更新蛇的位置和长度
x1 += x1_change
y1 += y1_change
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
# 判断是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
length_of_snake += 1
score += 10
# 绘制游戏界面
game_display.fill(black)
pygame.draw.rect(game_display, red, [foodx, foody, block_size, block_size])
draw_snake(block_size, snake_list)
our_score(score)
pygame.display.update()
# 设置游戏的帧率
clock = pygame.time.Clock()
clock.tick(15)
pygame.quit()
quit()
game_loop()
```
说明:
此段程序使用Pygame模块绘制了一个简单的贪吃蛇游戏,玩家可以通过上下左右控制蛇的移动,并吃到随机出现的食物来增加分数。当蛇碰到墙或者自己时,游戏结束。整个游戏界面每帧都会重新绘制一次。最后,调用game_loop()函数即可开始游戏。
阅读全文