帮我用python写贪吃蛇代码
时间: 2023-05-22 14:06:02 浏览: 82
好的,下面是一份简单的 Python 贪吃蛇代码示例:
```python
import pygame
import random
# 初始化窗口大小、蛇、食物等信息
SIZE = 40
pygame.init()
font = pygame.font.SysFont(None, 55)
def draw_text(text, color, x, y):
img = font.render(text, True, color)
screen.blit(img, (x, y))
def draw_snake(snake_block, snake_List):
for x in snake_List:
pygame.draw.rect(screen, (255, 255, 255), [x[0], x[1], snake_block, snake_block])
def gameLoop():
game_over = False
game_close = False
x1 = 250
y1 = 250
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, 600 - SIZE) / 40.0) * 40.0
foody = round(random.randrange(0, 400 - SIZE) / 40.0) * 40.0
while not game_over:
while game_close == True:
screen.fill((0, 0, 0))
draw_text("You Lost! Press Q-Quit or C-Play Again", (255, 255, 255), 50, 200)
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 = -SIZE
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = SIZE
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -SIZE
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = SIZE
x1_change = 0
if x1 >= 600 or x1 < 0 or y1 >= 400 or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 0, 0), [foodx, foody, SIZE, 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
draw_snake(SIZE, snake_List)
draw_text("Score: " + str(Length_of_snake - 1), (255, 255, 255), 10, 10)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, 600 - SIZE) / 40.0) * 40.0
foody = round(random.randrange(0, 400 - SIZE) / 40.0) * 40.0
Length_of_snake += 1
clock.tick(10)
pygame.quit()
quit()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Snake game")
gameLoop()
```
希望能帮到你。如果你有更多 Python 编程方面的问题,欢迎随时提出。
阅读全文