100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Pygame 简单打字游戏

Pygame 简单打字游戏

时间:2022-07-27 20:08:33

相关推荐

Pygame 简单打字游戏

功能描述:

1、点击开始游戏,会出现一段英文文章,并进入60s倒计时

2、如果一分钟内输入完成这段会自动呈现下一段

3、单词正确数实时统计,背景颜色随输入速度而变化

代码:

注意:上面动态图需要放在游戏目录下

import randomimport pygameimport sysclass TextData:def __init__(self):self.all_data = ["The author of the game is Jiawang Zhang.","A contented mind is the greatest blessing a man can enjoy in this world.","If you would know the value of money, go and try to borrow some.","If you wish to succeed, you should use persistence as your good friend, experience as your reference, prudence as your brother and hope as your sentry.","Health is certainly more valuable than money, because it is by health that money is procured.","Only those who have the patience to do simple things perfectly ever acquire the skill to do difficult things easily."] def get_single_data(self):index = random.randint(0,len(self.all_data)-1)return self.all_data[index]# def get_data_cut(self, cut_size = 30):res = []split_data = self.get_single_data().split(' ')tem = ""for it in split_data:if len(tem + it) < cut_size:tem += " " + it if tem != "" else itelse:res.append(tem)tem = ""if tem != "":res.append(tem)return len(split_data), res, split_dataclass TextBox:def __init__(self, x, y, w, h, text=""):# 文本框起始坐标和宽高self.x = xself.y = yself.width = wself.height = hself.text = text # 文本框中文字内容self.surface = pygame.Surface((w, h))self.surface.fill((255, 255, 255))def set_text(self, text_data):self.text = text_datadef add_single_char(self, single_char):self.text += single_chardef del_single_char(self):self.text = self.text[:-1]class TextArea:def __init__(self, height, width):self.font = pygame.font.Font(None, 32) # 全文需要统一的字体,所以放到这里self.boxes = []self.TD = TextData()self.left_padding = 98self.screen_height = heightself.screen_width = widthself.text_list = []self.split_words = []self.input_text = ""self.all_words_cnt = 0self.acc_words_cnt = 0self.pre_input_all_words = 0# text_surf = self.font.render(self.text, True, (255, 255, 255))def draw_boxes(self, screen):i = 0_, input_cut, __ = self.cut_data(self.input_text, 40)for it in self.boxes:if i % 2 == 0:text_surf = self.font.render(it.text, True, (109, 158, 235))else:it.text = input_cut[(i-1) // 2] if ((i-1) // 2) < len(input_cut) else ""text_surf = self.font.render(it.text, True, (0, 0, 0))i += 1screen.blit(it.surface, (it.x, it.y))screen.blit(text_surf, (it.x, it.y - 2 + (it.height - text_surf.get_height())),(0, 0, it.width, it.height))def add_box(self, x, y, w, h):self.boxes.append(TextBox(x, y, w, h))def get_text_set_boxes(self):self.boxes.clear()self.input_text = ""self.pre_input_all_words += self.acc_words_cntself.acc_words_cnt = 0tem_cnt, self.text_list, self.split_words = self.cut_data(self.TD.get_single_data(), 40)self.all_words_cnt += tem_cnttop_padding = (self.screen_height // 2) - 45*len(self.text_list) + 10if top_padding <= 0:print("The article is too long!")returnfor it in self.text_list:self.boxes.append(TextBox(self.left_padding, top_padding, 600, 30, text=it))self.boxes.append(TextBox(self.left_padding, top_padding+40, 600, 30, text=""))top_padding += 70+20def calc_acc(self):cnt = 0tem_list = self.input_text.split(' ')while(cnt < len(tem_list) and cnt < len(self.split_words)):if tem_list[cnt] != self.split_words[cnt]:breakcnt += 1self.acc_words_cnt = cntdef cut_data(self, data, cut_size = 30):res = []split_data = data.split(' ')tem = ""for it in split_data:if len(tem + it) < cut_size:tem += " " + it if tem != "" else itelse:res.append(tem)tem = itres.append(tem)return len(split_data), res, split_datadef calc_curr_state(self):i = 1while i < len(self.boxes):tem_compare = self.boxes[i].text, self.boxes[i-1].texti += 2if tem_compare[0] != tem_compare[1]:return True, i - 2return False, -1def get_score(self):return self.acc_words_cnt+self.pre_input_all_words, self.all_words_cntdef key_down(self, event):unicode_char = event.unicodekey = event.keyif key == 8: # 退位键self.input_text = self.input_text[0:-1]return if key == 301: # 切换大小写键returnif unicode_char != "":self.input_text += unicode_charelse:if len(unicode_char) != 0:self.input_text += chr(unicode_char)if unicode_char == ' ' or unicode_char == '.':self.calc_acc()class ScoreArea:def __init__(self):self.font = pygame.font.Font(None, 32) # 全文需要统一的字体,所以放到这里self.box = Nonedef set_box(self, x, y, w, h, text=""):self.box = TextBox(x, y, w, h, text)# self.box.surface.fill((0,0,0))def draw(self, screen, text="(0, 0)", padding=0):text = " " + texttext_surf = self.font.render(text, True, (255, 0, 0))screen.blit(self.box.surface, (self.box.x, self.box.y))screen.blit(text_surf, (self.box.x+padding, self.box.y - 2 + (self.box.height - text_surf.get_height())),(0, 0, self.box.width, self.box.height))def position_in_area(self, x, y):return x >= self.box.x and x <= self.box.x+self.box.width and y >= self.box.y and y <= self.box.y+self.box.heightclass MoveFun:def __init__(self, w, h):self.speed = [1, 1]self.width = wself.height = hself.ball = pygame.image.load("gui.gif")self.ballrect = self.ball.get_rect()def update_position(self):self.ballrect = self.ballrect.move(self.speed[0], self.speed[1])if self.ballrect.left < 0 or self.ballrect.right > self.width:self.speed[0] = - self.speed[0]if self.ballrect.top < 0 or self.ballrect.bottom > self.height:self.speed[1] = - self.speed[1]class TypingGame:def __init__(self, w = 800, h = 650):# 设置窗口大小和标题self.size = self.width, self.height = w, hself.screen = pygame.display.set_mode(self.size)pygame.display.set_caption("打字游戏")# 设置背景和移动渲染self.bg_color = 255, 0, 0self.moveball = MoveFun(w, h)# 设置文字显示区域self.text_area = TextArea(h - 50, w)self.text_area.get_text_set_boxes()self.score_area = ScoreArea()self.score_area.set_box(98, h - 50, 600, 30, "score: ")self.finish_area = ScoreArea()self.finish_area.set_box(98, h // 2, 600, 30, "game over")self.score = (0, 0)self.start_time = Nonedef calc_speed(self):curr_length = len(self.text_area.input_text) + self.text_area.pre_input_all_wordstime_dis = (pygame.time.get_ticks() - self.start_time + 1.0) / 6000.0speed = min((curr_length / time_dis) / 50.0, 1.0)return (255 - int(speed*255), int(speed*255), 0)def Start(self):self.start_time = pygame.time.get_ticks()def update_backgroud(self):self.moveball.update_position()if self.start_time != None:self.bg_color = self.calc_speed()self.screen.fill(self.bg_color) # 背景self.screen.blit(self.moveball.ball, self.moveball.ballrect) # 碰撞移动def update_game(self):# 游戏开始后渲染if self.start_time == None:self.score_area.draw(self.screen, "Click to start the game ", padding=170) # 分数面板else:now_time = pygame.time.get_ticks()if (now_time - self.start_time) < 60000.0:self.text_area.draw_boxes(self.screen) # 文本框self.score = self.text_area.get_score()self.score_area.draw(self.screen, "score: " + str(self.score) + " time: " + str(60 - int((now_time - self.start_time) / 1000)) + " s", padding=180) # 分数面板if self.score[0] == self.score[1] and self.score[0] != 0:self.text_area.get_text_set_boxes()else:self.score_area.draw(self.screen, "score: " + str(self.score) + " time: " + "0.00", padding=180) # 分数面板self.finish_area.draw(self.screen, "game over", padding=240) # 结束面板if __name__ == '__main__':pygame.init()Tgame = TypingGame()while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()elif event.type == pygame.KEYDOWN:if Tgame.start_time != None:Tgame.text_area.key_down(event)elif event.type == pygame.MOUSEBUTTONDOWN:if Tgame.start_time == None:x, y = pygame.mouse.get_pos()if Tgame.score_area.position_in_area(x, y):Tgame.Start()################ 背景+碰撞移动更新 ################Tgame.update_backgroud()Tgame.update_game()################ 更新画面 ################pygame.display.update()pygame.time.delay(50)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。