用python写一份能在VScode运行的贪吃蛇的代码
时间: 2024-02-12 11:09:21 浏览: 19
好的,以下是一个简单的Python贪吃蛇游戏代码,可以在VScode中运行:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏窗口尺寸
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
# 设置游戏窗口
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 设置游戏参数
CELL_SIZE = 20
FPS = 10
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
self.color = GREEN
self.score = 0
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0]*-1, point[1]*-1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = ((cur[0] + (x * CELL_SIZE)), (cur[1] + (y * CELL_SIZE)))
if new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
self.score = 0
def draw(self, surface):
for p in self.positions:
r = pygame.Rect((p[0], p[1]), (CELL_SIZE, CELL_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
def handle_keys(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
quit()
elif event.key == pygame.K_UP:
self.turn((0, -1))
elif event.key == pygame.K_DOWN:
self.turn((0, 1))
elif event.key == pygame.K_LEFT:
self.turn((-1, 0))
elif event.key == pygame.K_RIGHT:
self.turn((1, 0))
# 定义食物类
class Food:
def __init__(self):
x = random.randrange(CELL_SIZE, WINDOW_WIDTH - CELL_SIZE, CELL_SIZE)
y = random.randrange(CELL_SIZE, WINDOW_HEIGHT - CELL_SIZE, CELL_SIZE)
self.position = (x, y)
self.color = RED
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (CELL_SIZE, CELL_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 初始化贪吃蛇和食物
snake = Snake()
food = Food()
# 设置游戏时钟
clock = pygame.time.Clock()
# 游戏主循环
while True:
game_window.fill(WHITE)
# 处理键盘事件
snake.handle_keys()
# 移动贪吃蛇
snake.move()
# 判断贪吃蛇是否吃到食物
if snake.get_head_position() == food.position:
snake.length += 1
snake.score += 1
food = Food()
# 绘制贪吃蛇和食物
snake.draw(game_window)
food.draw(game_window)
# 更新游戏得分
font = pygame.font.SysFont('Arial', 20)
score_text = font.render('Score: {}'.format(snake.score), True, BLACK)
game_window.blit(score_text, (WINDOW_WIDTH - 100, 10))
# 更新游戏窗口
pygame.display.update()
# 设置游戏帧率
clock.tick(FPS)
# 退出Pygame
pygame.quit()
```
你可以将以上代码复制到VScode中并运行。希望能对你有所帮助!