151,848
社区成员
发帖
与我相关
我的任务
分享
import pygame # 导入pygame模块,用于绘制图形界面
import sys # 导入sys模块,用于退出程序
import random # 导入random模块,用于生成随机数
#定义常量
# 定义屏幕的宽度和高度(单位:像素)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 定义蛇的宽度和高度(单位:像素)
SNAKE_WIDTH = 20
SNAKE_HEIGHT = 20
# 定义食物的宽度和高度(单位:像素)
FOOD_WIDTH = 20
FOOD_HEIGHT = 20
# 定义蛇的移动速度(单位:像素/帧)
SNAKE_SPEED = 3
# 定义颜色(RGB值)
WHITE = (255, 255, 255) # 白色
BLACK = (0, 0, 0) # 黑色
RED = (255, 0, 0) # 红色
GREEN = (0, 255, 0) # 绿色
BLUE = (0, 0, 255) # 蓝色
#初始化游戏
# 初始化pygame模块
pygame.init()
# 创建一个窗口对象,设置窗口的大小和标题
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 创建一个时钟对象,用于控制游戏的帧率
clock = pygame.time.Clock()
# 创建一个字体对象,用于绘制文字
font = pygame.font.SysFont('arial', 32)
# 创建一个蛇对象,用于存储蛇的位置和方向
snake = pygame.Rect(400, 300, SNAKE_WIDTH, SNAKE_HEIGHT) # 初始位置在屏幕中央,初始大小为20*20像素
snake_direction = 'right' # 初始方向向右
# 创建一个食物对象,用于存储食物的位置
food = pygame.Rect(random.randint(0, SCREEN_WIDTH - FOOD_WIDTH), random.randint(0, SCREEN_HEIGHT - FOOD_HEIGHT), FOOD_WIDTH, FOOD_HEIGHT) # 随机生成食物的位置,大小为20*20像素
# 创建一个列表对象,用于存储蛇的身体
snake_body = []
# 创建一个整数对象,用于存储得分
score = 0
# 创建一个布尔对象,用于判断游戏是否结束
game_over = False
#主循环
# 进入主循环
while True:
# 处理事件
for event in pygame.event.get():
# 如果点击了关闭按钮,退出程序
if event.type == pygame.QUIT:
sys.exit()
# 如果按下了键盘,改变蛇的方向(不能反向移动)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
elif event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
# 更新游戏逻辑
if not game_over: # 如果游戏没有结束
# 根据蛇的方向移动蛇的位置(每帧移动10像素)
if snake_direction == 'up':
snake.y -= SNAKE_SPEED
elif snake_direction == 'down':
snake.y += SNAKE_SPEED
elif snake_direction == 'left':
snake.x -= SNAKE_SPEED
elif snake_direction == 'right':
snake.x += SNAKE_SPEED
# 将蛇的头部添加到蛇的身体列表中(注意要复制一份,否则会引用同一个对象)
snake_body.append(snake.copy())
# 如果蛇的身体列表的长度大于得分,删除最后一个元素(即蛇的尾部)
if len(snake_body) > score:
del snake_body[0]
# 判断蛇是否吃到了食物(如果蛇的头部和食物重叠)
if snake.colliderect(food):
# 得分加一
score += 1
# 随机生成新的食物位置(避免与蛇的身体重叠)
while True:
food.x = random.randint(0, SCREEN_WIDTH - FOOD_WIDTH)
food.y = random.randint(0, SCREEN_HEIGHT - FOOD_HEIGHT)
for body in snake_body:
if food.colliderect(body):
break # 如果食物与蛇的身体重叠,重新生成食物位置
else:
break # 如果食物没有与蛇的身体重叠,跳出循环
# 判断蛇是否撞到了边界或自己(如果蛇的头部超出屏幕范围或与自己的身体重叠)
if snake.x < 0 or snake.x > SCREEN_WIDTH - SNAKE_WIDTH or snake.y < 0 or snake.y > SCREEN_HEIGHT - SNAKE_HEIGHT:
game_over = True # 游戏结束标志设为True
for body in snake_body[:-1]: # 遍历蛇的身体列表(除了最后一个元素,即蛇的头部)
if snake.colliderect(body): # 如果蛇的头部与身体重叠
game_over = True # 游戏结束标志设为True
# 绘制游戏画面
# 填充背景颜色为黑色
screen.fill(BLACK)
# 绘制食物为红色矩形
pygame.draw.rect(screen, RED, food)
# 绘制蛇的身体为绿色矩形(从后往前绘制,避免覆盖)
for body in reversed(snake_body):
pygame.draw.rect(screen, WHITE, snake_body)
# 绘制得分为白色文字(左上角)
score_text = font.render(f'Score: {score}', True, WHITE)
screen.blit(score_text, (10, 10))
# 如果游戏结束,绘制“Game Over”为红色文字(居中)
if game_over:
game_over_text = font.render('Game Over', True, RED)
screen.blit(game_over_text, ((SCREEN_WIDTH - game_over_text.get_width()) // 2, (SCREEN_HEIGHT - game_over_text.get_height()) // 2))
# 更新屏幕显示
pygame.display.flip()
# 设置游戏帧率为30帧/秒
clock.tick(60)
import random
import sys
import time
import pygame
from pygame.locals import *
from collections import deque
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 480
SIZE = 20
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgText = font.render(text, True, fcolor)
screen.blit(imgText, (x, y))
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
light = (100, 100, 100)
dark = (200, 200, 200)
font1 = pygame.font.SysFont('SimHei', 24)
font2 = pygame.font.Font(None, 72)
red = (200, 30, 30)
fwidth, fheight = font2.size('GAME OVER')
line_width = 1
black = (0, 0, 0)
bgcolor = (40, 40, 60)
pos_x = 1
pos_y = 0
b = True
scope_x = (0, SCREEN_WIDTH // SIZE - 1)
scope_y = (2, SCREEN_HEIGHT // SIZE - 1)
snake = deque()
food_x = 0
food_y = 0
def _init_snake():
nonlocal snake
snake.clear()
snake.append((2, scope_y[0]))
snake.append((1, scope_y[0]))
snake.append((0, scope_y[0]))
def _create_food():
nonlocal food_x, food_y
food_x = random.randint(scope_x[0], scope_x[1])
food_y = random.randint(scope_y[0], scope_y[1])
while (food_x, food_y) in snake:
food_x = random.randint(scope_x[0], scope_x[1])
food_y = random.randint(scope_y[0], scope_y[1])
_init_snake()
_create_food()
game_over = True
start = False
score = 0
orispeed = 0.5
speed = orispeed
last_move_time = None
pause = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RETURN:
if game_over:
start = True
game_over = False
b = True
_init_snake()
_create_food()
pos_x = 1
pos_y = 0
score = 0
last_move_time = time.time()
elif event.key == K_SPACE:
if not game_over:
pause = not pause
elif event.key in (K_w, K_UP):
if b and not pos_y:
pos_x = 0
pos_y = -1
b = False
elif event.key in (K_s, K_DOWN):
if b and not pos_y:
pos_x = 0
pos_y = 1
b = False
elif event.key in (K_a, K_LEFT):
if b and not pos_x:
pos_x = -1
pos_y = 0
b = False
elif event.key in (K_d, K_RIGHT):
if b and not pos_x:
pos_x = 1
pos_y = 0
b = False
screen.fill(bgcolor)
for x in range(SIZE, SCREEN_WIDTH, SIZE):
pygame.draw.line(screen, black, (x, scope_y[0] * SIZE), (x, SCREEN_HEIGHT), line_width)
for y in range(scope_y[0] * SIZE, SCREEN_HEIGHT, SIZE):
pygame.draw.line(screen, black, (0, y), (SCREEN_WIDTH, y), line_width)
if game_over:
if start:
print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER',
red)
else:
curTime = time.time()
if curTime - last_move_time > speed:
if not pause:
b = True
last_move_time = curTime
next_s = (snake[0][0] + pos_x, snake[0][1] + pos_y)
if next_s[0] == food_x and next_s[1] == food_y:
_create_food()
snake.appendleft(next_s)
score += 10
speed = orispeed - 0.03 * (score // 100)
else:
if scope_x[0] <= next_s[0] <= scope_x[1] and scope_y[0] <= next_s[1] <= scope_y[1] \
and next_s not in snake:
snake.appendleft(next_s)
snake.pop()
else:
game_over = True
if not game_over:
pygame.draw.rect(screen, light, (food_x * SIZE, food_y * SIZE, SIZE, SIZE), 0)
for s in snake:
pygame.draw.rect(screen, dark, (s[0] * SIZE + line_width, s[1] * SIZE + line_width,
SIZE - line_width * 2, SIZE - line_width * 2), 0)
print_text(screen, font1, 30, 7, f'速度: {score // 100}')
print_text(screen, font1, 450, 7, f'得分: {score}')
pygame.display.update()
if __name__ == '__main__':
main()
import random
import sys
import time
import pygame
from pygame.locals import *
from collections import deque
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 480
SIZE = 20
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgText = font.render(text, True, fcolor)
screen.blit(imgText, (x, y))
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
light = (100, 100, 100)
dark = (200, 200, 200)
font1 = pygame.font.SysFont('SimHei', 24)
font2 = pygame.font.Font(None, 72)
red = (200, 30, 30)
fwidth, fheight = font2.size('GAME OVER')
line_width = 1
black = (0, 0, 0)
bgcolor = (40, 40, 60)
pos_x = 1
pos_y = 0
b = True
scope_x = (0, SCREEN_WIDTH // SIZE - 1)
scope_y = (2, SCREEN_HEIGHT // SIZE - 1)
snake = deque()
food_x = 0
food_y = 0
def _init_snake():
nonlocal snake
snake.clear()
snake.append((2, scope_y[0]))
snake.append((1, scope_y[0]))
snake.append((0, scope_y[0]))
def _create_food():
nonlocal food_x, food_y
food_x = random.randint(scope_x[0], scope_x[1])
food_y = random.randint(scope_y[0], scope_y[1])
while (food_x, food_y) in snake:
food_x = random.randint(scope_x[0], scope_x[1])
food_y = random.randint(scope_y[0], scope_y[1])
_init_snake()
_create_food()
game_over = True
start = False
score = 0
orispeed = 0.5
speed = orispeed
last_move_time = None
pause = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RETURN:
if game_over:
start = True
game_over = False
b = True
_init_snake()
_create_food()
pos_x = 1
pos_y = 0
score = 0
last_move_time = time.time()
elif event.key == K_SPACE:
if not game_over:
pause = not pause
elif event.key in (K_w, K_UP):
if b and not pos_y:
pos_x = 0
pos_y = -1
b = False
elif event.key in (K_s, K_DOWN):
if b and not pos_y:
pos_x = 0
pos_y = 1
b = False
elif event.key in (K_a, K_LEFT):
if b and not pos_x:
pos_x = -1
pos_y = 0
b = False
elif event.key in (K_d, K_RIGHT):
if b and not pos_x:
pos_x = 1
pos_y = 0
b = False
screen.fill(bgcolor)
for x in range(SIZE, SCREEN_WIDTH, SIZE):
pygame.draw.line(screen, black, (x, scope_y[0] * SIZE), (x, SCREEN_HEIGHT), line_width)
for y in range(scope_y[0] * SIZE, SCREEN_HEIGHT, SIZE):
pygame.draw.line(screen, black, (0, y), (SCREEN_WIDTH, y), line_width)
if game_over:
if start:
print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER',
red)
else:
curTime = time.time()
if curTime - last_move_time > speed:
if not pause:
b = True
last_move_time = curTime
next_s = (snake[0][0] + pos_x, snake[0][1] + pos_y)
if next_s[0] == food_x and next_s[1] == food_y:
_create_food()
snake.appendleft(next_s)
score += 10
speed = orispeed - 0.03 * (score // 100)
else:
if scope_x[0] <= next_s[0] <= scope_x[1] and scope_y[0] <= next_s[1] <= scope_y[1] \
and next_s not in snake:
snake.appendleft(next_s)
snake.pop()
else:
game_over = True
if not game_over:
pygame.draw.rect(screen, light, (food_x * SIZE, food_y * SIZE, SIZE, SIZE), 0)
for s in snake:
pygame.draw.rect(screen, dark, (s[0] * SIZE + line_width, s[1] * SIZE + line_width,
SIZE - line_width * 2, SIZE - line_width * 2), 0)
print_text(screen, font1, 30, 7, f'速度: {score // 100}')
print_text(screen, font1, 450, 7, f'得分: {score}')
pygame.display.update()
if __name__ == '__main__':
main()