求助,为什么写的一个贪吃蛇游戏看不见蛇身啊

追梦者ZX 2023-05-18 14:45:56
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)

 

...全文
140 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
韵日爱玩Web 2024-06-09
  • 打赏
  • 举报
回复

 
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()
 
Reaper ghost 2023-10-05
  • 打赏
  • 举报
回复

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()

基于C#.NET编程的游戏,本游戏实现了贪吃蛇的基本功能,需要要完善之处,望IT好友修正之。 程序功能 1)游戏选项:主要实现游戏的开始、暂停、退出,分别可以使用快捷键F2、空格键、F4。 2)设置: a)游戏难度等级设置:初级、中级、高级三个难度等级,每个难度等级又实现了三级加速,主要包括一级加速、二级加速、三级加速; b)蛇体颜色设置:绿色、红色、蓝色、黑色四种颜色可以选择; c) 蛇体宽度设置:初始大小、放大两倍、放大三倍三种选择; d)食物颜色设置:橙色、黄色、紫色三种颜色可以选择。 3)帮助:游戏操作说明,可以使用快捷键F3打开,主要介绍游戏的操作方法、以及版本信息、制作时间。 3.2设计思想 1)贪吃蛇的游戏规则:蛇头不能反向移动,若反向则保持原来的运动方向不变;不能碰到场地四周和自身,若碰到到四周墙壁或者自身,则游戏结束;当吃到食物后,应在随机生成一个新的坐标产生食物,并且食物不能再蛇身内生成;选择相应的游戏难度等级,当分数累加到一定程度以后,速度增加,每个等级有分为三个加速阶段。 2)游戏场地的绘制:将panel控件设计为游戏的背景,场地、贪吃蛇以及食物都是在panel控件中完成绘制。 3)蛇身和食物的绘制:本实验主要使用Graphics类在panel控件中绘制游戏的场地以及贪吃蛇、食物,食物模块、蛇身各模块的绘制是在单元格中进行绘制的,这样蛇身移动和食物生成过程中不需要重新绘制背景;根据蛇身模块宽度,可以改变蛇体的大小和场地坐标图方格的大小;根据食物类和蛇类各自的颜色变量,再通过菜单来改变其相应的颜色。 4)游戏的动态刷新控制:使用Timer组件来实现贪吃蛇的移动,通过设置该组件的Interval属性大小来控制移动的速度。 5)蛇身移动的实现:蛇身的移动主要是用ArrList类来实现的,该类的主要功能是使用大小可以根据需要动态增加数组,即建立动态数组来存储蛇身,本实验主要使用ArrList类的Insert方法和RemoveAt方法实现蛇模块的增加、蛇体移动的清除移动尾部。

151,848

社区成员

发帖
与我相关
我的任务
社区描述
欢迎加入hacker社区 博主致力于分享Python相关内容 人生苦短我用Python 期待和各位一同成长
后端python 个人社区
社区管理员
  • hacker707
  • 安然无虞
  • 小黎的培培笔录
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

人生苦短,我用Python

试试用AI创作助手写篇文章吧