|
发表于 2023-11-26 14:13:10
|
显示全部楼层
在你提供的代码中,我看到了一些问题。
首先,在处理贪吃蛇移动的时候,你没有使用适当的数据结构来保存蛇身体的坐标。我建议使用一个列表来保存蛇身体的每个部分的坐标。每当蛇移动的时候,你需要将新的头部坐标插入到列表的第一个位置,并且删除列表的最后一个元素。这样就能实现蛇的增长和移动。
其次,在控制方向的部分,你需要根据用户按下的键来改变蛇头移动的方向。你可以通过监听键盘事件来获取用户按下的键,并根据不同的按键设置不同的移动方向。
最后,在金币生成的部分,你需要将金币添加到`Money`组中,并在每一帧中更新金币的位置。当蛇头碰到金币时,你需要增加得分并生成新的金币。同时,你还需要在每一帧中检测蛇头是否和蛇身体碰撞,如果碰撞了,则游戏结束。
下面是修改后的代码示例:
- import pygame
- import sys
- import random
- from pygame.locals import *
- pygame.init()
- size = width, height = 600, 400
- bg = (255, 255, 255)
- YELLOW = (255, 255, 0)
- snake = (0, 255, 0)
- BLACK = (0, 0, 0)
- screen = pygame.display.set_mode(size)
- pygame.display.set_caption('贪吃蛇')
- move = USEREVENT
- pygame.time.set_timer(move, 200) # 设置蛇移动的时间间隔
- score = 0
- score_font = pygame.font.Font(None, 20)
- snake_body = [(300, 200)] # 蛇身体坐标列表
- direction = 'right'
- def generate_food():
- x = random.randint(0, width-10)
- y = random.randint(0, height-10)
- return (x//10 * 10, y//10 * 10)
- food = generate_food()
- while True:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- sys.exit()
- elif event.type == move:
- if direction == 'right':
- head_x = snake_body[0][0] + 10
- head_y = snake_body[0][1]
- elif direction == 'left':
- head_x = snake_body[0][0] - 10
- head_y = snake_body[0][1]
- elif direction == 'up':
- head_x = snake_body[0][0]
- head_y = snake_body[0][1] - 10
- elif direction == 'down':
- head_x = snake_body[0][0]
- head_y = snake_body[0][1] + 10
-
- snake_body.insert(0, (head_x, head_y)) # 插入新的蛇头位置
- snake_body.pop() # 删除最后一个蛇身部分
-
- key_pressed = pygame.key.get_pressed()
- if key_pressed[K_RIGHT] and direction != 'left':
- direction = 'right'
- elif key_pressed[K_LEFT] and direction != 'right':
- direction = 'left'
- elif key_pressed[K_UP] and direction != 'down':
- direction = 'up'
- elif key_pressed[K_DOWN] and direction != 'up':
- direction = 'down'
- if snake_body[0] == food:
- score += 10
- food = generate_food()
- # 在蛇尾增加一个身体部分
- snake_body.append(snake_body[-1])
- screen.fill(bg)
- for body_part in snake_body:
- pygame.draw.rect(screen, snake, (*body_part, 10, 10))
- pygame.draw.rect(screen, YELLOW, (*food, 10, 10))
- score_text = score_font.render(f'Score: {score}', True, BLACK)
- screen.blit(score_text, (10, 5))
- pygame.display.flip()
复制代码
你可以根据自己的需求对代码进行进一步的修改和完善。希望能帮到你解决问题!
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。 |
|