鱼C论坛

 找回密码
 立即注册
查看: 1854|回复: 4

pygame贪吃蛇问题

[复制链接]
发表于 2023-11-26 20:37:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #贪吃蛇.py
  2. import pygame
  3. import sys
  4. from pygame.locals import *
  5. import 金币
  6. import 蛇身
  7. pygame.init()
  8. pygame.mixer.init()
  9. size = width, height = 600, 400
  10. bg = (0, 0, 255)
  11. YELLOW = (255, 255, 0)
  12. snake = (0, 255, 0)
  13. white = (255, 255, 255)
  14. Sbody = {}
  15. fanxiang = 'right'
  16. left = 300
  17. top = 200
  18. pygame.mouse.set_visible(False)
  19. #pygame.mixer.music.load('Ximalaya-4.0.0_99B_sc100006.exe')
  20. pygame.mixer.music.load('game_music.ogg')
  21. pygame.mixer.music.set_volume(1)
  22. a = pygame.mixer.Sound('upgrade.wav')
  23. screen = pygame.display.set_mode(size)
  24. pygame.display.set_caption('贪吃蛇')
  25. move = USEREVENT
  26. pygame.time.set_timer(move, 1 * 100)
  27. money = USEREVENT + 1
  28. pygame.time.set_timer(money, 5 * 1000)
  29. score = 0
  30. score_font = pygame.font.Font(None, 20)
  31. GameOver_font = pygame.font.Font(None, 100)
  32. Money = pygame.sprite.Group()
  33. snakebody = pygame.sprite.Group()
  34. pygame.mixer.music.play()
  35. running = True
  36. clock = pygame.time.Clock()



  37. while running:   
  38.     for event in pygame.event.get():
  39.         if event.type == pygame.QUIT:
  40.             sys.exit()
  41.         elif event.type == move:
  42.             if fanxiang == 'left':
  43.                 Sbody[0] = [left, top]
  44.                 left -= 11
  45.                 for b in snakebody:
  46.                     Sbody[int(b.number)] = [b.width, b.height]
  47.                
  48.                
  49.             elif fanxiang == 'top':
  50.                 Sbody[0] = [left, top]
  51.                 top -= 11
  52.                 for b in snakebody:
  53.                     Sbody[int(b.number)] = [b.width, b.height]
  54.                
  55.                
  56.             elif fanxiang == 'right':
  57.                 Sbody[0] = [left, top]
  58.                 left += 11
  59.                 for b in snakebody:
  60.                     Sbody[int(b.number)] = [b.width, b.height]
  61.                
  62.                
  63.             elif fanxiang == 'bottom':
  64.                 Sbody[0] = [left, top]
  65.                 top += 11
  66.                 for b in snakebody:
  67.                     Sbody[int(b.number)] = [b.width, b.height]
  68.                
  69.                
  70.         
  71.         #生成金币
  72.         elif event.type == money:
  73.             print(left, top)
  74.             m = 金币.money()
  75.             Money.add(m)
  76.    
  77.     key_pressed = pygame.key.get_pressed()
  78.    
  79.     #控制方向
  80.     if key_pressed[K_w] or key_pressed[K_UP]:
  81.         fanxiang = 'top'
  82.     elif key_pressed[K_s] or key_pressed[K_DOWN]:
  83.         fanxiang = 'bottom'
  84.     elif key_pressed[K_d] or key_pressed[K_RIGHT]:
  85.         fanxiang = 'right'
  86.     elif key_pressed[K_a] or key_pressed[K_LEFT]:
  87.         fanxiang = 'left'

  88.     if left <= 0 or left >= 600 or top <= 0 or top >= 400:
  89.         pygame.mixer.music.stop()
  90.         #raise OSError('不能碰到身体或边缘!!!')
  91.         running = False
  92.         GameOver = True
  93.         

  94.     screen.fill(bg)
  95.     #蛇身机制
  96.     for b in snakebody:
  97.         lastnumber = b.number - 1
  98.         nextnumber = b.number + 1
  99.         
  100.         #pygame.time.delay(1)
  101.         #print(Sbody)
  102.         b.width = Sbody[lastnumber][0]
  103.         b.height = Sbody[lastnumber][1]
  104.         b.rect = pygame.Rect(b.width, b.height, 10, 10)
  105.         pygame.draw.rect(screen, snake, b.rect, 0)
  106.         if b.rect.colliderect(pygame.Rect(left, top, 10, 10)):
  107.             pygame.mixer.music.stop()
  108.             #raise OSError('不能碰到身体或边缘!!!')
  109.             running = False
  110.             GameOver = True
  111.             
  112.         
  113.     #金币机制
  114.     for i in Money:
  115.         pygame.draw.rect(screen, YELLOW, i.rect, 0)
  116.         if i.rect.colliderect(pygame.Rect(left, top, 10, 10)):
  117.             score+=1000
  118.             thousand = score / 1000
  119.             last = thousand - 1
  120.             #增加长度
  121.             s = 蛇身.body(int(Sbody[last][0]), int(Sbody[last][1]), thousand, size)
  122.             snakebody.add(s)
  123.             Money.remove(i)
  124.             a.play()
  125.     #绘制贪吃蛇
  126.     pygame.draw.rect(screen, snake, (left, top, 10, 10), 0)
  127.        #显示字迹
  128.     score_text = score_font.render(f'Score:{score}', True, white)
  129.     screen.blit(score_text, (10, 5))
  130.     pygame.display.flip()

  131. while GameOver:
  132.     #print('已经准备就绪!')
  133.     GameOver_text = GameOver_font.render('Game Over', True, white)
  134.     screen.blit(GameOver_text, (100, 100))
  135.     pygame.time.delay(1000)
  136.     clock.tick(1000)
复制代码

  1. #蛇身.py
  2. import pygame
  3. class body(pygame.sprite.Sprite):
  4.     def __init__(self, width, height, number, bg_size):
  5.         pygame.sprite.Sprite.__init__(self)
  6.         self.width = width
  7.         self.height = height
  8.         self.rect = pygame.Rect(self.width, self.height, 10, 10)
  9.         self.number = number
  10.         self.left = bg_size[0]
  11.         self.top = bg_size[1]
复制代码
  1. #金币.py
  2. import pygame
  3. import random
  4. class money(pygame.sprite.Sprite):
  5.     def __init__(self):
  6.         pygame.sprite.Sprite.__init__(self)
  7.         self.rect = pygame.Rect(random.randint(0, 590), random.randint(0, 390), 10, 10)
复制代码

不知道为什么游戏失败时突然卡住了,求各位帮忙修复,谢谢

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-11-26 20:37:48 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-11-26 20:38:01 | 显示全部楼层
在你的代码中,有几个地方可能导致游戏失败时卡住:

1. 在主循环中的`for event in pygame.event.get():`循环中,当检测到"QUIT"事件后应该退出游戏,但你的代码中只是调用了`sys.exit()`,并没有将`running`置为`False`。所以可以修改为 `running = False`,这样就能正确退出主循环。

2. 在主循环中的键盘控制部分,你使用了`or`逻辑运算符,这是错误的。应该使用`and`逻辑运算符来判断多个按键的组合。例如,应该将 `if key_pressed: fanxiang = 'top'` 修改为 `if key_pressed[K_w] and not key_pressed[K_s]: fanxiang = 'top'`。

3. 判断是否碰到边缘的条件语句有错误。在 `if left = 600 or top = 400:` 这一行中,应该使用相等比较运算符`==`而不是赋值运算符`=`。 所以应该修改为 `if left == 600 or top == 400:`。

修复以上问题后,你的代码应该能够正确处理游戏失败,并退出主循环。

另外,你的代码中存在一些不规范的写法和缺少部分代码,下面是修改后的代码示例:
  1. # 贪吃蛇.py
  2. import pygame
  3. import sys
  4. from pygame.locals import *
  5. import 金币
  6. import 蛇身
  7. pygame.init()
  8. pygame.mixer.init()
  9. size = width, height = 600, 400
  10. bg = (0, 0, 255)
  11. YELLOW = (255, 255, 0)
  12. snake = (0, 255, 0)
  13. white = (255, 255, 255)
  14. Sbody = 10 # 初始蛇身大小
  15. fanxiang = 'right'
  16. left = 300
  17. top = 200
  18. pygame.mouse.set_visible(False)
  19. pygame.mixer.music.load('game_music.ogg')
  20. pygame.mixer.music.set_volume(1)
  21. a = pygame.mixer.Sound('upgrade.wav')
  22. screen = pygame.display.set_mode(size)
  23. pygame.display.set_caption('贪吃蛇')
  24. move = USEREVENT
  25. pygame.time.set_timer(move, 1 * 100)
  26. money = USEREVENT + 1
  27. pygame.time.set_timer(money, 5 * 1000)
  28. score = 0
  29. score_font = pygame.font.Font(None, 20)
  30. GameOver_font = pygame.font.Font(None, 100)
  31. Money = pygame.sprite.Group()
  32. snakebody = pygame.sprite.Group()
  33. pygame.mixer.music.play()
  34. running = True
  35. clock = pygame.time.Clock()
  36. while running:   
  37.     for event in pygame.event.get():
  38.         if event.type == pygame.QUIT:
  39.             running = False
  40.         elif event.type == move:
  41.             if fanxiang == 'left':
  42.                 left -= 11
  43.             elif fanxiang == 'top':
  44.                 top -= 11
  45.             elif fanxiang == 'right':
  46.                 left += 11
  47.             elif fanxiang == 'bottom':
  48.                 top += 11
  49.         
  50.         # 生成金币
  51.         elif event.type == money:
  52.             m = 金币.money()
  53.             Money.add(m)
  54.    
  55.     key_pressed = pygame.key.get_pressed()
  56.    
  57.     # 控制方向
  58.     if key_pressed[K_w] and not key_pressed[K_s]:
  59.         fanxiang = 'top'
  60.     elif key_pressed[K_s] and not key_pressed[K_w]:
  61.         fanxiang = 'bottom'
  62.     elif key_pressed[K_d] and not key_pressed[K_a]:
  63.         fanxiang = 'right'
  64.     elif key_pressed[K_a] and not key_pressed[K_d]:
  65.         fanxiang = 'left'
  66.     if left >= 600 or top >= 400:
  67.         pygame.mixer.music.stop()
  68.         running = False
  69.         
  70.     screen.fill(bg)
  71.    
  72.     # 蛇身机制
  73.     for b in snakebody:
  74.         lastnumber = b.number - 1
  75.         nextnumber = b.number + 1
  76.         
  77.         b.width = Sbody
  78.         b.height = Sbody
  79.         b.rect = pygame.Rect(b.width, b.height, 10, 10)
  80.         pygame.draw.rect(screen, snake, b.rect, 0)
  81.         if b.rect.colliderect(pygame.Rect(left, top, 10, 10)):
  82.             pygame.mixer.music.stop()
  83.             running = False
  84.             
  85.     # 金币机制
  86.     for i in Money:
  87.         pygame.draw.rect(screen, YELLOW, i.rect, 0)
  88.         if i.rect.colliderect(pygame.Rect(left, top, 10, 10)):
  89.             score += 1000
  90.             thousand = score // 1000
  91.             last = thousand - 1
  92.             # 增加长度
  93.             s = 蛇身.body(int(Sbody), int(Sbody), thousand, size)
  94.             snakebody.add(s)
  95.             Money.remove(i)
  96.             a.play()
  97.             
  98.     # 绘制贪吃蛇
  99.     pygame.draw.rect(screen, snake, (left, top, 10, 10), 0)
  100.    
  101.     # 显示字迹
  102.     score_text = score_font.render(f'Score:{score}', True, white)
  103.     screen.blit(score_text, (10, 5))
  104.    
  105.     pygame.display.flip()
  106. GameOver = True
  107. while GameOver:
  108.     GameOver_text = GameOver_font.render('Game Over', True, white)
  109.     screen.blit(GameOver_text, (100, 100))
  110.     pygame.time.delay(1000)
  111.     clock.tick(1000)
复制代码

希望这能帮助到你修复问题。如果还有其他问题,请随时问我。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-11-26 20:49:03 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-11-26 20:49:24 | 显示全部楼层

抱歉,我之前的回答有错误,我理解错了你的代码问题。真正导致游戏卡住的原因是因为在主循环中没有处理事件监听与更新屏幕的间隔时间。

下面是修复问题的修改代码:
  1. import pygame
  2. import sys
  3. from pygame.locals import *
  4. import random
  5. pygame.init()
  6. size = width, height = 600, 400
  7. bg = (0, 0, 255)
  8. YELLOW = (255, 255, 0)
  9. snake = (0, 255, 0)
  10. white = (255, 255, 255)
  11. Sbody = 10 # 初始蛇身大小
  12. fanxiang = 'right'
  13. left = 300
  14. top = 200
  15. screen = pygame.display.set_mode(size)
  16. pygame.display.set_caption('贪吃蛇')
  17. clock = pygame.time.Clock()
  18. class SnakeBody(pygame.sprite.Sprite):
  19.     def __init__(self, width, height):
  20.         pygame.sprite.Sprite.__init__(self)
  21.         self.image = pygame.Surface((10, 10))
  22.         self.image.fill(snake)
  23.         self.rect = self.image.get_rect()
  24.         self.rect.x = width
  25.         self.rect.y = height
  26. class Money(pygame.sprite.Sprite):
  27.     def __init__(self):
  28.         pygame.sprite.Sprite.__init__(self)
  29.         self.image = pygame.Surface((10, 10))
  30.         self.image.fill(YELLOW)
  31.         self.rect = self.image.get_rect()
  32.         self.rect.x = random.randint(0, 590)
  33.         self.rect.y = random.randint(0, 390)
  34. snakebody = pygame.sprite.Group()
  35. moneygroup = pygame.sprite.Group()
  36. score = 0
  37. score_font = pygame.font.Font(None, 20)
  38. GameOver_font = pygame.font.Font(None, 100)
  39. running = True
  40. move_event = pygame.USEREVENT
  41. money_event = pygame.USEREVENT + 1
  42. pygame.time.set_timer(move_event, 100)
  43. pygame.time.set_timer(money_event, 5000)
  44. while running:
  45.     for event in pygame.event.get():
  46.         if event.type == pygame.QUIT:
  47.             running = False
  48.         elif event.type == move_event:
  49.             if fanxiang == 'left':
  50.                 left -= 11
  51.             elif fanxiang == 'top':
  52.                 top -= 11
  53.             elif fanxiang == 'right':
  54.                 left += 11
  55.             elif fanxiang == 'bottom':
  56.                 top += 11
  57.         elif event.type == money_event:
  58.             m = Money()
  59.             moneygroup.add(m)
  60.     key_pressed = pygame.key.get_pressed()
  61.     if key_pressed[K_UP] and not key_pressed[K_DOWN]:
  62.         fanxiang = 'top'
  63.     elif key_pressed[K_DOWN] and not key_pressed[K_UP]:
  64.         fanxiang = 'bottom'
  65.     elif key_pressed[K_RIGHT] and not key_pressed[K_LEFT]:
  66.         fanxiang = 'right'
  67.     elif key_pressed[K_LEFT] and not key_pressed[K_RIGHT]:
  68.         fanxiang = 'left'
  69.     snakebody.update()
  70.    
  71.     screen.fill(bg)
  72.     snakebody.draw(screen)
  73.     moneygroup.draw(screen)
  74.     for b in snakebody:
  75.         if b.rect.colliderect(pygame.Rect(left, top, 10, 10)):
  76.             running = False
  77.     for i in moneygroup:
  78.         if i.rect.colliderect(pygame.Rect(left, top, 10, 10)):
  79.             score += 1000
  80.             thousand = score // 1000
  81.             last = thousand - 1
  82.             s = SnakeBody(int(left), int(top))
  83.             snakebody.add(s)
  84.             moneygroup.remove(i)
  85.     score_text = score_font.render(f'Score:{score}', True, white)
  86.     screen.blit(score_text, (10, 5))
  87.     pygame.display.flip()
  88.     clock.tick(10)
  89. pygame.quit()
  90. sys.exit()
复制代码

希望这次能解决你的问题。如果还有其他问题,请随时问我。

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-24 08:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表