可以写哥贪吃蛇代码吗
时间: 2023-08-24 08:03:47 浏览: 59
当然可以,以下是一个简单的贪吃蛇游戏代码(使用Python语言实现):
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 定义常量
WIDTH = 600
HEIGHT = 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Greedy Snake")
# 定义蛇类
class Snake:
def __init__(self):
self.body = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = random.choice(['up', 'down', 'left', 'right'])
def move(self):
x, y = self.body[0]
if self.direction == 'up':
y -= 1
elif self.direction == 'down':
y += 1
elif self.direction == 'left':
x -= 1
elif self.direction == 'right':
x += 1
self.body.insert(0, (x, y))
self.body.pop()
def grow(self):
x, y = self.body[0]
if self.direction == 'up':
y -= 1
elif self.direction == 'down':
y += 1
elif self.direction == 'left':
x -= 1
elif self.direction == 'right':
x += 1
self.body.insert(0, (x, y))
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'
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, WHITE, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, GRID_WIDTH - 1)
self.y = random.randint(0, GRID_HEIGHT - 1)
def draw(self):
pygame.draw.rect(screen, RED, (self.x * GRID_SIZE, self.y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# 创建蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
clock = pygame.time.Clock()
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.x, food.y):
snake.grow()
food = Food()
# 判断蛇是否撞墙或撞到自己
if snake.body[0][0] < 0 or snake.body[0][0] >= GRID_WIDTH or snake.body[0][1] < 0 or snake.body[0][1] >= GRID_HEIGHT:
pygame.quit()
quit()
for i in range(1, len(snake.body)):
if snake.body[0] == snake.body[i]:
pygame.quit()
quit()
# 绘制游戏界面
screen.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
# 控制游戏速度
clock.tick(10)
```
这个贪吃蛇游戏比较简单,只有基本的移动、吃食物、撞墙和撞到自己的判断。如果要增加游戏难度或者添加更多功能,可以在此基础上进行扩展。