python编写贪吃蛇游戏300行源代码
时间: 2023-07-07 12:39:26 浏览: 89
好的,以下是我为你准备的 Python 编写贪吃蛇游戏的源代码,共计300行:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小
screen_width = 480
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 定义蛇
snake_block_size = 10
snake_speed = 20
font_style = pygame.font.SysFont(None, 30)
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block_size, snake_block_size])
# 定义消息显示函数
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [screen_width / 6, screen_height / 3])
# 定义游戏循环
def game_loop():
game_over = False
game_close = False
# 定义蛇的初始位置和长度
snake_list = []
length_of_snake = 1
# 定义食物的初始位置
food_x = round(random.randrange(0, screen_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block_size) / 10.0) * 10.0
# 定义蛇的初始位置和移动方向
x = screen_width / 2
y = screen_height / 2
x_change = 0
y_change = 0
# 游戏循环
while not game_over:
# 游戏失败后的操作
while game_close == True:
screen.fill(white)
message("游戏结束!按 Q 退出,按 C 重新开始游戏", red)
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:
x_change = -snake_block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = snake_block_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -snake_block_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = snake_block_size
x_change = 0
# 判断蛇是否撞墙
if x >= screen_width or x < 0 or y >= screen_height or y < 0:
game_close = True
# 移动蛇的位置
x += x_change
y += y_change
# 绘制游戏界面
screen.fill(white)
pygame.draw.rect(screen, green, [food_x, food_y, snake_block_size, snake_block_size])
snake_head = []
snake_head.append(x)
snake_head.append(y)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
# 判断蛇是否吃到食物
for block in snake_list[:-1]:
if block == snake_head:
game_close = True
draw_snake(snake_block_size, snake_list)
pygame.display.update()
if x == food_x and y == food_y:
food_x = round(random.randrange(0, screen_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block_size) / 10.0) * 10.0
length_of_snake += 1
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
pygame.quit()
quit()
game_loop()
```
希望这份代码能对你有所帮助!
阅读全文