贪吃蛇游戏

贪吃蛇游戏

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File  : 0.py
@Author:   BC
@Date  : 2023-04-20 17:20
贪吃蛇
'''
import pygame
import random

pygame.init()

# 游戏窗口尺寸
window_width = 640
window_height = 480
window = pygame.display.set_mode((window_width, window_height))

# 设置游戏窗口标题
pygame.display.set_caption("贪吃蛇")

# 定义颜色常量
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)

# 蛇的位置
snake_x = 0
snake_y = 0
snake_width = 10
snake_height = 10
snake_list = []
snake_length = 1

# 初始方向
direction = "right"

# 食物的位置
food_x = round(random.randrange(0, window_width - snake_width) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_height) / 10.0) * 10.0

# 游戏结束标志
game_over = False

clock = pygame.time.Clock()

while not game_over:
    # 主事件循环
    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:
                direction = "left"
            elif event.key == pygame.K_RIGHT:
                direction = "right"
            elif event.key == pygame.K_UP:
                direction = "up"
            elif event.key == pygame.K_DOWN:
                direction = "down"

    # 碰撞检测
    if snake_x >= window_width or snake_x < 0 or snake_y > window_height or snake_y < 0:
        game_over = True

    snake_head = []
    snake_head.append(snake_x)
    snake_head.append(snake_y)

    # 蛇的移动
    if direction == "right":
        snake_x += 10
    elif direction == "left":
        snake_x -= 10
    elif direction == "up":
        snake_y -= 10
    elif direction == "down":
        snake_y += 10

    # 更新贪吃蛇的位置列表
    snake_list.append(snake_head)
    if len(snake_list) > snake_length:
        del snake_list[0]

    for segment in snake_list[:-1]:
        if segment == snake_head:
            game_over = True

    # 绘制食物和贪吃蛇
    window.fill(black)
    pygame.draw.rect(window, white, [food_x, food_y, snake_width, snake_height])
    for segment in snake_list:
        pygame.draw.rect(window, red, [segment[0], segment[1], snake_width, snake_height])

    # 检测食物是否被吃掉并更新食物位置
    if snake_x == food_x and snake_y == food_y:
        food_x = round(random.randrange(0, window_width - snake_width) / 10.0) * 10.0
        food_y = round(random.randrange(0, window_height - snake_height) / 10.0) * 10.0
        snake_length += 1

    # 刷新屏幕
    pygame.display.update()

    # 设置游戏帧率
    clock.tick(15)

# 退出游戏
pygame.quit()
quit()

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值