python贪吃蛇完整代码
时间: 2023-07-23 10:03:41 浏览: 155
以下是一个简单的Python贪吃蛇的完整代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇游戏")
# 定义蛇的初始位置和速度
snake_block = 10
snake_speed = 30
x1 = screen_width / 2
y1 = screen_height / 2
x1_change = 0
y1_change = 0
# 定义食物的初始位置
foodx = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
# 定义蛇的身体
snake_body = []
snake_length = 1
clock = pygame.time.Clock()
font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)
def score(score):
value = score_font.render("Score: " + str(score), True, WHITE)
screen.blit(value, [0, 0])
def snake(snake_block, snake_body):
for x in snake_body:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block, snake_block])
def game_loop():
game_over = False
game_close = False
while not game_over:
while game_close:
screen.fill(BLACK)
message = font_style.render("Game Over! Press Q-Quit or C-Play Again", True, RED)
screen.blit(message, [screen_width / 6, screen_height / 3])
score(snake_length - 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:
game_loop()
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 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
screen.fill(BLACK)
pygame.draw.rect(screen, RED, [foodx, foody, snake_block, snake_block])
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
for x in snake_body[:-1]:
if x == snake_head:
game_close = True
snake(snake_block, snake_body)
score(snake_length - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
game_loop()
```
这是一个简单的贪吃蛇游戏的代码,使用了Pygame库来实现图形化界面和游戏逻辑。你可以将代码复制到Python环境中运行,并使用方向键来控制贪吃蛇的移动。