用Python实现贪吃蛇小游戏
时间: 2023-11-05 20:10:28 浏览: 110
好的,以下是用Python实现贪吃蛇小游戏的代码:
```python
import pygame
import random
# 初始化
pygame.init()
# 窗口大小
win_width = 500
win_height = 500
# 创建窗口
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("贪吃蛇")
# 颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 蛇的属性
snake_block = 10
snake_speed = 15
# 字体
font = pygame.font.SysFont(None, 25)
# 显示得分
def show_score(score):
score_text = font.render("Score: " + str(score), True, white)
win.blit(score_text, [0, 0])
# 画蛇
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(win, black, [x[0], x[1], snake_block, snake_block])
# 消息提示
def message(msg, color):
message_text = font.render(msg, True, color)
win.blit(message_text, [win_width/6, win_height/3])
# 游戏循环
def gameLoop():
game_over = False
game_close = False
# 初始位置
x1 = win_width / 2
y1 = win_height / 2
# 移动位置
x1_change = 0
y1_change = 0
# 蛇的长度
snake_List = []
Length_of_snake = 1
# 食物的位置
foodx = round(random.randrange(0, win_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, win_height - snake_block) / 10.0) * 10.0
# 游戏循环
while not game_over:
while game_close == True:
win.fill(black)
message("You Lost! Press Q-Quit or C-Play Again", red)
show_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
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
# 超出边界
if x1 >= win_width or x1 < 0 or y1 >= win_height or y1 < 0:
game_close = True
# 移动位置
x1 += x1_change
y1 += y1_change
# 画食物
win.fill(black)
pygame.draw.rect(win, red, [foodx, foody, snake_block, snake_block])
# 蛇的长度
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]
# 撞到身体
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
# 画蛇
draw_snake(snake_block, snake_List)
show_score(Length_of_snake - 1)
pygame.display.update()
# 吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, win_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, win_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
# 刷新速度
pygame.time.delay(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 运行游戏
gameLoop()
```
这段代码实现了一个简单的贪吃蛇小游戏,可以在Python编译器中直接运行。
阅读全文