Python写一个贪吃蛇游戏
时间: 2023-03-23 11:00:33 浏览: 83
好的,关于Python写贪吃蛇游戏的问题,我可以回答。下面是一个简单的Python代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏窗口大小
screen_width = 480
screen_height = 480
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建游戏窗口
game_display = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Snake Game')
# 定义方块大小和蛇的大小
block_size = 10
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义游戏结束函数
def game_over():
message('Game Over!', red)
pygame.display.update()
time.sleep(2)
game_loop()
# 定义显示消息的函数
def message(msg, color):
text = font.render(msg, True, color)
game_display.blit(text, [screen_width/6, screen_height/3])
# 定义贪吃蛇函数
def snake(block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, black, [x[0], x[1], block_size, block_size])
# 定义游戏循环函数
def game_loop():
game_exit = False
game_over = False
# 初始化蛇的位置和长度
lead_x = screen_width / 2
lead_y = screen_height / 2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 初始化食物的位置
food_x = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
while not game_exit:
while game_over == True:
game_display.fill(white)
message("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:
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:
game_over()
lead_x += lead_x_change
lead_y += lead_y_change
game_display.fill(white)
pygame.draw.rect(game_display, red, [food_x, food_y
阅读全文