pycharm编写贪吃蛇小游戏
时间: 2023-07-07 07:44:39 浏览: 154
Sudoku,ChromeDragon,FlippyBird,YummySnake
好的,下面是一个简单的贪吃蛇小游戏的代码实现,使用PyCharm编写:
```python
import random
import pygame
from pygame.locals import *
# 定义颜色变量
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# 定义游戏结束函数
def game_over():
pygame.quit()
sys.exit()
# 定义主函数
def main():
# 初始化pygame
pygame.init()
# 设置游戏窗口大小和标题
play_surface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('贪吃蛇')
# 初始化变量
snake_position = [100, 100]
snake_body = [[100, 100], [80, 100], [60, 100]]
food_position = [300, 300]
food_spawned = 1
direction = 'RIGHT'
change_direction_to = direction
score = 0
# 定义计时器
fps_controller = pygame.time.Clock()
# 开始游戏主循环
while True:
# 监听事件
for event in pygame.event.get():
if event.type == QUIT:
game_over()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
change_direction_to = 'RIGHT'
if event.key == K_LEFT or event.key == ord('a'):
change_direction_to = 'LEFT'
if event.key == K_UP or event.key == ord('w'):
change_direction_to = 'UP'
if event.key == K_DOWN or event.key == ord('s'):
change_direction_to = 'DOWN'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# 判断是否改变方向
if change_direction_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
if change_direction_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_direction_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_direction_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
# 根据方向移动蛇头
if direction == 'RIGHT':
snake_position[0] += 20
if direction == 'LEFT':
snake_position[0] -= 20
if direction == 'UP':
snake_position[1] -= 20
if direction == 'DOWN':
snake_position[1] += 20
# 增加蛇身
snake_body.insert(0, list(snake_position))
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
food_spawned = 0
score += 1
else:
snake_body.pop()
# 生成食物
if food_spawned == 0:
food_position = [random.randrange(1, 32) * 20, random.randrange(1, 24) * 20]
food_spawned = 1
# 绘制游戏界面
play_surface.fill(black)
for position in snake_body:
pygame.draw.rect(play_surface, green, Rect(position[0], position[1], 20, 20))
pygame.draw.rect(play_surface, white, Rect(food_position[0], food_position[1], 20, 20))
# 刷新游戏界面
pygame.display.flip()
# 判断游戏是否结束
if snake_position[0] < 0 or snake_position[0] > 620:
game_over()
if snake_position[1] < 0 or snake_position[1] > 460:
game_over()
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
# 控制游戏帧率
fps_controller.tick(10)
if __name__ == '__main__':
main()
```
运行以上代码,即可开始游戏,使用方向键或wasd键控制蛇的移动方向,吃到食物加分,碰到边界或自身游戏结束。
阅读全文