Python实现的贪吃蛇小游戏代码.pdf
Python实现的贪吃蛇小游戏代码--第1页
以下是Python实现的贪吃蛇小游戏代码:
```python
importpygame
importrandom
#初始化Pygame
pygame.init()
#设置游戏窗口大小和标题
screen_width=480
screen_height=480
game_display=pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption(贪吃蛇游戏)
#定义颜色
white=(255,255,255)
black=(0,0,0)
red=(255,0,0)
green=(0,255,0)
#定义蛇的初始位置和尺寸
snake_block_size=20
snake_speed=10
initial_snake_pos={x:screen_width/2,y:screen_height/2}
snake_list=[initial_snake_pos]
#定义食物的尺寸和位置
food_block_size=20
food_pos={x:round(random.randrange(0,screen_width-food_block_size)/20.0)*20.0,
y:round(random.randrange(0,screen_height-food_block_size)/20.0)*20.0}
#定义分数、字体和大小
score=0
font_style=pygame.font.SysFont(None,30)
#刷新分数
defrefresh_score(score):
game_display.blit(score_text,[0,0])
#绘制蛇
defdraw_snake(snake_block_size,snake_list):
forposinsnake_list:
Python实现的贪吃蛇小游戏代码--第1页
Python实现的贪吃蛇小游戏代码--第2页
pygame.draw.rect(game_display,green,[pos[x],pos[y],snake_block_size,
snake_block_size])
#显示消息
defmessage(msg,color):
message_text=font_style.render(msg,True,color)
game_display.blit(message_text,[screen_width/6,screen_height/3])
#主函数循环
defgame_loop():
game_over=False
game_close=False
#设置蛇头的初始移动方向
x_change=0
y_change=0
#处理事件
while