基于Python开发贪吃蛇代码
时间: 2023-11-19 09:05:08 浏览: 121
好的,我可以回答您的问题。以下是一个基于Python实现的贪吃蛇游戏的代码示例:
```
import pygame
import random
# 初始化pygame
pygame.init()
# 尺寸设置
window_width = 640
window_height = 480
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# 创建窗口
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# 设置游戏时钟
clock = pygame.time.Clock()
block_size = 10
snake_speed = 15
font_style = pygame.font.SysFont(None, 30)
def message(msg, color):
message_display = font_style.render(msg, True, color)
game_window.blit(message_display, [window_width / 6, window_height / 3])
def snake(block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_window, green, [x[0], x[1], block_size, block_size])
def gameLoop():
game_over = False
game_close = False
x1 = window_width / 2
y1 = window_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
while not game_over:
while game_close == True:
game_window.fill(white)
message("You Lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
game_close = False
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 = -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 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
game_window.fill(black)
pygame.draw.rect(game_window, red, [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
snake(block_size, snake_List)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
```
希望这个代码示例能够回答您的问题!
阅读全文