给我一个贪吃蛇的代码并且教我怎么运行
以下是一个简单的贪吃蛇游戏代码,使用Python语言编写:
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
WIDTH = 640
HEIGHT = 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置游戏标题
pygame.display.set_caption("Snake Game")
# 定义贪吃蛇类
class Snake():
def __init__(self):
self.length = 1
self.positions = [((WIDTH / 2), (HEIGHT / 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
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*GRIDSIZE)) % WIDTH), (cur[1] + (y*GRIDSIZE)) % HEIGHT)
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 = [((WIDTH / 2), (HEIGHT / 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
def draw(self, surface):
for p in self.positions:
r = pygame.Rect((p[0], p[1]), (GRIDSIZE, GRIDSIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 定义食物类
class Food():
def __init__(self):
x = random.randrange(0, WIDTH, GRIDSIZE)
y = random.randrange(0, HEIGHT, GRIDSIZE)
self.position = (x, y)
self.color = RED
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (GRIDSIZE, GRIDSIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 定义方向常量
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# 定义网格大小
GRIDSIZE = 10
# 定义时钟对象
clock = pygame.time.Clock()
# 定义贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.turn(UP)
elif event.key == pygame.K_DOWN:
snake.turn(DOWN)
elif event.key == pygame.K_LEFT:
snake.turn(LEFT)
elif event.key == pygame.K_RIGHT:
snake.turn(RIGHT)
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.get_head_position() == food.position:
snake.length += 1
food = Food()
# 绘制游戏界面
screen.fill(WHITE)
snake.draw(screen)
food.draw(screen)
pygame.display.update()
# 控制游戏帧率
clock.tick(10)
运行此代码需要安装pygame库,可以使用pip命令进行安装:
pip install pygame
将以上代码保存为snake.py文件后,在命令行中进入文件所在目录,运行以下命令启动游戏:
python snake.py
接下来就可以使用上下左右箭头控制贪吃蛇的移动了。
原文地址: http://www.cveoy.top/t/topic/bk2r 著作权归作者所有。请勿转载和采集!