Python能有多“骚”?用代码画个会动的“贪吃蛇”游戏
Python不仅能写严谨的算法和复杂的后端服务,还能用来开发趣味十足的小游戏。今天,我们就用Python的pygame库实现一个经典的"贪吃蛇"游戏,展示Python在快速开发交互式应用方面的独特魅力。
一、环境准备
首先安装pygame库:
bash
pip install pygame
二、完整代码实现
python
importpygame
importrandom
importtime
# 初始化pygame
pygame.init()
# 游戏窗口设置
WIDTH, HEIGHT =600,400
GRID_SIZE =20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Python贪吃蛇")
# 颜色定义
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
# 蛇和食物类
classSnake:
def__init__(self):
self.positions = [(GRID_WIDTH //2, GRID_HEIGHT //2)]
self.direction = (1,0)
self.length =1
defget_head_position(self):
returnself.positions[0]
defmove(self):
head =self.get_head_position()
x, y =self.direction
new_head = ((head[0] + x) % GRID_WIDTH, (head[1] + y) % GRID_HEIGHT)
ifnew_headinself.positions[1:]:
returnFalse# 撞到自己
self.positions.insert(0, new_head)
iflen(self.positions) >self.length:
self.positions.pop()
returnTrue
defgrow(self):
self.length +=1
defchange_direction(self, new_direction):
# 防止180度转向
if(new_direction[0] * -1, new_direction[1] * -1) !=self.direction:
self.direction = new_direction
classFood:
def__init__(self):
self.position =self.random_position()
defrandom_position(self):
return(random.randint(0, GRID_WIDTH -1), random.randint(0, GRID_HEIGHT -1))
defrespawn(self, snake_positions):
whileTrue:
new_pos =self.random_position()
ifnew_posnotinsnake_positions:
self.position = new_pos
break
# 游戏主循环
defmain():
clock = pygame.time.Clock()
snake = Snake()
food = Food()
score =0
game_over =False
whilenotgame_over:
# 事件处理
foreventinpygame.event.get():
ifevent.type== pygame.QUIT:
game_over =True
elifevent.type== pygame.KEYDOWN:
ifevent.key == pygame.K_UP:
snake.change_direction((0, -1))
elifevent.key == pygame.K_DOWN:
snake.change_direction((0,1))
elifevent.key == pygame.K_LEFT:
snake.change_direction((-1,0))
elifevent.key == pygame.K_RIGHT:
snake.change_direction((1,0))
# 移动蛇
ifnotsnake.move():
game_over =True
# 检测是否吃到食物
ifsnake.get_head_position() == food.position:
snake.grow()
food.respawn(snake.positions)
score +=10
# 绘制画面
screen.fill(BLACK)
# 绘制网格(可选)
forxinrange(0, WIDTH, GRID_SIZE):
pygame.draw.line(screen, WHITE, (x,0), (x, HEIGHT))
foryinrange(0, HEIGHT, GRID_SIZE):
pygame.draw.line(screen, WHITE, (0, y), (WIDTH, y))
# 绘制蛇
forposinsnake.positions:
pygame.draw.rect(screen, GREEN,
(pos[0] * GRID_SIZE, pos[1] * GRID_SIZE, GRID_SIZE -1, GRID_SIZE -1))
# 绘制食物
pygame.draw.rect(screen, RED,
(food.position[0] * GRID_SIZE, food.position[1] * GRID_SIZE, GRID_SIZE -1, GRID_SIZE -1))
# 显示分数
font = pygame.font.SysFont(None,36)
text = font.render(f"Score:{score}",True, WHITE)
screen.blit(text, (10,10))
pygame.display.update()
clock.tick(10)# 控制游戏速度
# 游戏结束显示
font = pygame.font.SysFont(None,72)
text = font.render("Game Over!",True, WHITE)
screen.blit(text, (WIDTH//2- text.get_width()//2, HEIGHT//2- text.get_height()//2))
pygame.display.update()
time.sleep(2)
pygame.quit()
if__name__ =="__main__":
main()
三、代码亮点解析
面向对象设计:将蛇和食物封装为类,提高代码可维护性
环形边界处理:通过取模运算实现蛇从一边出来另一边进去的效果
碰撞检测:不仅检测与食物的碰撞,还检测蛇自身的碰撞
游戏速度控制:使用clock.tick()控制帧率
简单AI潜力:代码结构易于扩展,可添加AI自动控制蛇的移动
四、扩展方向
添加难度等级:通过调整clock.tick()的参数改变游戏速度
实现AI对手:添加第二个蛇并实现自动寻路算法
增加音效:使用pygame.mixer添加背景音乐和音效
网络对战:基于socket实现多人联机功能
这个简单的贪吃蛇游戏展示了Python在快速开发图形界面应用方面的强大能力。通过200行左右的代码,我们实现了一个功能完整、可玩性强的经典游戏。Python的"骚"不仅体现在语法简洁上,更体现在其丰富的生态系统和无限的可能性上。
mip.zhongyuwl.com
mip.xitengfei.com.cn
mip.jingchuanwh.com
mip.hbxwgc.com
mip.kolfamily.com
mip.hntjcw.com
mip.roadhere.com
mip.runyancn.com
mip.dsthing.com
mip.qdhmdmv.com