当然可以。下面是 python 实现一个简单的贪吃蛇游戏的完整攻略,包括代码和示例说明。
步骤一:准备工作
首先要安装 pygame 模块。在终端下输入以下命令即可:
pip install pygame
接着,可以下载以下代码并解压到项目文件夹中。
import random
import pygame
from pygame.locals import *
SIZE = 40
class Apple:
def __init__(self, parent_screen):
self.image = pygame.image.load("resources/apple.jpg").convert()
self.parent_screen = parent_screen
self.x = SIZE * 3
self.y = SIZE * 3
def draw(self):
self.parent_screen.blit(self.image, (self.x, self.y))
pygame.display.flip()
def move(self):
self.x = random.randint(0, 24) * SIZE
self.y = random.randint(0, 19) * SIZE
class Snake:
def __init__(self, parent_screen):
self.parent_screen = parent_screen
self.image = pygame.image.load("resources/block.jpg").convert()
self.direction = 'down'
self.length = 1
self.x = [SIZE]
self.y = [SIZE]
def draw(self):
self.parent_screen.fill((110, 110, 5))
for i in range(self.length):
self.parent_screen.blit(self.image, (self.x[i], self.y[i]))
pygame.display.flip()
def grow(self):
self.length += 1
self.x.append(-1)
self.y.append(-1)
def move_up(self):
self.direction = 'up'
def move_down(self):
self.direction = 'down'
def move_left(self):
self.direction = 'left'
def move_right(self):
self.direction = 'right'
def walk(self):
for i in range(self.length - 1, 0, -1):
self.x[i] = self.x[i - 1]
self.y[i] = self.y[i - 1]
if self.direction == 'up':
self.y[0] -= SIZE
if self.direction == 'down':
self.y[0] += SIZE
if self.direction == 'left':
self.x[0] -= SIZE
if self.direction == 'right':
self.x[0] += SIZE
self.draw()
class Game:
def __init__(self):
pygame.init()
pygame.display.set_caption("贪吃蛇大作战")
pygame.mixer.init()
self.play_background_music()
self.surface = pygame.display.set_mode((1000, 800))
self.snake = Snake(self.surface)
self.snake.draw()
self.apple = Apple(self.surface)
self.apple.draw()
def is_collision(self, x1, y1, x2, y2):
if x1 >= x2 and x1 < x2 + SIZE:
if y1 >= y2 and y1 < y2 + SIZE:
return True
return False
def play_background_music(self):
pygame.mixer.music.load("resources/bg_music_1.mp3")
pygame.mixer.music.play()
def play_sound(self, sound):
sound = pygame.mixer.Sound(f"resources/{sound}.mp3")
pygame.mixer.Sound.play(sound)
def render_background(self):
bg = pygame.image.load("resources/background.jpg")
self.surface.blit(bg, (0, 0))
def play(self):
self.render_background()
self.snake.walk()
self.apple.draw()
self.display_score()
pygame.display.flip()
# eat apple
if self.is_collision(self.snake.x[0], self.snake.y[0], self.apple.x, self.apple.y):
self.play_sound("ding")
self.snake.grow()
self.apple.move()
# snake collides with itself
for i in range(3, self.snake.length):
if self.is_collision(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i]):
self.play_sound('crash')
raise "Collision Occurred"
def display_score(self):
font = pygame.font.SysFont('arial', 30)
score = font.render(f"Score: {self.snake.length}", True, (200, 200, 200))
self.surface.blit(score, (800, 10))
def show_game_over(self):
self.render_background()
font = pygame.font.SysFont('arial', 30)
line1 = font.render(f"Game is Over! Your score is {self.snake.length}", True, (255, 255, 255))
self.surface.blit(line1, (200, 300))
line2 = font.render("To play again press Enter. To exit press Escape!", True, (255, 255, 255))
self.surface.blit(line2, (200, 350))
pygame.display.flip()
pygame.mixer.music.pause()
def reset(self):
self.snake = Snake(self.surface)
self.apple = Apple(self.surface)
def run(self):
running = True
pause = False
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_RETURN:
pygame.mixer.music.unpause()
pause = False
if not pause:
if event.key == K_UP:
self.snake.move_up()
if event.key == K_DOWN:
self.snake.move_down()
if event.key == K_LEFT:
self.snake.move_left()
if event.key == K_RIGHT:
self.snake.move_right()
elif event.type == QUIT:
running = False
try:
if not pause:
self.play()
except Exception as e:
self.show_game_over()
pause = True
self.play_background_music()
self.reset()
pygame.time.Clock().tick(10)
if __name__ == '__main__':
game = Game()
game.run()
示例说明:
首先在 Snake
类中定义了三个函数,分别是 __init__
、draw
和 move
。其中 __init__
函数初始化贪吃蛇的一些属性,比如初始长度为 1
,头部坐标为 (SIZE, SIZE)
。draw
函数根据当前贪吃蛇的位置画出贪吃蛇。move
函数则实现了贪吃蛇移动的逻辑。
在 Apple
类中,__init__
函数则是初始化苹果的一些属性,比如苹果初始坐标为 (SIZE*3, SIZE*3)
。而 draw
函数是画出当前位置的苹果,并更新显示。
在 Game
类中,则定义了贪吃蛇游戏的一些属性和逻辑,如是否与苹果碰撞,是否与自身碰撞,背景音乐播放,游戏结束等等。
代码中还有一些函数和参数的定义,不再赘述。接下来是第二个示例说明。
步骤二:执行效果
在代码中执行后,会弹出一个窗口,贪吃蛇游戏开始。按键盘上方向键控制方向,贪吃蛇一旦碰撞到苹果即有机会增长一个长度。游戏结束时,会提示得分,并可选择重新开始游戏或退出游戏。
如果想要重新开始游戏,按 Enter 键即可重新开始,如果想退出游戏,则按 Esc 键即可退出。
以上就是 python 实现一个简单的贪吃蛇游戏的攻略,希望对你有所帮助!
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python实现一个简单的贪吃蛇游戏附代码 - Python技术站