贪吃蛇小游戏代码
时间: 2023-07-02 18:08:28 浏览: 95
基于C#窗体程序的贪吃蛇代码
下面是一个简单的Python贪吃蛇游戏代码,希望能帮到你:
```python
import pygame
import random
# 初始化
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置窗口大小
size = (500, 500)
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("贪吃蛇")
# 坐标值设置
block_size = 10
snake_speed = 15
# 字体设置
font = pygame.font.SysFont(None, 25)
# 输出文字
def message(msg, color):
text = font.render(msg, True, color)
screen.blit(text, [size[0]/6, size[1]/3])
# 绘制蛇
def drawSnake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, BLACK, [x[0], x[1], snake_block, snake_block])
# 主函数
def gameLoop():
game_over = False
game_close = False
# 初始化贪吃蛇位置和长度
x1 = size[0]/2
y1 = size[1]/2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
# 食物随机生成位置
foodx = round(random.randrange(0, size[0]-block_size)/10.0)*10.0
foody = round(random.randrange(0, size[1]-block_size)/10.0)*10.0
# 游戏循环
while not game_over:
# 游戏结束
while game_close == True:
screen.fill(WHITE)
message("你输了!按 Q 退出或 R 重新开始", RED)
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_r:
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 = -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 >= size[0] or x1 < 0 or y1 >= size[1] or y1 < 0:
game_close = True
# 更新贪吃蛇的坐标
x1 += x1_change
y1 += y1_change
screen.fill(WHITE)
# 绘制食物
pygame.draw.rect(screen, GREEN, [foodx, foody, block_size, block_size])
# 贪吃蛇的身体
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
# 绘制贪吃蛇
drawSnake(block_size, snake_List)
pygame.display.update()
# 判断是否吃到食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, size[0]-block_size)/10.0)*10.0
foody = round(random.randrange(0, size[1]-block_size)/10.0)*10.0
Length_of_snake += 1
# 控制贪吃蛇移动速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 开始游戏
gameLoop()
```
这个代码是基于Python Pygame库编写的,可以在Python环境下直接运行。希望对你有帮助!
阅读全文