2013-12-03 2 views
1

Это просто игра с фруктами.Как добавить рабочий таймер, который появляется на экране в pygame

import pygame, random, time, os, webbrowser 
from time import sleep 
from pygame import* 
pygame.init() 
myname=input('What is your name') 

#set the window size 
window= pygame.display.set_mode((800,600) ,0,24) 
pygame.display.set_caption("Fruit Catch") 

#game variables 
gameover=pygame.image.load('gameover.jpg') 
myscore=0 
file = 'score.txt' 
eating=pygame.mixer.Sound('data/eating.wav') 
die=pygame.mixer.Sound('die.wav') 
mylives=3 
mouth_x=300 
fruit_x=250 
fruit_y=75 
fruitlist=['broccoli.gif','chicken.gif'] 
keyclicks=0 
#prepare for screen 
myfont=pygame.font.SysFont("Britannic Bold", 55) 
label1=myfont.render(myname, 1, (240, 0, 0)) 
label3=myfont.render(str(mylives), 1, (20, 255, 0)) 
#grapchics 
fruit=pygame.image.load('data/chicken.png') 
mouth=pygame.image.load('data/v.gif') 
backGr=pygame.image.load('data/kfc.jpg') 
backGr1=pygame.image.load('sj.jpg') 
#endless loop 

start=pygame.image.load('chibro.jpg') 
end_it=False 
while (end_it==False): 
    window.blit(start, (0,0)) 
    myfont=pygame.font.SysFont("Impact", 55) 
    label7=myfont.render("Welcome "+myname+" Click here to begin", 1, (255, 0, 0)) 
    myfont=pygame.font.SysFont("Impact", 30) 
    label8=myfont.render("Catch as much Chicken and brocoli as you can", 1, (255, 0, 0)) 
    label9=myfont.render("If you miss 3, you will starve to death!", 1, (255, 0, 0)) 
    for event in pygame.event.get(): 
     if event.type==MOUSEBUTTONDOWN: 
      end_it=True 
    window.blit(label7,(10,500)) 
    window.blit(label8,(10,300)) 
    window.blit(label9,(10,400)) 
    pygame.display.update() 
running=True 
while running: 
    if fruit_y>=460:#check if at bottom, if so prepare new fruit 
     fruit_x=random.randrange(50,530,1) 
     fruit_y=75 
     fruit=pygame.image.load('data/'+fruitlist[random.randrange(0,2,1)]) 
    else:fruit_y+=5 

    #check collision 
    if fruit_y>=456: 
     mylives-=1 
    if fruit_y>=440: 
      if fruit_x>=mouth_x and fruit_x<=mouth_x+300 : 
        myscore+=1 
        fruit_y=600#move it off screen 
        eating.play() 

    pygame.mouse.get_pressed() 
    for event in pygame.event.get(): 
      if (event.type==pygame.KEYDOWN): 
       if (event.key==pygame.K_LEFT): 
         mouth_x-=55 
         keyclicks+=1 
       if (event.key==pygame.K_RIGHT): 
         mouth_x+=55 
         keyclicks+=1 
      if event.type==MOUSEBUTTONDOWN and keyclicks>=2 : 
       pygame.quit() 
    label3=myfont.render(str(mylives), 1, (20, 255, 0)) 
    label2=myfont.render(str(myscore), 1, (20, 255, 0)) 
    text1='You caught'+str(myscore) 
    text3='Press the mouse to close the game' 
    label4=myfont.render(text1, 1, (135, 206, 250)) 
    myfont1=pygame.font.SysFont("Britannic Bold", 40) 
    label5=myfont1.render(text3, 1, (255, 0, 0)) 

    if mylives==0: 
     window.blit(gameover, (0,0)) 
     window.blit(label4, (500,400)) 
     die.play() 
     pygame.time.get_ticks 
     pygame.display.update() 
     running=False 
     webbrowser.open(file) 

    else: 

     window.blit(backGr,(0,0)) 
     window.blit(mouth, (mouth_x,440)) 
     window.blit(fruit,(fruit_x, fruit_y)) 
     window.blit(label1, (174, 537)) 
     window.blit(label2, (700, 157)) 
     window.blit(label3, (700, 400)) 
     window.blit(label5, (10, 0)) 
     pygame.display.update() 

Как бы сделать так, чтобы, когда основной цикл начинается и работает верно таймер показывает на экране подсчета в секундах, и таймер заканчивается, когда бег является ложным какие-либо идеи, ребята?

ответ

1

Я не уверен, есть ли встроенный метод для этого в pygame, но вот как я это сделаю.

  1. import time
  2. Перед тем, как ввести свой игровой цикл, сохранить время, когда вы начали запуская его с
    startTime = time.time() это будет рассматриваться ваше нулевое время.
  3. Создайте новый ярлык, который рисует str(time.time() - startTime) как текст каждого обновления. Вы вычитаете time.time(), которое является текущим временем, с нулевого времени, чтобы получить время, прошедшее с момента запуска цикла, и там у вас есть свой таймер.
  4. Если вы хотите округляется до нескольких секунд вы должны убедиться, что усечение значение времени на междунар, потому что иначе это будет десятичное str(int(time.time() - startTime))

Позвольте мне знать, если это то, что вы искали.

+0

Pygame имеет [pygame.time.get_ticks()] (http://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks), поэтому в основном вам не нужно ' библиотека времени. – furas

1

Использование pygame.time.get_ticks()

полный пример - время в миллисекундах, таймер центрируется на экране, ESC - выход, ПРОСТРАНСТВО - пауза таймера

EDIT: Теперь он показывает минуты, секунды, миллисекунды - Python 2 .Икс. Для Python 3.x используйте // вместо / для counting_minutes, counting_seconds.

import pygame 

pygame.init() 

screen = pygame.display.set_mode((800,600)) 

font = pygame.font.SysFont(None, 32) 

clock = pygame.time.Clock() 

start_time = pygame.time.get_ticks() 

paused = False 
running = True 
while running: 

    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 

     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_ESCAPE: 
       running = False 

      if event.key == pygame.K_SPACE: 
       paused = not paused 

    if not paused: 
     counting_time = pygame.time.get_ticks() - start_time 

     # change milliseconds into minutes, seconds, milliseconds 
     counting_minutes = str(counting_time/60000).zfill(2) 
     counting_seconds = str((counting_time%60000)/1000).zfill(2) 
     counting_millisecond = str(counting_time%1000).zfill(3) 

     counting_string = "%s:%s:%s" % (counting_minutes, counting_seconds, counting_millisecond) 

     counting_text = font.render(str(counting_string), 1, (255,255,255)) 
     counting_rect = counting_text.get_rect(center = screen.get_rect().center) 

    screen.fill((0,0,0)) 
    screen.blit(counting_text, counting_rect) 

    pygame.display.update() 

    clock.tick(25) 
+0

Сохраняет рендеринг новых чисел на старых, и это похоже на беспорядок, как это исправить? – Kahin

+0

В примере я очищаю экран ('screen.fill ((0,0,0))') перед отображением новых номеров. – furas

+0

Да, я попытался добавить это, но у меня есть несколько других вещей, отображаемых на экране, и когда я заполняю экран, он становится пустым, поэтому как я могу попытаться заполнить только часть часов, а не весь экран? – Kahin

Смежные вопросы