编写出一款贪吃蛇的代码
时间: 2024-05-13 07:11:55 浏览: 64
编写贪吃蛇的代码需要使用图形化界面,可以使用Python中的Pygame模块来实现。下面是一个简单的贪吃蛇代码示例:
```
import pygame
import random
# 初始化Pygame
pygame.init()
# 定义颜色变量
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义游戏窗口大小
window_width = 800
window_height = 600
# 创建游戏窗口
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# 定义贪吃蛇大小
block_size = 10
# 定义时钟对象
clock = pygame.time.Clock()
# 定义字体对象
font = pygame.font.SysFont(None, 25)
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
game_display.blit(screen_text, [window_width/2, window_height/2])
def gameLoop():
# 定义游戏结束变量
game_exit = False
game_over = False
# 初始化贪吃蛇位置和速度
lead_x = window_width/2
lead_y = window_height/2
lead_x_change = 0
lead_y_change = 0
# 初始化食物位置
rand_food_x = round(random.randrange(0, window_width - block_size) / float(block_size)) * float(block_size)
rand_food_y = round(random.randrange(0, window_height - block_size) / float(block_size)) * float(block_size)
while not game_exit:
while game_over == True:
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:
gameLoop()
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 >= window_width or lead_x < 0 or lead_y >= window_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, red, [rand_food_x, rand_food_y, block_size, block_size])
pygame.draw.rect(game_display, black, [lead_x, lead_y, block_size, block_size])
pygame.display.update()
# 判断是否吃到食物
if lead_x == rand_food_x and lead_y == rand_food_y:
rand_food_x = round(random.randrange(0, window_width - block_size) / float(block_size)) * float(block_size)
rand_food_y = round(random.randrange(0, window_height - block_size) / float(block_size)) * float(block_size)
# 控制游戏帧率
clock.tick(10)
# 关闭Pygame
pygame.quit()
quit()
gameLoop()
```
上面代码中,我们使用Pygame实现了一个简单的贪吃蛇游戏。游戏中,我们使用方向键控制贪吃蛇的移动,贪吃蛇吃到食物后会增加长度,如果贪吃蛇撞到边界或者自身,则游戏结束。
阅读全文