Creating Dynamic Text Using the blit method [duplicate]

2024/11/16 18:33:05

I'm creating a basic game where a black square moves around the screen. There are two other squares, a green square and a red square. When the black square collides with the red square it quits the program, when it collides with the green square it adds to your points counter. I've got the red square part down but I'm having trouble creating dynamic text using sprites and classes. Someone from a previous question I asked told me I should blit the score to the screen and then re-blit it every time the square collided with the green square. I don't know how to properly do this however. Here is my code:

import os, sys
import pygame
from pygame.locals import *pygame.init()
mainClock = pygame.time.Clock()WINDOWWIDTH = 1000
WINDOWHEIGHT = 700
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption("Avoid!")BLACK = (0, 0, 0)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)player = pygame.Rect(500, 300, 40, 40)
playerImage = pygame.Surface((40, 40))enemy = pygame.Rect(300, 400, 20, 20)
enemyImage = pygame.Surface((20, 20))
enemyImage.fill((RED))food = pygame.Rect(300, 500 , 20, 20)
foodImage = pygame.Surface((20, 20))
foodImage.fill((GREEN))class Score(pygame.sprite.Sprite):"""A sprite for the score."""def __init__(self, xy):pygame.sprite.Sprite.__init__(self)self.xy = xy    # save xy -- will center our rect on it when we change the scoreself.font = pygame.font.Font(None, 50)  # load the default font, size 50self.color = (BLACK)         # our font color in rgbself.score = 0  # start at zeroself.reRender() # generate the imagedef update(self):passdef add(self, points):"""Adds the given number of points to the score."""if player.colliderect(food):my_score.score += pointsself.reRender()def reset(self):"""Resets the scores to zero."""self.score = 0self.reRender()def reRender(self):"""Updates the score. Renders a new image and re-centers at the initial coordinates."""self.image = self.font.render("%d"%(self.score), True, self.color)self.rect = self.image.get_rect()self.rect.center = self.xymy_score = Score((75, 575))
print my_score.scorefont = pygame.font.Font(None, 36)
text = font.render("%d" % (my_score.score), 1, (10, 10, 10))
textpos = text.get_rect(centerx=windowSurface.get_width()/2)moveLeft = False
moveRight = False
moveUp = False
moveDown = FalseMOVESPEED = 6while True:for event in pygame.event.get():if event.type == QUIT:pygame.quit()sys.exit()if event.type == KEYDOWN:if event.key == K_LEFT:moveRight = FalsemoveLeft = Trueif event.key == K_RIGHT:moveLeft = FalsemoveRight = Trueif event.key == K_UP:moveDown = FalsemoveUp = Trueif event.key == K_DOWN:moveUp = FalsemoveDown = Trueif event.type == KEYUP:if event.key == K_ESCAPE:pygame.quit()sys.exit()if event.key == K_LEFT:moveRight = FalsemoveLeft = Trueif event.key == K_RIGHT:moveLeft = FalsemoveRight = Trueif event.key == K_UP:moveDown = FalsemoveUp = Trueif event.key == K_DOWN:moveUp = FalsemoveDown = TruewindowSurface.fill(WHITE)if moveDown and player.bottom < WINDOWHEIGHT:player.top += MOVESPEEDif moveUp and player.top > 0:player.top -= MOVESPEEDif moveLeft and player.left > 0:player.left -= MOVESPEEDif moveRight and player.right < WINDOWWIDTH:player.right +=MOVESPEEDif player.colliderect(enemy):pygame.quit()sys.exit()windowSurface.blit(playerImage, player)windowSurface.blit(enemyImage, enemy)windowSurface.blit(foodImage, food)windowSurface.blit(text, textpos)score = Score((75, 575))pygame.display.update()mainClock.tick(40)

Do I put windowSurface.blit(text, textpos) into the add function within the Score class? How do I increase the score once the big square touches the little green square?

Answer

Honestly, I don't think you really need a separate class for the score, you can just have an add score method which is called whenever the rects for the big and little squares collide:

def addScore():global scorescore += 1 #just increasing thescoreif pygame.font: #checking if the font loading correctly, this section is taken directly from the Chimp Line by Line tutorialfont = pygame.font.Font(None, 36)text = font.render("score: " + str(score), 1, (10, 10, 10))textpos = text.get_rect(centerx=background.get_width()/2)background.blit(text, textpos)

Note: I haven't tested this myself within python

Does this work for you?

https://en.xdnf.cn/q/119166.html

Related Q&A

Regex to match special list items

I have weird list of items and lists like this with | as a delimiters and [[ ]] as a parenthesis. It looks like this:| item1 | item2 | item3 | Ulist1[[ | item4 | item5 | Ulist2[[ | item6 | item7 ]] | i…

How to choose the best model dynamically using python

Here is my code im building 6 models and i am getting accuracy in that, how do i choose that dynamically which accuracy is greater and i want to execute only that model which as highest accuracy."…

How do you access specific elements from the nested lists

I am trying to access elements from the nested lists. For example, file = [[“Name”,”Age”,”Medal”,”Location”],[“Jack”,”31”,”Gold”,”China”],[“Jim”,”29”,”Silver”,”US”]]This data c…

Why does BLOCKCHAIN.COM API only return recipient BASE58 addresses and omits BECH32s?

Following this post, I am trying to access all transactions within the #630873 block in the bitcoin blockchain.import requestsr = requests.get(https://blockchain.info/block-height/630873?format=json) …

rename columns according to list

I have 3 lists of data frames and I want to add a suffix to each column according to whether it belongs to a certain list of data frames. its all in order, so the first item in the suffix list should b…

How to send a pdf file from Flask to ReactJS

How can I send a file from Flask to ReactJS? I have already code that in the frontend, the user upload a file and then that file goes to the Flask server, then in the flask server the file is modify, …

How to draw cover on each tile in memory in pygame

I am a beginner in pygame and I am not a English native speaker.My assignment is coding a game called Memory. This game contains 8 pairs pictures and an cover exists on each pictures. This week, our as…

Compare 2 Excel files and output an Excel file with differences

Assume for simplicity that the data files look like this, sorted on ID:ID | Data1 | Data2 | Data3 | Data4 199 | Tim | 55 | work | $55 345 | Joe | 45 | work | $34 356 | Sam |…

Problem to show data dynamically table in python flask

I want to show a table in the html using python flask framework. I have two array. One for column heading and another for data record. The length of the column heading and data record are dynamic. I ca…

RuntimeError: generator raised StopIteration

I am in a course and try to find my problem. I cant understand why if I enter something other than 9 digits, the if should raise the StopIteration and then I want it to go to except and print it out. W…