赞
踩
import pygame
import random
from tkinter import messagebox
# 初始化pygame
pygame.init()
# 设置游戏窗口的大小和标题
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇和食物的初始位置和大小
snake_pos = [[320, 240]]
snake_len = 1
food_pos = [random.randint(0, 31) * 20, random.randint(0, 23) * 20]
# 定义游戏结束标志和分数
game_over = False
score = 0
# 定义蛇的移动方向和速度
direction = 'space'
speed = [0, 0]
# 加载字体和音效
font = pygame.font.Font(None, 36)
# sound_eat = pygame.mixer.Sound('eat.wav')
# sound_hit = pygame.mixer.Sound('hit.wav')
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != 'down':
direction = 'up'
speed = [0, -20]
elif event.key == pygame.K_DOWN and direction != 'up':
direction = 'down'
speed = [0, 20]
elif event.key == pygame.K_LEFT and direction != 'right':
direction = 'left'
speed = [-20, 0]
elif event.key == pygame.K_RIGHT and direction != 'left':
direction = 'right'
speed = [20, 0]
elif event.key == pygame.K_SPACE and direction != 'space':
direction = 'space'
speed = [0, 0]
elif event.key == pygame.K_ESCAPE and direction != 'ESC':
direction = 'esc'
game_over = True
# 更新蛇的位置和长度
snake_pos.insert(0, [snake_pos[0][0] + speed[0], snake_pos[0][1] + speed[1]])
if snake_pos[0] == food_pos:
food_pos = [random.randint(0, 31) * 20, random.randint(0, 23) * 20]
snake_len += 1
score += 10
# sound_eat.play()
else:
snake_pos.pop()
if len(snake_pos) > snake_len:
snake_pos.pop()
if snake_pos[0][0] < 0 or snake_pos[0][0] >= width or snake_pos[0][1] < 0 or snake_pos[0][1] >= height:
game_over = True
# sound_hit.play()
for i in range(1, len(snake_pos)):
if snake_pos[0] == snake_pos[i]:
game_over = True
# sound_hit.play()
# 在屏幕上绘制游戏元素
screen.fill(black)
pygame.draw.rect(screen, white, [food_pos[0], food_pos[1], 20, 20])
for pos in snake_pos:
pygame.draw.rect(screen, red, [pos[0], pos[1], 20, 20])
score_text = font.render('Score: ' + str(score), True, white)
screen.blit(score_text, [10, 10])
pygame.display.flip()
#pygame.time.wait(200)
# 控制游戏速度,数值越小速度越快,可以根据需要调整。
# 注意,该数值不能太大,否则游戏会变慢。
# 另外,该数值也不能太小,否则游戏会变快,而且可能会因为计算机性能不够而出现卡顿现象。
# 最好的办法是根据自己的计算机性能进行尝试和调整。另外,也可以使用pygame.time.Clock()对象来控制游戏速度。
# 具体使用方法可以参考pygame官方文档。例如:clock = pygame.time.Clock();clock.tick(60)。这样
pygame.time.wait(200)
messagebox.showinfo("Message", "Game, over!")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。