- Python
拯救黑洞2源代码
- 2024-9-22 12:04:34 @
import pygame
from pygame.locals import *
from sys import exit
import random
# 生成文本图片
def text_img(name, size, text, color):
font = pygame.font.SysFont(name, size)
image = font.render(text, True, color)
return image
# 新的红球坐标
def new_location():
x = random.randint(30, 770)
y = random.randint(30, 570)
return x, y
# 分数初始值为0
num = 0
x, y = new_location()
x_speed = 2
y_speed = 2
# RGB系统中的R参数的初始值为0
r = 0
# 游戏倒计时开始时间
time = 12
# 初始化pygame
pygame.init()
# 设置窗口大小
screen = pygame.display.set_mode((800, 600))
# 设置游戏名称
pygame.display.set_caption('拯救黑洞')
img = text_img('simhei', 30, '当移动的红球靠近黑洞时……', (255, 0, 0))
screen.blit(img, (200, 300))
pygame.display.update()
pygame.time.delay(2000)
screen.fill((0, 0, 0))
img = text_img('simhei', 30, '迅速按下鼠标左键即可收集红球的能量!', (255, 0, 0))
screen.blit(img, (150, 300))
pygame.display.update()
pygame.time.delay(2000)
t1 = pygame.time.get_ticks()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
elif event.type == MOUSEBUTTONDOWN:
mouse_down = event.button
try:
if mouse_down == 1:
if c1.contains(c2):
r += 51
num += 1
x, y = new_location()
# 延时200ms传值
pygame.time.delay(200)
except NameError:
pass
# 填充屏幕背景颜色
screen.fill((255, 255, 255))
# 失败判断
if time <= 0:
pygame.draw.circle(screen, (0, 0, 0), (400, 300), 100)
img = text_img(None, 50, 'you lose', (255, 0, 0))
screen.blit(img, (335, 280))
pygame.display.update()
continue
# 胜利判断
if num >= 5:
pygame.draw.circle(screen, (255, 0, 0), (400, 300), 100)
img = text_img(None, 50, 'you win', (0, 0, 0))
screen.blit(img, (335, 280))
pygame.display.update()
continue
# 绘制半径为100的黑洞
c1 = pygame.draw.circle(screen, (r, 0, 0), (400, 300), 100)
# 绘制红球
c2 = pygame.draw.circle(screen, (255, 0, 0), (x, y), 30)
x += x_speed
y += y_speed
# 触边反弹
if x < 30 or x > 770:
x_speed = -x_speed
if y < 30 or y > 570:
y_speed = -y_speed
t2 = pygame.time.get_ticks()
# 判断有没有过去一秒
if t2-t1 >= 1000:
t1 = t2
time = time-1
score = text_img('simhei', 25, '得分:' + str(num), (0, 0, 0))
screen.blit(score, (0, 30))
countdown = text_img('simhei', 25, '倒计时:' + str(time), (0, 0, 0))
screen.blit(countdown, (0, 0))
# 更新屏幕画面
pygame.display.update()
0 条评论
目前还没有评论...