是不是这个样子(import pygame
import sys
import random
pygame.init()
游戏窗口设置
WIDTH, HEIGHT = 640, 480
CELL_SIZE = 20
ROWS, COLS = HEIGHT // CELL_SIZE, WIDTH // CELL_SIZE
BACKGROUND_COLOR = (0, 0, 0)
颜色
SNAKE_COLOR = (0, 255, 0)
FOOD_COLOR = (255, 0, 0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
clock = pygame.time.Clock()
class Snake:
def __init__(self):
self.body = [(CELL_SIZE * 2, CELL_SIZE * 2), (CELL_SIZE, CELL_SIZE * 2)]
self.direction = (CELL_SIZE, 0)
def move(self):
head_x, head_y = self.body[0]
dir_x, dir_y = self.direction
new_head = (head_x + dir_x, head_y + dir_y)
if new_head in self.body or not (0 <= new_head[0] < WIDTH and 0 <= new_head[1] < HEIGHT):
return False
self.body.insert(0, new_head)
self.body.pop()
return True
def grow(self):
self.body.append(self.body[-1])
def change_direction(self, new_direction):
if (self.direction[0] == -new_direction[0] and self.direction[1] == new_direction[1]) or (
self.direction[1] == -new_direction[1] and self.direction[0] == new_direction[0]):
return
self.direction = new_direction
def draw(self, screen):
for segment in self.body:
pygame.draw.rect(screen, SNAKE_COLOR, pygame.Rect(segment[0], segment[1], CELL_SIZE, CELL_SIZE))
class Food:
def __init__(self, snake_body):
self.position = self.generate_food_position(snake_body)
def generate_food_position(self, snake_body):
position = (random.randrange(0, COLS) * CELL_SIZE, random.randrange(0, ROWS) * CELL_SIZE)
while position in snake_body:
position = (random.randrange(0, COLS) * CELL_SIZE, random.randrange(0, ROWS) * CELL_SIZE)
return position
def draw(self, screen):
pygame.draw.rect(screen, FOOD_COLOR, pygame.Rect(self.position[0], self.position[1], CELL_SIZE, CELL_SIZE))
def main():
snake = Snake()
food = Food(snake.body)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction((0, -CELL_SIZE))
elif event.key == pygame.K_DOWN:
snake.change_direction((0, CELL_SIZE))
elif event.key == pygame.K_LEFT:
snake.change_direction((-CELL_SIZE, 0))
elif event.key == pygame.K_RIGHT:
snake.change_direction((CELL_SIZE, 0))
if not snake.move():
break
if snake.body[0] == food.position:
snake.grow()
food = Food(snake.body)
screen.fill(BACKGROUND_COLOR)
snake.draw(screen)
food.draw
def main():
snake = Snake()
food = Food(snake.body)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction((0, -CELL_SIZE))
elif event.key == pygame.K_DOWN:
snake.change_direction((0, CELL_SIZE))
elif event.key == pygame.K_LEFT:
snake.change_direction((-CELL_SIZE, 0))
elif event.key == pygame.K_RIGHT:
snake.change_direction((CELL_SIZE, 0))