python写个贪吃蛇
时间: 2023-06-23 09:51:27 浏览: 58
如何用Python写一个贪吃蛇AI.pdf
好的,以下是一个简单的Python贪吃蛇游戏代码示例,你可以参考一下:
```
import pygame
import random
# 定义颜色变量
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 定义游戏区域大小
display_width = 800
display_height = 600
pygame.init()
pygame.display.set_caption('贪吃蛇')
# 定义游戏区域
game_display = pygame.display.set_mode((display_width, display_height))
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇的初始位置和大小
block_size = 10
snake_speed = 15
font_style = pygame.font.SysFont(None, 50)
def message(msg, color):
msg = font_style.render(msg, True, color)
game_display.blit(msg, [display_width/6, display_height/3])
def snake(block_size, snake_list):
for x,y in snake_list:
pygame.draw.rect(game_display, green, [x, y, block_size, block_size])
# 定义游戏主函数
def game_loop():
game_exit = False
game_over = False
x1 = display_width / 2
y1 = display_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
food_x = round(random.randrange(0, display_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, display_height - block_size) / 10.0) * 10.0
# 游戏循环
while not game_exit:
while game_over == True:
game_display.fill(white)
message("Game over, press Q to quit or C to continue", red)
pygame.display.update()
# 判断用户的操作
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()
# 判断用户的操作
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = 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 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
game_over = True
# 更新贪吃蛇的位置
x1 += x1_change
y1 += y1_change
game_display.fill(white)
# 画出食物
pygame.draw.rect(game_display, red, [food_x, food_y, 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 segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
# 画出贪吃蛇
snake(block_size, snake_list)
# 更新分数
pygame.display.update()
# 判断贪吃蛇是否吃到了食物
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, display_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, display_height - block_size) / 10.0) * 10.0
length_of_snake += 1
# 游戏时钟
clock.tick(snake_speed)
# 关闭游戏
pygame.quit()
quit()
game_loop()
```
注意:以上代码仅为示例,可能有些不足之处,欢迎大家提出修改建议。
阅读全文