用Python写的贪吃蛇游戏。

冽:

编写一个贪吃蛇游戏。

这里提供一个简单的Python贪吃蛇游戏示例。

使用标准库 pygame 来实现图形界面:

首先,确保你已经安装了 pygame 库。如果没有安装,可以通过以下命令安装:

pip install pygame

然后,你可以使用以下代码来创建一个基本的贪吃蛇游戏:

import pygame

import time

import random

 

# 初始化pygame

pygame.init()

 

# 设置窗口大小

width, height = 640, 480

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption('贪吃蛇')

 

# 颜色定义

white = (255, 255, 255)

red = (213, 50, 80)

green = (0, 255, 0)

blue = (50, 153, 213)

black = (0, 0, 0)

 

# 蛇的初始位置和长度

snake_pos = [100, 50]

snake_body = [[100, 50], [90, 50], [80, 50]]

snake_length = len(snake_body)

direction = 'RIGHT'

change_to = direction

 

# 食物的初始位置

food_pos = [random.randrange(1, (width//10)) * 10, random.randrange(1, (height//10)) * 10]

 

# 游戏速度

clock = pygame.time.Clock()

food_spawn_time = 0

food_spawn_interval = 5 # 每秒生成食物

 

# 游戏主循环

while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            pygame.quit()

            quit()

        elif event.type == pygame.KEYDOWN:

            if event.key == pygame.K_UP or event.key == ord('w'):

                change_to = 'UP'

            if event.key == pygame.K_DOWN or event.key == ord('s'):

                change_to = 'DOWN'

            if event.key == pygame.K_LEFT or event.key == ord('a'):

                change_to = 'LEFT'

            if event.key == pygame.K_RIGHT or event.key == ord('d'):

                change_to = 'RIGHT'

 

    # 更新蛇头的位置

    if change_to == 'UP':

        snake_pos[1] -= 10

    if change_to == 'DOWN':

        snake_pos[1] += 10

    if change_to == 'LEFT':

        snake_pos[0] -= 10

    if change_to == 'RIGHT':

        snake_pos[0] += 10

 

    # 检查蛇头是否撞到自己的身体

    if snake_pos in snake_body:

        print('Game Over')

        pygame.time.wait(2000)

        snake_body = [[100, 50], [90, 50], [80, 50]]

        snake_length = len(snake_body)

        snake_pos = [100, 50]

        direction = 'RIGHT'

        change_to = direction

 

    # 检查蛇是否吃到食物

    if snake_pos == food_pos:

        snake_length += 1

        food_spawn_time = time.time()

        food_pos = [random.randrange(1, (width//10)) * 10, random.randrange(1, (height//10)) * 10]

 

    # 移动蛇的身体

    snake_body.insert(0, list(snake_pos))

    if snake_length > len(snake_body):

        snake_body.pop()

 

    # 绘制游戏界面

    screen.fill(black)

    for pos in snake_body:

        pygame.draw.rect(screen, green, pygame.Rect(pos[0], pos[1], 10, 10))

    pygame.draw.rect(screen, red, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

 

    pygame.display.flip()

 

    # 控制游戏速度

    clock.tick(10)

 

    # 控制食物生成速度

    if time.time() - food_spawn_time > food_spawn_interval:

        food_pos = [random.randrange(1, (width//10)) * 10, random.randrange(1, (height//10)) * 10]

        food_spawn_time = time.time()

这段代码创建了一个具有基本功能的贪吃蛇游戏,包括键盘控制、食物生成和游戏结束条件。游戏的内存使用量将取决于你的操作系统和 pygame 库的实现,如果你需要进一步优化内存使用,可能需要考虑更复杂的内存管理技术,但这通常对于贪吃蛇这样的简单游戏不是必需的。

 

 

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用Python实现贪吃蛇游戏的代码: ```python import pygame import random # 初始化pygame模块 pygame.init() # 设置屏幕大小及标题 screen_width = 640 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) # 设置字体 font = pygame.font.SysFont(None, 25) # 定义方向常量 UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 # 定义蛇类 class Snake: def __init__(self): self.body = [(screen_width // 2, screen_height // 2)] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) self.color = green def move(self): # 获取蛇头位置 x, y = self.body[0] # 根据方向改变位置 if self.direction == UP: y -= 10 elif self.direction == DOWN: y += 10 elif self.direction == LEFT: x -= 10 elif self.direction == RIGHT: x += 10 # 将新的头部位置插入到蛇身中 self.body.insert(0, (x, y)) # 删除蛇尾 self.body.pop() def draw(self): for x, y in self.body: pygame.draw.rect(screen, self.color, (x, y, 10, 10)) def change_direction(self, direction): if direction == UP and self.direction != DOWN: self.direction = UP elif direction == DOWN and self.direction != UP: self.direction = DOWN elif direction == LEFT and self.direction != RIGHT: self.direction = LEFT elif direction == RIGHT and self.direction != LEFT: self.direction = RIGHT # 定义食物类 class Food: def __init__(self): self.position = self.new_position() self.color = red def new_position(self): x = random.randrange(0, screen_width - 10, 10) y = random.randrange(0, screen_height - 10, 10) return (x, y) def draw(self): x, y = self.position pygame.draw.rect(screen, self.color, (x, y, 10, 10)) # 创建贪吃蛇和食物对象 snake = Snake() food = Food() # 游戏循环 while True: # 处理退出事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: snake.change_direction(UP) elif event.key == pygame.K_DOWN: snake.change_direction(DOWN) elif event.key == pygame.K_LEFT: snake.change_direction(LEFT) elif event.key == pygame.K_RIGHT: snake.change_direction(RIGHT) # 移动蛇 snake.move() # 判断是否吃到食物 if snake.body[0] == food.position: snake.body.append(snake.body[-1]) food.position = food.new_position() # 判断是否撞到墙或自己 if snake.body[0][0] < 0 or snake.body[0][0] > screen_width - 10 or snake.body[0][1] < 0 or snake.body[0][1] > screen_height - 10: pygame.quit() quit() for i in range(1, len(snake.body)): if snake.body[0] == snake.body[i]: pygame.quit() quit() # 绘制背景和文字 screen.fill(white) text = font.render('Score: ' + str(len(snake.body) - 1), True, black) screen.blit(text, (10, 10)) # 绘制蛇和食物 snake.draw() food.draw() # 更新显示 pygame.display.update() ``` 这个游戏实现了贪吃蛇的基本逻辑,包括蛇的移动、吃食物、撞墙或自己等情况的判断。你可以尝试运行代码,体验一下这个游戏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值