|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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]
#pygame.time.delay(1)
#print(Sbody)
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
#增加长度
for b in snakebody:
lastnumber = b.number - 1
s = 蛇身.body(int(Sbody[lastnumber][0]), int(Sbody[lastnumber][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
金币.py
import pygame
import random
class money(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.Rect(random.randint(0, 590), random.randint(0, 390), 10, 10)@isdkz
麻烦修一下里面的bug(蛇的身体不会加长)谢谢(不准用AI回答)(所有代码已经粘贴好了,可以测试) |
|