|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#贪吃蛇.py
import pygame
import sys
from pygame.locals import *
import 金币
import 蛇身
pygame.init()
size = width, height = 600, 400
bg = (255, 255, 255)
YELLOW = (255, 255, 0)
snake = (0, 255, 0)
BLACK = (0, 0, 0)
Sbody = {}
fanxiang = 'right'
left = 300
top = 200
screen = pygame.display.set_mode(size)
pygame.display.set_caption('贪吃蛇')
move = USEREVENT
pygame.time.set_timer(move, 1 * 100)
money = USEREVENT + 1
pygame.time.set_timer(money, 5 * 1000)
score = 0
score_font = pygame.font.Font(None, 20)
Money = pygame.sprite.Group()
snakebody = pygame.sprite.Group()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == move:
if fanxiang == 'left':
Sbody[0] = [left, top]
left -= 11
elif fanxiang == 'top':
Sbody[0] = [left, top]
top -= 11
elif fanxiang == 'right':
Sbody[0] = [left, top]
left += 11
elif fanxiang == 'bottom':
Sbody[0] = [left, top]
top += 11
#生成金币
elif event.type == money:
m = 金币.money()
Money.add(m)
key_pressed = pygame.key.get_pressed()
#控制方向
if key_pressed[K_w] or key_pressed[K_UP]:
fanxiang = 'top'
if key_pressed[K_s] or key_pressed[K_DOWN]:
fanxiang = 'bottom'
if key_pressed[K_d] or key_pressed[K_RIGHT]:
fanxiang = 'right'
if key_pressed[K_a] or key_pressed[K_LEFT]:
fanxiang = 'left'
screen.fill(bg)
#蛇身机制
for b in snakebody:
lastnumber = b.number - 1
nextnumber = b.number + 1
Sbody[b.number] = [b.width, b.height]
b.width = Sbody[lastnumber][0]
b.height = Sbody[lastnumber][1]
b.rect = pygame.Rect(b.width, b.height, 10, 10)
pygame.draw.rect(screen, snake, b.rect, 0)
#金币机制
for i in Money:
pygame.draw.rect(screen, YELLOW, i.rect, 0)
if i.rect.colliderect(pygame.Rect(left, top, 10, 10)):
score+=1000
thousand = score / 1000
#增加长度
s = 蛇身.body(int(Sbody[thousand - 1][0]), int(Sbody[thousand - 1][1]), thousand)
snakebody.add(s)
Money.remove(i)
#绘制贪吃蛇
pygame.draw.rect(screen, snake, (left, top, 10, 10), 0)
#显示字迹
score_text = score_font.render(f'Score:{score}', True, BLACK)
screen.blit(score_text, (10, 5))
pygame.display.flip()
#蛇身.py
import pygame
class body(pygame.sprite.Sprite):
def __init__(self, width, height, number):
pygame.sprite.Sprite.__init__(self)
self.width = width
self.height = height
self.rect = pygame.Rect(self.width, self.height, 10, 10)
self.number = number
想请教一下如何做到蛇身完全加长且不有bug(吃了两个金币后才有bug)?
|
|