Python 显示播放器';s在游戏中得分并更新它
我是编程新手,目前正在开发一款类似于松鼠游戏的游戏,在游戏中,你吃掉比你小的其他人,并受到比你大的人的伤害。我现在想显示球员的大小,这将做得很好,但它只显示开始大小。所以当我吃了一个敌人时,我希望数字会改变,但我不知道如何改变Python 显示播放器';s在游戏中得分并更新它,python,timer,pygame,display,Python,Timer,Pygame,Display,我是编程新手,目前正在开发一款类似于松鼠游戏的游戏,在游戏中,你吃掉比你小的其他人,并受到比你大的人的伤害。我现在想显示球员的大小,这将做得很好,但它只显示开始大小。所以当我吃了一个敌人时,我希望数字会改变,但我不知道如何改变 def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, L_SQUIR_IMG, R_SQUIR_IMG, GRASSIMAGES, MEL, MER, L_SQUIR_IMG2, R_SQUIR_IMG2
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT, L_SQUIR_IMG, R_SQUIR_IMG, GRASSIMAGES, MEL, MER, L_SQUIR_IMG2, R_SQUIR_IMG2
pygame.init()
FPSCLOCK = pygame.time.Clock()
pygame.display.set_icon(pygame.image.load('cat.png'))
DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))
pygame.display.set_caption('Space CAT')
BASICFONT = pygame.font.Font('freesansbold.ttf', 32)
# load the image files
MEL = pygame.image.load("cat.png")
MER = pygame.transform.flip(MEL, True, False)
L_SQUIR_IMG = pygame.image.load("foe1.png")
R_SQUIR_IMG = pygame.transform.flip(L_SQUIR_IMG, True, False)
L_SQUIR_IMG2 = pygame.image.load("spacemouse2.png")
R_SQUIR_IMG2 = pygame.transform.flip(L_SQUIR_IMG2, True, False)
GRASSIMAGES = []
for i in range(1, 5):
GRASSIMAGES.append(pygame.image.load("grass%s.png" % i))
while True:
runGame()
def runGame():
# set up variables for the start of a new game
invulnerableMode = False # if the player is invulnerable
invulnerableStartTime = 0 # time the player became invulnerable
gameOverMode = False # if the player has lost
gameOverStartTime = 0 # time the player lost
winMode = False # if the player has won
Level2 = False # if Level 2 is reached
# create the surfaces to hold game text
gameOverSurf = BASICFONT.render('Game Over', True, WHITE)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.center = (HALF_WINWIDTH, HALF_WINHEIGHT)
winSurf = BASICFONT.render('You have achieved ALPHA CAT!', True, WHITE)
winRect = winSurf.get_rect()
winRect.center = (HALF_WINWIDTH, HALF_WINHEIGHT)
winSurf2 = BASICFONT.render('(Press "r" to restart.)', True, WHITE)
winRect2 = winSurf2.get_rect()
winRect2.center = (HALF_WINWIDTH, HALF_WINHEIGHT + 30)
winSurf3 = BASICFONT.render('You have reached Level 2', True, WHITE)
winRect3 = winSurf3.get_rect()
winRect3.center = (HALF_WINWIDTH, HALF_WINHEIGHT)
# camerax and cameray are the top left of where the camera view is
camerax = 0
cameray = 0
grassObjs = [] # stores all the star objects in the game
squirrelObjs = [] # stores all the non-player fish objects
squirrelObjs2 = [] #stores all the non-player mouse objects
# stores the player object:
playerObj = {'surface': pygame.transform.scale(MEL, (STARTSIZE, STARTSIZE)),
'facing': LEFT,
'size': STARTSIZE,
'x': HALF_WINWIDTH,
'y': HALF_WINHEIGHT,
'bounce':0,
'health': MAXHEALTH}
# show the player's score
winSurf4 = BASICFONT.render(str(playerObj['size']), True, RED)
winRect4 = winSurf4.get_rect()
winRect4.center = (HALF_WINWIDTH + 680, HALF_WINHEIGHT - 420)
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
# start off with some random grass images on the screen
for i in range(7):
grassObjs.append(makeNewGrass(camerax, cameray))
grassObjs[i]['x'] = random.randint(0, WINWIDTH)
grassObjs[i]['y'] = random.randint(0, WINHEIGHT)
while True: # main game loop
# Check if we should turn off invulnerability
if invulnerableMode and time.time() - invulnerableStartTime > INVULNTIME:
invulnerableMode = False
#### move all the fish
for sObj in squirrelObjs:
# move the fish, and adjust for their bounce
sObj['x'] += sObj['movex']
sObj['y'] += sObj['movey']
sObj['bounce'] += 0
if sObj['bounce'] > sObj['bouncerate']:
sObj['bounce'] = 0 # reset bounce amount
# random chance they change direction
if random.randint(0, 99) < DIRCHANGEFREQ:
sObj['movex'] = getRandomVelocity()
sObj['movey'] = getRandomVelocity()
if sObj['movex'] > 0: # faces right
sObj['surface'] = pygame.transform.scale(R_SQUIR_IMG, (sObj['width'], sObj['height']))
else: # faces left
sObj['surface'] = pygame.transform.scale(L_SQUIR_IMG, (sObj['width'], sObj['height']))
#### move all the mice
for sObj2 in squirrelObjs2:
# move the mice, and adjust for their bounce
sObj2['x'] += sObj2['movex']
sObj2['y'] += sObj2['movey']
sObj2['bounce'] += 0
if sObj2['bounce'] > sObj2['bouncerate']:
sObj2['bounce'] = 0 # reset bounce amount
# random chance they change direction
if random.randint(0, 99) < DIRCHANGEFREQ:
sObj2['movex'] = getRandomVelocity()
sObj2['movey'] = getRandomVelocity()
if sObj2['movex'] > 0: # faces right
sObj2['surface'] = pygame.transform.scale(R_SQUIR_IMG2, (sObj2['width'], sObj2['height']))
else: # faces left
sObj2['surface'] = pygame.transform.scale(L_SQUIR_IMG2, (sObj2['width'], sObj2['height']))
#### go through all the objects and see if any need to be deleted.(1)
for i in range(len(grassObjs) - 1, -1, -1):
if isOutsideActiveArea(camerax, cameray, grassObjs[i]):
del grassObjs[i]
for i in range(len(squirrelObjs) - 1, -1, -1):
if isOutsideActiveArea(camerax, cameray, squirrelObjs[i]):
del squirrelObjs[i]
#### go through all the objects and see if any need to be deleted.(2)
for i in range(len(squirrelObjs2) - 1, -1, -1):
if isOutsideActiveArea(camerax, cameray, squirrelObjs2[i]):
del squirrelObjs2[i]
#### add more stars & foes if we don't have enough.
while len(grassObjs) < NUMGRASS:
grassObjs.append(makeNewGrass(camerax, cameray))
if Level2 == False:
while len(squirrelObjs) < NUMSQUIRRELS:
squirrelObjs.append(makeNewFish(camerax, cameray))
#### Level 2 spawn mouse
if Level2 == True:
while len(squirrelObjs2) < NUMSQUIRRELS:
squirrelObjs2.append(makeNewMice(camerax, cameray))
# adjust camerax and cameray if beyond the "camera slack"
playerCenterx = playerObj['x'] + int(playerObj['size'] / 2)
playerCentery = playerObj['y'] + int(playerObj['size'] / 2)
if (camerax + HALF_WINWIDTH) - playerCenterx > CAMERASLACK:
camerax = playerCenterx + CAMERASLACK - HALF_WINWIDTH
elif playerCenterx - (camerax + HALF_WINWIDTH) > CAMERASLACK:
camerax = playerCenterx - CAMERASLACK - HALF_WINWIDTH
if (cameray + HALF_WINHEIGHT) - playerCentery > CAMERASLACK:
cameray = playerCentery + CAMERASLACK - HALF_WINHEIGHT
elif playerCentery - (cameray + HALF_WINHEIGHT) > CAMERASLACK:
cameray = playerCentery - CAMERASLACK - HALF_WINHEIGHT
# draw the black background
DISPLAYSURF.fill(GRASSCOLOR)
# draw all the grass objects on the screen
for gObj in grassObjs:
gRect = pygame.Rect( (gObj['x'] - camerax,
gObj['y'] - cameray,
gObj['width'],
gObj['height']) )
DISPLAYSURF.blit(GRASSIMAGES[gObj['grassImage']], gRect)
### draw the fish
for sObj in squirrelObjs:
sObj['rect'] = pygame.Rect( (sObj['x'] - camerax,
sObj['y'] - cameray - getBounceAmount(sObj['bounce'], sObj['bouncerate'], sObj['bounceheight']),
sObj['width'],
sObj['height']) )
DISPLAYSURF.blit(sObj['surface'], sObj['rect'])
### draw the mice
for sObj2 in squirrelObjs2:
sObj2['rect'] = pygame.Rect( (sObj2['x'] - camerax,
sObj2['y'] - cameray - getBounceAmount(sObj2['bounce'], sObj2['bouncerate'], sObj2['bounceheight']),
sObj2['width'],
sObj2['height']) )
DISPLAYSURF.blit(sObj2['surface'], sObj2['rect'])
### draw the player
flashIsOn = round(time.time(), 1) * 10 % 2 == 1
if not gameOverMode and not (invulnerableMode and flashIsOn):
playerObj['rect'] = pygame.Rect( (playerObj['x'] - camerax,
playerObj['y'] - cameray - getBounceAmount(playerObj['bounce'], BOUNCERATE, BOUNCEHEIGHT),
playerObj['size'],
playerObj['size']) )
DISPLAYSURF.blit(playerObj['surface'], playerObj['rect'])
### draw the health meter
drawHealthMeter(playerObj['health'])
for event in pygame.event.get(): # event handling loop
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if event.key in (K_UP, K_w):
moveDown = False
moveUp = True
elif event.key in (K_DOWN, K_s):
moveUp = False
moveDown = True
elif event.key in (K_LEFT, K_a):
moveRight = False
moveLeft = True
if playerObj['facing'] != LEFT: # change player image
playerObj['surface'] = pygame.transform.scale(MEL, (playerObj['size'], playerObj['size']))
playerObj['facing'] = LEFT
elif event.key in (K_RIGHT, K_d):
moveLeft = False
moveRight = True
if playerObj['facing'] != RIGHT: # change player image
playerObj['surface'] = pygame.transform.scale(MER, (playerObj['size'], playerObj['size']))
playerObj['facing'] = RIGHT
elif winMode and event.key == K_r:
return
elif event.type == KEYUP:
# stop moving the player
if event.key in (K_LEFT, K_a):
moveLeft = False
elif event.key in (K_RIGHT, K_d):
moveRight = False
elif event.key in (K_UP, K_w):
moveUp = False
elif event.key in (K_DOWN, K_s):
moveDown = False
elif event.key == K_ESCAPE:
terminate()
if not gameOverMode:
# actually move the player
if moveLeft:
playerObj['x'] -= MOVERATE
if moveRight:
playerObj['x'] += MOVERATE
if moveUp:
playerObj['y'] -= MOVERATE
if moveDown:
playerObj['y'] += MOVERATE
if (moveLeft or moveRight or moveUp or moveDown) or playerObj['bounce'] != 0:
playerObj['bounce'] += 0
if playerObj['bounce'] > BOUNCERATE:
playerObj['bounce'] = 0 # reset bounce amount
#### check if the player has collided with any fish
for i in range(len(squirrelObjs)-1, -1, -1):
sqObj = squirrelObjs[i]
if 'rect' in sqObj and playerObj['rect'].colliderect(sqObj['rect']):
# a player/fish collision has occurred
if sqObj['width'] * sqObj['height'] <= playerObj['size']**2:
# player is larger and eats the fish
playerObj['size'] += int( (sqObj['width'] * sqObj['height'])**0.2 ) + 1
del squirrelObjs[i]
if playerObj['facing'] == LEFT:
playerObj['surface'] = pygame.transform.scale(MEL, (playerObj['size'], playerObj['size']))
if playerObj['facing'] == RIGHT:
playerObj['surface'] = pygame.transform.scale(MER, (playerObj['size'], playerObj['size']))
if playerObj['size'] > WINSIZE/2:
Level2 = True # Turn on Level 2
if playerObj['size'] > WINSIZE:
winMode = True # turn on "win mode"
elif not invulnerableMode:
# player is smaller and takes damage
invulnerableMode = True
invulnerableStartTime = time.time()
playerObj['health'] -= 1
if playerObj['health'] == 0:
gameOverMode = True # turn on "game over mode"
gameOverStartTime = time.time()
### check if the player has collided with any mice
for i in range(len(squirrelObjs2)-1, -1, -1):
sqObj2 = squirrelObjs2[i]
if 'rect' in sqObj2 and playerObj['rect'].colliderect(sqObj2['rect']):
# a player/mouse collision has occurred
if sqObj2['width'] * sqObj2['height'] <= playerObj['size']**2:
# player is larger and eats the mouse
playerObj['size'] += int( (sqObj2['width'] * sqObj2['height'])**0.2 ) + 1
del squirrelObjs2[i]
if playerObj['facing'] == LEFT:
playerObj['surface'] = pygame.transform.scale(MEL, (playerObj['size'], playerObj['size']))
if playerObj['facing'] == RIGHT:
playerObj['surface'] = pygame.transform.scale(MER, (playerObj['size'], playerObj['size']))
if playerObj['size'] > WINSIZE/2:
Level2 = True # Turn on Level 2
if playerObj['size'] > WINSIZE:
winMode = True # turn on "win mode"
elif not invulnerableMode:
# player is smaller and takes damage
invulnerableMode = True
invulnerableStartTime = time.time()
playerObj['health'] -= 1
if playerObj['health'] == 0:
gameOverMode = True # turn on "game over mode"
gameOverStartTime = time.time()
else:
# game is over, show "game over" text
DISPLAYSURF.blit(gameOverSurf, gameOverRect)
if time.time() - gameOverStartTime > GAMEOVERTIME:
return # end the current game
# show the player's size
if not winMode:
DISPLAYSURF.blit(winSurf4, winRect4)
# check if the player has reached level 2.
if Level2 and playerObj['size'] < WINSIZE/2+10:
DISPLAYSURF.blit(winSurf3, winRect3)
# check if the player has won.
if winMode:
DISPLAYSURF.blit(winSurf, winRect)
DISPLAYSURF.blit(winSurf2, winRect2)
pygame.display.update()
FPSCLOCK.tick(FPS)
def main():
全球FPSCLOCK、DISPLAYSURF、BASICFONT、L_SQUIR_IMG、R_SQUIR_IMG、GRASSIMAGES、MEL、MER、L_SQUIR_IMG2、R_SQUIR_IMG2
pygame.init()
fpscall=pygame.time.Clock()
pygame.display.set_图标(pygame.image.load('cat.png'))
DISPLAYSURF=pygame.display.set_模式((WINWIDTH,WINHEIGHT))
pygame.display.set_标题('Space CAT'))
BASICFONT=pygame.font.font('freesansbold.ttf',32)
#加载图像文件
MEL=pygame.image.load(“cat.png”)
MER=pygame.transform.flip(MEL,真,假)
L_SQUIR_IMG=pygame.image.load(“foe1.png”)
R\u SQUIR\u IMG=pygame.transform.flip(L\u SQUIR\u IMG,True,False)
L_SQUIR_IMG2=pygame.image.load(“spacemouse2.png”)
R\u SQUIR\u IMG2=pygame.transform.flip(L\u SQUIR\u IMG2,真,假)
GRASSIMAGES=[]
对于范围(1,5)内的i:
GRASSIMAGES.append(pygame.image.load(“grass%s.png”%i))
尽管如此:
runGame()
def runGame():
#为新游戏的开始设置变量
无敌模式=假#如果玩家是无敌的
无敌开始时间=0#当玩家变得无敌时
gameOverMode=False#如果玩家输了
gameOverStartTime=0#玩家损失的时间
winMode=False#如果玩家赢了
Level2=False#如果达到2级
#创建用于保存游戏文本的曲面
gameOverSurf=BASICFONT.render('Game Over',True,白色)
gameOverRect=gameOverSurf.get_rect()
GameOverect.center=(半宽半高)
winSurf=BASICFONT.render('您已经实现了ALPHA CAT!',True,白色)
winRect=winSurf.get_rect()
winRect.center=(半宽半高)
winSurf2=BASICFONT.render(‘(按“r”重新启动。)’,True,白色)
winRect2=winSurf2.get_rect()
winRect2.center=(半宽半高+30)
winSurf3=BASICFONT.render('您已达到级别2',True,白色)
winRect3=winSurf3.get_rect()
winRect3.center=(半宽半高)
#camerax和cameray位于摄影机视图所在位置的左上角
camerax=0
摄像机=0
grassObjs=[]#存储游戏中的所有明星对象
squirrelObjs=[]#存储所有非玩家鱼对象
squirrelObjs2=[]#存储所有非玩家鼠标对象
#存储播放器对象:
playerObj={'surface':pygame.transform.scale(MEL,(STARTSIZE,STARTSIZE)),
“面向”:左,
“大小”:开始大小,
“x”:半宽,
“y”:半高,
“反弹”:0,
“健康”:MAXHEALTH}
#显示球员的得分
winSurf4=BASICFONT.render(str(playerObj['size']),True,红色)
winRect4=winSurf4.get_rect()
winRect4.center=(半宽+680,半高-420)
moveLeft=False
moveRight=False
moveUp=False
向下移动=错误
#从屏幕上的一些随机草地图像开始
对于范围(7)中的i:
grassObjs.append(makeNewGrass(camerax,cameray))
grassObjs[i]['x']=random.randint(0,WINWIDTH)
grassObjs[i]['y']=random.randint(0,WINHEIGHT)
虽然正确:#主游戏循环
#检查我们是否应该关闭抗毁性
如果抗毁模式和时间.time()-抗毁开始时间>抗毁时间:
抗毁模式=错误
####把所有的鱼都移走
对于squirrelObjs中的sObj:
#移动鱼,调整它们的反弹
sObj['x']+=sObj['movex']
sObj['y']+=sObj['movey']
sObj['bounce']+=0
如果sObj['bounce']>sObj['bouncerate']:
sObj['bounce']=0#重置反弹量
#他们改变方向的随机机会
如果random.randint(0,99)0:#向右
sObj['surface']=pygame.transform.scale(R_SQUIR_IMG,(sObj['width'],sObj['height']))
否则:#面朝左
sObj['surface']=pygame.transform.scale(L_SQUIR_IMG,(sObj['width'],sObj['height']))
####移动所有的老鼠
对于squirrelObjs2中的sObj2:
#移动鼠标,调整它们的反弹
sObj2['x']+=sObj2['movex']
sObj2['y']+=sObj2['movey']
sObj2['bounce']+=0
如果sObj2['bounce']>sObj2['bouncerate']:
sObj2['bounce']=0#重置反弹量
#他们改变方向的随机机会
如果random.randint(0,99)0:#向右
sObj2['surface']=pygame.transform.scale(R_SQUIR_IMG2,(sObj2['width'],sObj2['height']))
否则:#面朝左
sObj2['surface']=pygame.transform.scale(L_SQUIR_IMG2,(sObj2['width'],sObj2['height']))
####检查所有对象,看看是否需要删除任何对象。(1)
对于范围内的i(len(grassObjs)-1,-1,-1):
如果isOutsideActiveArea(camerax、cameray、grassObjs[i]):
德尔格拉索布斯[i]
对于范围内的i(len(squirrelObjs)-1,-1,-1):
如果isOutsideActiveArea(camerax、cameray、SquirreObjs[i]):
del squirrelObjs[i]
####检查所有对象,看看是否需要删除任何对象
winSurf4 = BASICFONT.render(str(playerObj['size']), True, RED)
winRect4 = winSurf4.get_rect()
winRect4.center = (HALF_WINWIDTH + 680, HALF_WINHEIGHT - 420)
while True:
(...)
winSurf4 = BASICFONT.render(str(playerObj['size']), True, RED)
winRect4 = winSurf4.get_rect()
winRect4.center = (HALF_WINWIDTH + 680, HALF_WINHEIGHT - 420)
(...)