游戏效果展示
下面给出项目的部分代码,想要该游戏完整代码和配套资源的小伙伴私信我领取哦
精灵类定义
小蛇类
class Snake:
def __init__(self):
self.pos = [100, 100]
self.body = [[100, 100], [80, 100], [60, 100]]
self.vel = 20
self.direction = 'right'
self.speed = {1: 1, 2: 1.25, 3: 1.5, 4: 2}
def move(self, new_dir, speed=1):
if new_dir == 'left' and not self.direction == 'right':
self.direction = new_dir
if new_dir == 'right' and not self.direction == 'left':
self.direction = new_dir
if new_dir == 'up' and not self.direction == 'down':
self.direction = new_dir
if new_dir == 'down' and not self.direction == 'up':
self.direction = new_dir
if self.direction == 'right':
self.pos[0] += self.vel * self.speed[speed]
elif self.direction == 'left':
self.pos[0] -= self.vel * self.speed[speed]
elif self.direction == 'up':
self.pos[1] -= self.vel * self.speed[speed]
elif self.direction == 'down':
self.pos[1] += self.vel * self.speed[speed]
self.update()
def update(self):
self.body.insert(0, list(self.pos))
def eat(self, target):
if self.pos[0] == target.pos[0] and self.pos[1] == target.pos[1]:
target.update()
else:
self.body.pop()
食物类
class Food:
def __init__(self):
self.pos = [300, 300]
self.index = 0
def update(self):
x = random.randrange(1, 32)
y = random.randrange(1, 24)
self.pos = [int(x * 20), int(y * 20)]
self.index += 1
游戏逻辑实现
游戏主窗口
class GameState:
def __init__(self):
self.isend = False
self.snake = Snake()
self.food = Food()
self.screen = pygame.display.set_mode((640, 480))
键盘事件处理及窗口刷新
def start_game(self):
new_direction = 'right'
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
new_direction = 'right'
elif event.key == pygame.K_LEFT:
new_direction = 'left'
elif event.key == pygame.K_UP:
new_direction = 'up'
elif event.key == pygame.K_DOWN:
new_direction = 'down'
self.snake.move(new_direction)
self.snake.eat(self.food)
self.screen.fill(blackColor)
text = font.render(f'score:{self.food.index}', False, (255, 255, 255))
# 3.显示文字
self.screen.blit(text, (0, 0))
for pos in self.snake.body:
pygame.draw.rect(self.screen, redcolor, Rect(pos[0], pos[1], 20, 20))
pygame.draw.rect(self.screen, whiteColor, Rect(self.food.pos[0], self.food.pos[1], 20, 20))
pygame.display.flip()
self.go_out()
fps.tick(2)
游戏结束函数
def game_over(self):
pygame.quit()
sys.exit()
def go_out(self):
if self.snake.pos[0] > 620 or self.snake.pos[0] < 0:
self.game_over()
elif self.snake.pos[1] > 460 or self.snake.pos[1] < 0:
self.game_over()