当前位置:网站首页>Space shooting Lesson 10: score (painting and writing)
Space shooting Lesson 10: score (painting and writing)
2022-07-28 20:51:00 【acktomas】
Space shooting No 10 course : Score ( Painting and writing )
This is us. “Shmup” Project No 7 part . If you haven't read through the previous section , Please from The first 1 part Start . In this lesson , We will start to maintain our scores , And learn how to display text on the screen .
video
Watch Video
Show scores
It's very simple to show players' scores : We only need one score Variable , We initialize to 0, And every time a bullet destroys a meteor . Because we have meteors of different sizes , And big meteors are easier to hit than small ones , So it makes sense to get more points when hitting a smaller meteor .
We will call this variable and initialize it before the game loop :
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
score = 0
# Game loop
running = True
The score should be allocated according to the size of the meteor , We can use what we used before radius attribute . The largest meteor image is about 100 px wide , Its radius is 100 * .85 / 2 = 43 px, The radius of the smallest meteor is about 8 Pixels . therefore , If we subtract the radius from a larger number 50, for instance , Big meteor gives 7 branch , The smallest meteor gives 42 branch .
# check to see if a bullet hit a mob
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
score += 50 - hit.radius
m = Mob()
all_sprites.add(m)
mobs.add(m)
Render text
Now we have a variable to save our scores , But we need to be able to draw it on the screen , It's a little tricky . stay Pygame Drawing text in is a little complicated , It takes a few steps . If you want to draw text multiple times , So it makes sense to create a function , We're going to call draw_text Function to handle it . The parameters of this function will be :
surf- We want to draw the surface of the texttext- The string we want to displayx, y- Location
We also need to choose a font . If the font you selected does not exist on the computer you are using , There may be problems . We can do that by using pygame.font.match_font() Search the system for the closest matching font to solve this problem .
Here is draw_text function :
font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
Drawing fonts onto the screen requires accurate calculation of the required pixel patterns - Computer graphics terminology is “ Rendering ”. This is it. font.render() Functions perform operations . however , You may want to know True The purpose of the parameter . This is an open / Closing is called Anti-Aliasing Function options .
Anti-Aliasing
If you have ever tried to draw something manually with pixels , So you know it's very difficult to draw curves on a square grid - You will eventually get a jagged shape . This jagged shape is called “ sawtooth ”, You can see an example here :

Due to aliasing , first “a” The characters look very blocky . Anti-Aliasing It's the way modern computers make text on the screen look less jagged . They achieve this by mixing the pixels at the edge of the shape with the background color . In this example , You can see black “a” Surrounded by gray pixels . Shrink the hours , The font looks very clean and curved .
Show scores
Now? , We are ready to display the score on the screen . We just need to add it to our drawing section , The score is displayed at the top center of the screen :
# Draw / render
screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
draw_text(screen, str(score), 18, WIDTH / 2, 10)

this is it ! thereinafter , We will add sounds and music to make it more interesting !
The complete code of this part
# KidsCanCode - Game Development with Pygame video series
# Shmup game - part 7
# Video link: https://www.youtube.com/watch?v=U8yyrpuplwc
# Adding score (and drawing text)
import pygame
import random
from os import path
img_dir = path.join(path.dirname(__file__), 'img')
WIDTH = 480
HEIGHT = 600
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Shmup!")
clock = pygame.time.Clock()
font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(player_img, (50, 38))
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = 20
# pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -8
if keystate[pygame.K_RIGHT]:
self.speedx = 8
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_orig = random.choice(meteor_images)
self.image_orig.set_colorkey(BLACK)
self.image = self.image_orig.copy()
self.rect = self.image.get_rect()
self.radius = int(self.rect.width * .85 / 2)
# pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-150, -100)
self.speedy = random.randrange(1, 8)
self.speedx = random.randrange(-3, 3)
self.rot = 0
self.rot_speed = random.randrange(-8, 8)
self.last_update = pygame.time.get_ticks()
def rotate(self):
now = pygame.time.get_ticks()
if now - self.last_update > 50:
self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360
new_image = pygame.transform.rotate(self.image_orig, self.rot)
old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect()
self.rect.center = old_center
def update(self):
self.rotate()
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = bullet_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10
def update(self):
self.rect.y += self.speedy
# kill if it moves off the top of the screen
if self.rect.bottom < 0:
self.kill()
# Load all game graphics
background = pygame.image.load(path.join(img_dir, "starfield.png")).convert()
background_rect = background.get_rect()
player_img = pygame.image.load(path.join(img_dir, "playerShip1_orange.png")).convert()
bullet_img = pygame.image.load(path.join(img_dir, "laserRed16.png")).convert()
meteor_images = []
meteor_list = ['meteorBrown_big1.png', 'meteorBrown_med1.png', 'meteorBrown_med1.png',
'meteorBrown_med3.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png',
'meteorBrown_tiny1.png']
for img in meteor_list:
meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert())
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
score = 0
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
# Update
all_sprites.update()
# check to see if a bullet hit a mob
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
score += 50 - hit.radius
m = Mob()
all_sprites.add(m)
mobs.add(m)
# check to see if a mob hit the player
hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle)
if hits:
running = False
# Draw / render
screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
draw_text(screen, str(score), 18, WIDTH / 2, 10)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
The first 8 part : Sound and music
边栏推荐
- Network layer performance test
- Redis 3.0 source code analysis - data structure and object SDS list Dict
- 记一次Runtime.getRuntime().exce(“command“)报错
- Introduction to redis I: redis practical reading notes
- 融合数据库生态:利用 EventBridge 构建 CDC 应用
- Understanding of C # delegate
- JS drag and drop alert pop-up plug-in
- 算法面试高频题解指南【一】
- Pl515 SOT23-5 single / Dual Port USB charging protocol port controller Parkson electronic agent
- JS page black and white background switch JS special effect
猜你喜欢

到底为什么不建议使用SELECT * ?

Network shell

How bad can a programmer be? Nima, they are all talents

Introduction to redis II: RedHat 6.5 installation and use

h5微信射击小游戏源码

JS picture hanging style photo wall JS special effect

Talking about canvas and three rendering modes in unity

Speech controlled robot based on ROS (I): realization of basic functions

PXE_ KS unattended system

js图片悬挂样式照片墙js特效
随机推荐
想画一张版权属于你的图吗?AI作画,你也可以
Easynlp Chinese text and image generation model takes you to become an artist in seconds
研发效能的思考总结
到底为什么不建议使用SELECT * ?
云原生编程挑战赛火热开赛,51 万奖金等你来挑战!
Mysql报错:Specified key was too long; max key length is 767 bytes
How bad can a programmer be? Nima, they are all talents
Algorithm interview high frequency problem solving guide [1]
prometheus配置alertmanager完整过程
算法面试高频题解指南【一】
Unity package project to vs deploy hololens process summary
Seventeen year operation and maintenance veterans, ten thousand words long, speak through the code of excellent maintenance and low cost~
The engineering practice of super large model was polished, and Baidu AI Cloud released the cloud native AI 2.0 solution
Unity performance optimization scheme arrangement
LeetCode_ Bit operation_ Medium_ 260. Number III that appears only once
Unity makes prefabricated bodies with one key and modifies prefabricated bodies with one key
Beautiful blue background form input box style
超大模型工程化实践打磨,百度智能云发布云原生AI 2.0方案
Redis入门一:Redis实战读书笔记
What is data center? What value does the data center bring_ Light spot technology