使用Python编写贪吃蛇代码
时间: 2023-11-05 13:59:43 浏览: 77
好的,编写贪吃蛇游戏的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('贪吃蛇游戏')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
red = (255, 0, 0)
# 定义蛇的属性
snake_block_size = 10
snake_speed = 20
# 字体设置
font_style = pygame.font.SysFont(None, 30)
# 定义显示分数函数
def display_score(score):
score_text = font_style.render("Score: " + str(score), True, black)
window.blit(score_text, [0, 0])
# 定义画出蛇的函数
def draw_snake(snake_block_size, snake_body):
for block in snake_body:
pygame.draw.rect(window, green, [block[0], block[1], snake_block_size, snake_block_size])
# 定义游戏主函数
def gameLoop():
game_over = False
game_close = False
# 初始蛇的位置
x1 = window_width / 2
y1 = window_height / 2
# 蛇每一段的大小
x1_change = 0
y1_change = 0
# 定义蛇的长度
snake_body = []
length_of_snake = 1
# 食物位置随机生成
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
while not game_over:
while game_close == True:
window.fill(white)
game_over_text = font_style.render("Game Over! Press Q-Quit or C-Play Again", True, red)
window.blit(game_over_text, [window_width / 6, window_height / 3])
display_score(length_of_snake - 1)
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:
gameLoop()
# 监听事件
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:
x1_change = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
# 判断蛇是否碰到边界,游戏结束
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
# 更新蛇的位置
x1 += x1_change
y1 += y1_change
# 绘制窗口
window.fill(white)
# 画出食物
pygame.draw.rect(window, red, [foodx, foody, snake_block_size, snake_block_size])
# 更新蛇的长度
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_body.append(snake_head)
if len(snake_body) > length_of_snake:
del snake_body[0]
# 检查蛇是否撞上自己,游戏结束
for block in snake_body[:-1]:
if block == snake_head:
game_close = True
# 画出蛇
draw_snake(snake_block_size, snake_body)
# 显示分数
display_score(length_of_snake - 1)
pygame.display.update()
# 当蛇吃到食物时,更新食物位置,蛇的长度+1
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
length_of_snake += 1
# 控制蛇的速度
pygame.time.wait(snake_speed)
pygame.quit()
quit()
# 开始游戏
gameLoop()
```
阅读全文