我是编程的新手,我正在开发一款类似于游戏松鼠的游戏,在这种游戏中你会吃掉比你小的人并受到更大的伤害。我现在想要显示播放器的大小,这将完美地完成,但它只显示起始大小。因此,当我吃敌人时,我希望数字改变,但我无法弄清楚如何。
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)
答案 0 :(得分:0)
呈现大小的代码是:
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)
(...)
每次迭代都会刷新得分。这将完成这项工作,但这可能是不必要的。最好只在内部更改分数时执行此例程,以减少不必要的代码执行。