制作一款贪吃蛇小游戏
时间: 2023-07-04 19:05:29 浏览: 57
好的,我们可以使用 Python 编写一个简单的贪吃蛇小游戏。以下是一些基本的代码示例:
```python
import pygame, random
# 初始化 Pygame
pygame.init()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏窗口大小和标题
window_width = 800
window_height = 600
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇的大小和速度
snake_block_size = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 50)
# 定义游戏结束函数
def message(msg, color):
message_text = font_style.render(msg, True, color)
game_display.blit(message_text, [window_width / 6, window_height / 3])
# 定义主函数
def main():
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 - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
# 游戏循环
while not game_over:
while game_close == True:
game_display.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:
main()
# 监听键盘事件
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 = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_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_display.fill(white)
# 绘制食物
pygame.draw.rect(game_display, red, [foodx, foody, snake_block_size, snake_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
for segment in snake_List:
pygame.draw.rect(game_display, black, [segment[0], segment[1], snake_block_size, snake_block_size])
pygame.display.update()
# 判断是否吃到了食物
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
Length_of_snake += 1
# 设置游戏速度
clock.tick(snake_speed)
# 退出 Pygame
pygame.quit()
quit()
# 运行主函数
if __name__ == "__main__":
main()
```
通过上述代码,我们可以创建一个简单的贪吃蛇小游戏。玩家可以通过键盘上下左右键来控制贪吃蛇的移动方向,然后吃掉食物,增加贪吃蛇的长度。如果贪吃蛇碰到了边界或者自己的身体,则游戏结束,玩家可以选择重新开始或者退出游戏。