贪吃蛇的python代码
时间: 2023-05-16 17:07:10 浏览: 73
以下是一个简单的贪吃蛇 Python 代码示例:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置字体
font = pygame.font.SysFont(None, 25)
# 定义方块大小
block_size = 20
# 定义蛇的初始位置和长度
def snake(block_size, snake_list):
for x_y in snake_list:
pygame.draw.rect(screen, black, [x_y[0], x_y[1], block_size, block_size])
# 显示消息
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [screen_width/2, screen_height/2])
# 游戏循环
def gameLoop():
gameExit = False
gameOver = False
# 定义蛇的初始位置和长度
lead_x = screen_width/2
lead_y = screen_height/2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 定义食物的位置
rand_food_x = round(random.randrange(0, screen_width-block_size)/10.0)*10.0
rand_food_y = round(random.randrange(0, screen_height-block_size)/10.0)*10.0
# 游戏循环
while not gameExit:
# 游戏结束
while gameOver == True:
screen.fill(white)
message_to_screen("Game over, press C to play again or Q to quit", red)
pygame.display.update()
# 判断用户按键
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
# 判断用户按键
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = 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 >= screen_width or lead_x < 0 or lead_y >= screen_height or lead_y < 0:
gameOver = True
# 移动蛇
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制食物
screen.fill(white)
pygame.draw.rect(screen, red, [rand_food_x, rand_food_y, block_size, block_size])
# 绘制蛇
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for eachSegment in snake_list[:-1]:
if eachSegment == snake_head:
gameOver = True
snake(block_size, snake_list)
pygame.display.update()
# 判断蛇是否吃到食物
if lead_x == rand_food_x and lead_y == rand_food_y:
rand_food_x = round(random.randrange(0, screen_width-block_size)/10.0)*10.0
rand_food_y = round(random.randrange(0, screen_height-block_size)/10.0)*10.0
snake_length += 1
# 设置游戏帧率
clock = pygame.time.Clock()
clock.tick(15)
# 退出 Pygame
pygame.quit()
quit()
gameLoop()
```
希望对你有所帮助!
阅读全文