如何用Python編寫俄羅斯方塊Tetris游戲?

在本文中,我們將用Python代碼構建一個令人驚嘆的項目:俄羅斯方塊游戲。在這個項目中,我們將使用pygame庫來構建游戲。要創建此項目,請確保您的系統中安裝了最新版本的Python。讓我們開始吧!

Pygame是一組跨平臺的Python模塊,用于創建視頻游戲。它由設計用于Python編程語言的計算機圖形和聲音庫組成。Pygame適合創建客戶端應用程序,這些應用程序可能被封裝在獨立的可執行文件中。要學習pygame,需要具備Python的基本知識。

要安裝pygame,請在終端中執行以下代碼:

pip install pygame

我們已經完成了項目的先決條件。讓我們來看看這個項目中的一些重要功能。

這種update_graphics方法用于設計游戲界面,并在游戲執行過程中進行必要的更新。該函數設置背景顏色和要顯示的文本,并設置邊框和寬度。它顯示當前分數和時間。它繪制一個小屏幕來顯示下一個塊。為塊設置瓷磚,每行20個瓷磚/平方,即19條水平線,每列10個瓷磚/廣場,即9條垂直線。

draw_small_screen方法用于設計在游戲執行期間顯示下一個塊的相同屏幕界面。它設置背景、邊框和文本,并顯示下一個塊。

manage_events函數用于在游戲執行期間處理塊。

Python中俄羅斯方塊游戲的完整代碼:

我們可以在Pygame的幫助下用Python構建俄羅斯方塊游戲,因為它有很多功能。現在,讓我們從實現部分開始。在注釋的幫助下,您可以逐行理解代碼。

現在創建兩個python文件,并將它們保存為util.py和tetris.py:

util.py文件:

#Import libraries
import pygame
import sys
import random
import time# Define important global variables
pygame.init()
clock = pygame.time.Clock()best_score = 0
longest_time = 0width = 700
height = 750
DISPLAY_SCREEN = pygame.display.set_mode((width, height))
pygame.display.set_caption(" Tetris")off_set_x = 10
off_set_y = 80
playing_field_width = 330  #330 / 10 = 33 width per tile
playing_field_height = 660  #600 / 20 = 33 height per tile
tile_length = 33 # tile is a square#colors
blue = (0, 0, 255)
white = (255, 255, 255) 
black = (0, 0, 0)
gray = (95, 95, 96) 
orange  = (249, 87, 0)  
cobalt_blue = (3, 65, 174)
green_apple  = (114, 203, 59)
cyber_yellow= (255, 213, 0)
beer = (255, 151, 28)
ryb_red = (255, 50, 19)
purple = (128, 0, 128)# colors of Tetris blocks
block_colors = (cobalt_blue, blue, green_apple, purple, cyber_yellow, beer, ryb_red)
# shapes of Tetris blocks
shapes = ("i_block", "l_block", "j_block", "o_block", "s_block", "t_block", "z_block")
directions = ("vertical_1", "vertical_2", "horizontal_1", "horizontal_2")background_img = pygame.image.load("resources/images/background_img.jpg")      
instructions_img = pygame.image.load("resources/images/instructions_img.jpg")  
icon_img = pygame.image.load("resources/images/icon.png")
pygame.display.set_icon(icon_img)class Button:def __init__(self, button_color, button_hover_over_color, x, y, width, height, text_size,  text_color, text_hover_over_color = None, text_str=""):self.button_color = button_colorself.button_hover_over_color = button_hover_over_colorself.x = xself.y = yself.width = widthself.height = heightself.text_size = text_sizeself.text_color = text_colorif text_hover_over_color:self.text_hover_over_color = text_hover_over_colorelse:self.text_hover_over_color =  text_colorself.text_str = text_strdef blit(self, display_screen, outline_color=None):if outline_color: pygame.draw.rect(display_screen, outline_color, (self.x-3, self.y-3, self.width+6, self.height+6))pygame.draw.rect(display_screen, self.button_color, (self.x, self.y, self.width, self.height))if self.text_str != "": font = pygame.font.Font("freesansbold.ttf", self.text_size)text = font.render(self.text_str, True, self.text_color)# to center the text in the middle of the button based on the size of the buttontext_position = (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2))display_screen.blit(text, text_position)def is_hovered_over(self, mouse_position):if self.x < mouse_position[0] < self.x+self.width and self.y < mouse_position[1] < self.y+self.height:return Truereturn Falsedef blit_hovered_over(self, display_screen):pygame.draw.rect(display_screen, self.button_hover_over_color, (self.x, self.y, self.width, self.height))if self.text_str != "":font = pygame.font.Font("freesansbold.ttf", self.text_size)text = font.render(self.text_str, True, self.text_hover_over_color)# to center the text in the middle of the button based on the size of the buttontext_position = (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2))display_screen.blit(text, text_position)def is_clicked(self, mouse_position, event):if self.is_hovered_over(mouse_position):if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:return Truereturn Falseclass Tile:def __init__(self, x, y, color = black):self.x = xself.y = yself.color = colorself.empty = Truedef draw_tile(self):pygame.draw.rect(DISPLAY_SCREEN , self.color, (self.x, self.y, tile_length, tile_length) )class PlayingField():def __init__(self):#y coordinate of first row = (80) off_set_y self.tiles = {"row1":  {80:  []},"row2":  {113: []},"row3":  {146: []},"row4":  {179: []},"row5":  {212: []},"row6":  {245: []},"row7":  {278: []},"row8":  {311: []},"row9":  {344: []},"row10": {377: []},"row11": {410: []},"row12": {443: []},"row13": {476: []},"row14": {509: []},"row15": {542: []},"row16": {575: []},"row17": {608: []},"row18": {641: []},"row19": {674: []},"row20": {707: []},}self.__init_field()def __init_field(self):    y = off_set_yfor i in range(20): #rowsx = off_set_xfor j in range(10): #colstile_to_add = Tile(x, y) self.tiles["row"+str(i+1)][y].append(tile_to_add)x += tile_lengthy += tile_lengthdef destory_full_row(self, player):times = 0y = off_set_y        for i in range(20):for tile in self.tiles["row"+str(i+1)][y]:if tile.empty: breakelif tile.x == off_set_x+playing_field_width-tile_length:times += 1for j in range(800): #just for flashing the rowif j%2 == 0:pygame.draw.rect(DISPLAY_SCREEN , black, (self.tiles["row"+str(i+1)][y][0].x+1, self.tiles["row"+str(i+1)][y][0].y+1, playing_field_width-2, tile_length-2) )else:for tile in self.tiles["row"+str(i+1)][y]:pygame.draw.rect(DISPLAY_SCREEN , tile.color, (tile.x, tile.y, tile_length, tile_length) )pygame.draw.line(DISPLAY_SCREEN , white, (off_set_x, y), (playing_field_width+off_set_x-1, y)) # horizontal linepygame.display.update()# let's destory this full rowself.destroy_and_replace(i+1, y)player.score += 10*timesy += tile_length def destroy_and_replace(self, row_number, row_y):for i in range (row_number, 1, -1):prev_row_number = i-1prev_y = row_y-tile_lengthself.tiles["row"+str(i)][row_y].clear() #current_row.clear()temp_x = off_set_xfor j in range(10):empty_tile = Tile(temp_x, row_y)temp_x += tile_lengthself.tiles["row"+str(i)][row_y].append(empty_tile)if prev_y < 80: breakfor j in range(10):old_tile = self.tiles["row"+str(i)][row_y][j]new_tile = self.tiles["row"+str(prev_row_number)][prev_y][j] old_tile.x = new_tile.xold_tile.color = new_tile.color old_tile.empty = new_tile.emptyrow_y -= tile_lengthclass Block:def __init__(self, shape:str, color = black):self.shape = shapeself.color = colorself.direction = directions[0] #vertical_1#                         tile1                                                        , tile2            , tile3            , tile4self.tiles = [ Tile(off_set_x+playing_field_width/2-tile_length, off_set_y, self.color), Tile(0, 0, color), Tile(0, 0, color), Tile(0, 0, color)]self.__init_shape() for tile in self.tiles:tile.empty = Falsedef __init_shape(self):if self.shape == "i_block":self.tiles[1] = Tile(self.tiles[0].x, self.tiles[0].y-tile_length, self.color)self.tiles[2] = Tile(self.tiles[0].x, self.tiles[1].y-tile_length, self.color)self.tiles[3] = Tile(self.tiles[0].x, self.tiles[2].y-tile_length, self.color)elif self.shape == "l_block":self.tiles[1] = Tile(self.tiles[0].x+tile_length, self.tiles[0].y, self.color)self.tiles[2] = Tile(self.tiles[0].x-tile_length, self.tiles[0].y, self.color)self.tiles[3] = Tile(self.tiles[2].x, self.tiles[2].y-tile_length, self.color)elif self.shape == "j_block":self.tiles[1] = Tile(self.tiles[0].x+tile_length, self.tiles[0].y, self.color)self.tiles[2] = Tile(self.tiles[0].x-tile_length, self.tiles[0].y, self.color)self.tiles[3] = Tile(self.tiles[1].x, self.tiles[1].y-tile_length, self.color)elif self.shape == "o_block":self.tiles[1] = Tile(self.tiles[0].x+tile_length,  self.tiles[0].y, self.color)self.tiles[2] = Tile(self.tiles[0].x, self.tiles[0].y-tile_length, self.color)self.tiles[3] = Tile(self.tiles[1].x, self.tiles[1].y-tile_length, self.color)elif self.shape == "s_block":self.tiles[1] = Tile(self.tiles[0].x-tile_length, self.tiles[0].y, self.color)self.tiles[2] = Tile(self.tiles[0].x, self.tiles[0].y-tile_length, self.color)self.tiles[3] = Tile(self.tiles[2].x+tile_length, self.tiles[2].y, self.color)elif self.shape == "t_block":self.tiles[1] = Tile(self.tiles[0].x+tile_length,  self.tiles[0].y, self.color)self.tiles[2] = Tile(self.tiles[0].x-tile_length, self.tiles[0].y, self.color)self.tiles[3] = Tile(self.tiles[0].x, self.tiles[0].y-tile_length, self.color)elif self.shape == "z_block":self.tiles[1] = Tile(self.tiles[0].x+tile_length,  self.tiles[0].y, self.color)self.tiles[2] = Tile(self.tiles[0].x, self.tiles[0].y-tile_length, self.color)self.tiles[3] = Tile(self.tiles[2].x-tile_length, self.tiles[2].y, self.color)else:print("Error: wrong block name.")pygame.quit()sys.exit()def complete_block(self):self.__init_shape()def can_fall(self, next_block, playing_field, player):from tetris import manage_events, update_graphicsmanage_events(self, next_block, playing_field, player)#check bordersfor block_tile in self.tiles:if block_tile.y >= playing_field_height+off_set_y-tile_length:return False  #check already existed tilesfor block_tile in self.tiles:y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.y+tile_length == tile.y and block_tile.x == tile.x: return False  y += tile_lengthreturn Truedef block_is_falling(self, next_block, playing_field, player, faster=None):from tetris import manage_events, update_graphicsmanage_events(self,next_block, playing_field, player)if self.can_fall(next_block, playing_field, player):for tile in self.tiles:tile.y += tile_lengthmanage_events(self, next_block, playing_field, player)             update_graphics(self, next_block, playing_field, player)if faster:                clock.tick(40)self.block_is_falling( next_block, playing_field, player)else:                clock.tick(5)manage_events(self, next_block, playing_field, player)             update_graphics(self, next_block, playing_field, player)def get_new_block(self, next_block, playing_field, player):if self.can_fall(next_block, playing_field, player): return (self, next_block, False)#if the block has falled completelyfor block_tile in self.tiles: found = False y = off_set_yfor i in range(20):if not found:for j in range(10):if block_tile.x == playing_field.tiles["row"+str(i+1)][y][j].x and block_tile.y == playing_field.tiles["row"+str(i+1)][y][j].y:playing_field.tiles["row"+str(i+1)][y][j].color = block_tile.colorplaying_field.tiles["row"+str(i+1)][y][j].empty = Falsefound = Truebreaky += tile_lengthelse:breaknew_block = next_blocknext_rand_index1 = random.randint(0, 6)next_rand_index2 = random.randint(0, 6)new_next_block = Block(shapes[next_rand_index1], block_colors[next_rand_index2])clock.tick(2)return (new_block, new_next_block, True)def move_left(self, playing_field):if self.can_move_left(playing_field):for tile in self.tiles:tile.x -= tile_lengthdef move_right(self, playing_field):if self.can_move_right(playing_field):for tile in self.tiles:tile.x += tile_lengthdef can_move_left(self, playing_field):# whether inside the playing field or notfor tile in self.tiles:if tile.x <= off_set_x:return False# whether adjacent field_tiles are occupied or notfor block_tile in self.tiles:y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x-tile_length == tile.x and block_tile.y  == tile.y:return False  y += tile_lengthreturn Truedef can_move_right(self, playing_field):# whether inside the playing field or notfor tile in self.tiles:if tile.x + tile_length >= off_set_x+playing_field_width:return False# whether adjacent field_tiles are occupied or notfor block_tile in self.tiles:y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x+tile_length == tile.x and block_tile.y  == tile.y:return False  y += tile_lengthreturn Truedef rotate(self, next_block, playing_field, player):from tetris import manage_events, update_graphicsmanage_events(self, next_block, playing_field, player)if self.shape == "i_block":self.rotate_i_block(playing_field)elif self.shape == "l_block":self.rotate_l_block(playing_field)elif self.shape == "j_block":self.rotate_j_block(playing_field)elif self.shape == "o_block":return#no rotation for o_block.elif self.shape == "s_block":self.rotate_s_block(playing_field)elif self.shape == "t_block":self.rotate_t_block(playing_field)elif self.shape == "z_block":self.rotate_z_block(playing_field)else:print("Error: wrong block name.")pygame.quit()sys.exit()manage_events(self, next_block, playing_field, player)update_graphics(self, next_block, playing_field, player)def rotate_i_block(self, playing_field): #donetemp_rotated_i = Block("i_block", self.color)temp_rotated_i.tiles = self.tiles.copy()if self.direction == directions[0] or self.direction == directions[1]:# ----temp_rotated_i.tiles[0] = Tile(temp_rotated_i.tiles[1].x, temp_rotated_i.tiles[0].y, temp_rotated_i.color) temp_rotated_i.tiles[1] = Tile(temp_rotated_i.tiles[0].x-tile_length, temp_rotated_i.tiles[0].y, temp_rotated_i.color)temp_rotated_i.tiles[2] = Tile(temp_rotated_i.tiles[0].x+tile_length, temp_rotated_i.tiles[0].y, temp_rotated_i.color)temp_rotated_i.tiles[3] = Tile(temp_rotated_i.tiles[2].x+tile_length, temp_rotated_i.tiles[0].y, temp_rotated_i.color)temp_rotated_i.direction = directions[2] # "horizontal_1"elif self.direction == directions[2] or self.direction == directions[3]:# |# |# |# |temp_rotated_i.tiles[1] = Tile(temp_rotated_i.tiles[0].x, temp_rotated_i.tiles[0].y-tile_length, temp_rotated_i.color)temp_rotated_i.tiles[2] = Tile(temp_rotated_i.tiles[1].x, temp_rotated_i.tiles[1].y-tile_length, temp_rotated_i.color)temp_rotated_i.tiles[3] = Tile(temp_rotated_i.tiles[2].x, temp_rotated_i.tiles[2].y-tile_length, temp_rotated_i.color)temp_rotated_i.direction = directions[0] #"vertical_1"for block_tile in temp_rotated_i.tiles:if block_tile.x <= off_set_x or block_tile.x >= playing_field_width:return y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x == tile.x and block_tile.y  == tile.y:returny += tile_lengthself.direction = temp_rotated_i.directionself.tiles = temp_rotated_i.tilesdef rotate_l_block(self, playing_field): #donetemp_rotated_l = Block("l_block", self.color)temp_rotated_l.tiles = self.tiles.copy()if self.direction == directions[0]:# after rotating, the block should look like this ↓#  _# |# |# |temp_rotated_l.tiles[0] = Tile(temp_rotated_l.tiles[0].x, temp_rotated_l.tiles[0].y, temp_rotated_l.color)temp_rotated_l.tiles[1] = Tile(temp_rotated_l.tiles[0].x, temp_rotated_l.tiles[0].y-tile_length, temp_rotated_l.color)temp_rotated_l.tiles[2] = Tile(temp_rotated_l.tiles[1].x, temp_rotated_l.tiles[1].y-tile_length, temp_rotated_l.color)temp_rotated_l.tiles[3] = Tile(temp_rotated_l.tiles[2].x+tile_length, temp_rotated_l.tiles[2].y, temp_rotated_l.color)temp_rotated_l.direction = directions[2] # "horizontal_1"elif self.direction == directions[2]:# after rotating, the block should look like this ↓# ---#   |temp_rotated_l.tiles[0] = Tile(temp_rotated_l.tiles[3].x, temp_rotated_l.tiles[0].y, temp_rotated_l.color)temp_rotated_l.tiles[1] = Tile(temp_rotated_l.tiles[0].x, temp_rotated_l.tiles[0].y-tile_length, temp_rotated_l.color)temp_rotated_l.tiles[2] = Tile(temp_rotated_l.tiles[1].x-tile_length, temp_rotated_l.tiles[1].y, temp_rotated_l.color)temp_rotated_l.tiles[3] = Tile(temp_rotated_l.tiles[2].x-tile_length, temp_rotated_l.tiles[2].y, temp_rotated_l.color)temp_rotated_l.direction = directions[1] #"vertical_2"elif self.direction == directions[1]: # after rotating, the block should look like this ↓#  |#  |# _|temp_rotated_l.tiles[0] = Tile(temp_rotated_l.tiles[3].x, temp_rotated_l.tiles[0].y, temp_rotated_l.color)temp_rotated_l.tiles[1] = Tile(temp_rotated_l.tiles[0].x+tile_length, temp_rotated_l.tiles[0].y, temp_rotated_l.color)temp_rotated_l.tiles[2] = Tile(temp_rotated_l.tiles[1].x, temp_rotated_l.tiles[1].y-tile_length, temp_rotated_l.color)temp_rotated_l.tiles[3] = Tile(temp_rotated_l.tiles[2].x, temp_rotated_l.tiles[2].y-tile_length, temp_rotated_l.color)temp_rotated_l.direction = directions[3] #"horizontal_2"elif self.direction == directions[3]: # after rotating, the block should look like this ↓# |# ---temp_rotated_l.tiles[0] = Tile(temp_rotated_l.tiles[1].x, temp_rotated_l.tiles[0].y, temp_rotated_l.color)temp_rotated_l.tiles[1] = Tile(temp_rotated_l.tiles[0].x+tile_length, temp_rotated_l.tiles[0].y, temp_rotated_l.color)temp_rotated_l.tiles[2] = Tile(temp_rotated_l.tiles[0].x-tile_length, temp_rotated_l.tiles[1].y, temp_rotated_l.color)temp_rotated_l.tiles[3] = Tile(temp_rotated_l.tiles[2].x, temp_rotated_l.tiles[2].y-tile_length, temp_rotated_l.color) temp_rotated_l.direction = directions[0] #"vertical_1"for block_tile in temp_rotated_l.tiles:if block_tile.x <= off_set_x or block_tile.x >= playing_field_width:return y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x == tile.x and block_tile.y  == tile.y:returny += tile_lengthself.direction = temp_rotated_l.directionself.tiles = temp_rotated_l.tilesdef rotate_j_block(self, playing_field): #donetemp_rotated_j = Block("j_block", self.color)temp_rotated_j.tiles = self.tiles.copy()if self.direction == directions[0]: temp_rotated_j.tiles[0] = Tile(temp_rotated_j.tiles[1].x, temp_rotated_j.tiles[0].y, temp_rotated_j.color)temp_rotated_j.tiles[1] = Tile(temp_rotated_j.tiles[0].x-tile_length, temp_rotated_j.tiles[0].y, temp_rotated_j.color)temp_rotated_j.tiles[2] = Tile(temp_rotated_j.tiles[1].x, temp_rotated_j.tiles[1].y-tile_length, temp_rotated_j.color)temp_rotated_j.tiles[3] = Tile(temp_rotated_j.tiles[2].x, temp_rotated_j.tiles[2].y-tile_length, temp_rotated_j.color)temp_rotated_j.direction = directions[2] # "horizontal_1"elif self.direction == directions[2]:temp_rotated_j.tiles[0] = Tile(temp_rotated_j.tiles[1].x-tile_length, temp_rotated_j.tiles[0].y, temp_rotated_j.color)temp_rotated_j.tiles[1] = Tile(temp_rotated_j.tiles[0].x, temp_rotated_j.tiles[0].y-tile_length, temp_rotated_j.color)temp_rotated_j.tiles[2] = Tile(temp_rotated_j.tiles[1].x+tile_length, temp_rotated_j.tiles[1].y, temp_rotated_j.color)temp_rotated_j.tiles[3] = Tile(temp_rotated_j.tiles[2].x+tile_length, temp_rotated_j.tiles[2].y, temp_rotated_j.color)temp_rotated_j.direction = directions[1] #"vertical_2"elif self.direction == directions[1]: temp_rotated_j.tiles[0] = Tile(temp_rotated_j.tiles[2].x, temp_rotated_j.tiles[0].y, temp_rotated_j.color)temp_rotated_j.tiles[1] = Tile(temp_rotated_j.tiles[0].x, temp_rotated_j.tiles[0].y-tile_length, temp_rotated_j.color)temp_rotated_j.tiles[2] = Tile(temp_rotated_j.tiles[1].x, temp_rotated_j.tiles[1].y-tile_length, temp_rotated_j.color)temp_rotated_j.tiles[3] = Tile(temp_rotated_j.tiles[2].x-tile_length, temp_rotated_j.tiles[2].y, temp_rotated_j.color)temp_rotated_j.direction = directions[3] #"horizontal_2"elif self.direction == directions[3]: #back to normal:temp_rotated_j.tiles[0] = Tile(temp_rotated_j.tiles[0].x, temp_rotated_j.tiles[0].y, temp_rotated_j.color)temp_rotated_j.tiles[1] = Tile(temp_rotated_j.tiles[0].x+tile_length, temp_rotated_j.tiles[0].y, temp_rotated_j.color)temp_rotated_j.tiles[2] = Tile(temp_rotated_j.tiles[0].x-tile_length, temp_rotated_j.tiles[0].y, temp_rotated_j.color)temp_rotated_j.tiles[3] = Tile(temp_rotated_j.tiles[1].x, temp_rotated_j.tiles[1].y-tile_length, temp_rotated_j.color) temp_rotated_j.direction = directions[0] #"vertical_1"for block_tile in temp_rotated_j.tiles:if block_tile.x <= off_set_x or block_tile.x >= playing_field_width:return y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x == tile.x and block_tile.y  == tile.y:return y += tile_lengthself.direction = temp_rotated_j.directionself.tiles = temp_rotated_j.tilesdef rotate_s_block(self, playing_field): #donetemp_rotated_s = Block("s_block", self.color)temp_rotated_s.tiles = self.tiles.copy()if self.direction == directions[0] or self.direction == directions[1]:temp_rotated_s.tiles[0] = Tile(temp_rotated_s.tiles[3].x, temp_rotated_s.tiles[0].y, temp_rotated_s.color)temp_rotated_s.tiles[1] = Tile(temp_rotated_s.tiles[0].x, temp_rotated_s.tiles[0].y-tile_length, temp_rotated_s.color)temp_rotated_s.tiles[2] = Tile(temp_rotated_s.tiles[1].x-tile_length, temp_rotated_s.tiles[1].y, temp_rotated_s.color)temp_rotated_s.tiles[3] = Tile(temp_rotated_s.tiles[2].x, temp_rotated_s.tiles[2].y-tile_length, temp_rotated_s.color)temp_rotated_s.direction = directions[2] # "horizontal_1"elif self.direction == directions[2] or self.direction == directions[3]temp_rotated_s.tiles[0] = Tile(temp_rotated_s.tiles[2].x, temp_rotated_s.tiles[0].y, temp_rotated_s.color)temp_rotated_s.tiles[1] = Tile(temp_rotated_s.tiles[0].x-tile_length, temp_rotated_s.tiles[0].y, temp_rotated_s.color)temp_rotated_s.tiles[2] = Tile(temp_rotated_s.tiles[0].x, temp_rotated_s.tiles[0].y-tile_length, temp_rotated_s.color)temp_rotated_s.tiles[3] = Tile(temp_rotated_s.tiles[2].x+tile_length, temp_rotated_s.tiles[2].y, temp_rotated_s.color)temp_rotated_s.direction = directions[0] #"vertical_1"for block_tile in temp_rotated_s.tiles:if block_tile.x <= off_set_x or block_tile.x >= playing_field_width:return y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x == tile.x and block_tile.y  == tile.y:returny += tile_lengthself.direction = temp_rotated_s.directionself.tiles = temp_rotated_s.tiles   def rotate_t_block(self, playing_field): #donetemp_rotated_t = Block("j_block", self.color)temp_rotated_t.tiles = self.tiles.copy()if self.direction == directions[0]: temp_rotated_t.tiles[0] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y, temp_rotated_t.color)temp_rotated_t.tiles[1] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y-tile_length, temp_rotated_t.color)temp_rotated_t.tiles[2] = Tile(temp_rotated_t.tiles[1].x, temp_rotated_t.tiles[1].y-tile_length, temp_rotated_t.color)temp_rotated_t.tiles[3] = Tile(temp_rotated_t.tiles[1].x+tile_length, temp_rotated_t.tiles[1].y, temp_rotated_t.color)temp_rotated_t.direction = directions[2] # "horizontal_1"elif self.direction == directions[2]:temp_rotated_t.tiles[0] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y, temp_rotated_t.color)temp_rotated_t.tiles[1] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y-tile_length, temp_rotated_t.color)temp_rotated_t.tiles[2] = Tile(temp_rotated_t.tiles[1].x-tile_length, temp_rotated_t.tiles[1].y, temp_rotated_t.color)temp_rotated_t.tiles[3] = Tile(temp_rotated_t.tiles[1].x+tile_length, temp_rotated_t.tiles[2].y, temp_rotated_t.color)temp_rotated_t.direction = directions[1] #"vertical_2"elif self.direction == directions[1]:temp_rotated_t.tiles[0] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y, temp_rotated_t.color)temp_rotated_t.tiles[1] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y-tile_length, temp_rotated_t.color)temp_rotated_t.tiles[2] = Tile(temp_rotated_t.tiles[1].x, temp_rotated_t.tiles[1].y-tile_length, temp_rotated_t.color)temp_rotated_t.tiles[3] = Tile(temp_rotated_t.tiles[1].x-tile_length, temp_rotated_t.tiles[1].y, temp_rotated_t.color)temp_rotated_t.direction = directions[3] #"horizontal_2"elif self.direction == directions[3]: #back to normal:temp_rotated_t.tiles[0] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y, temp_rotated_t.color)temp_rotated_t.tiles[1] = Tile(temp_rotated_t.tiles[0].x+tile_length, temp_rotated_t.tiles[0].y, temp_rotated_t.color)temp_rotated_t.tiles[2] = Tile(temp_rotated_t.tiles[0].x-tile_length, temp_rotated_t.tiles[0].y, temp_rotated_t.color)temp_rotated_t.tiles[3] = Tile(temp_rotated_t.tiles[0].x, temp_rotated_t.tiles[0].y-tile_length, temp_rotated_t.color) temp_rotated_t.direction = directions[0] #"vertical_1"for block_tile in temp_rotated_t.tiles:if block_tile.x <= off_set_x or block_tile.x >= playing_field_width:return y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x == tile.x and block_tile.y  == tile.y:returny += tile_lengthself.direction = temp_rotated_t.directionself.tiles = temp_rotated_t.tilesdef rotate_z_block(self, playing_field): #donetemp_rotated_z = Block("z_block", self.color)temp_rotated_z.tiles = self.tiles.copy()if self.direction == directions[0] or self.direction == directions[1]:temp_rotated_z.tiles[0] = Tile(temp_rotated_z.tiles[3].x, temp_rotated_z.tiles[0].y, temp_rotated_z.color)temp_rotated_z.tiles[1] = Tile(temp_rotated_z.tiles[0].x, temp_rotated_z.tiles[0].y-tile_length, temp_rotated_z.color)temp_rotated_z.tiles[2] = Tile(temp_rotated_z.tiles[1].x+tile_length, temp_rotated_z.tiles[1].y, temp_rotated_z.color)temp_rotated_z.tiles[3] = Tile(temp_rotated_z.tiles[2].x, temp_rotated_z.tiles[2].y-tile_length, temp_rotated_z.color)temp_rotated_z.direction = directions[2] # "horizontal_1"elif self.direction == directions[2] or self.direction == directions[3]:temp_rotated_z.tiles[0] = Tile(temp_rotated_z.tiles[3].x, temp_rotated_z.tiles[0].y, temp_rotated_z.color)temp_rotated_z.tiles[1] = Tile(temp_rotated_z.tiles[0].x+tile_length, temp_rotated_z.tiles[0].y, temp_rotated_z.color)temp_rotated_z.tiles[2] = Tile(temp_rotated_z.tiles[0].x, temp_rotated_z.tiles[0].y-tile_length, temp_rotated_z.color)temp_rotated_z.tiles[3] = Tile(temp_rotated_z.tiles[2].x-tile_length, temp_rotated_z.tiles[2].y, temp_rotated_z.color)temp_rotated_z.direction = directions[0] #"vertical_1"for block_tile in temp_rotated_z.tiles:if block_tile.x <= off_set_x or block_tile.x >= playing_field_width:return y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.x == tile.x and block_tile.y  == tile.y:returny += tile_lengthself.direction = temp_rotated_z.directionself.tiles = temp_rotated_z.tiles      def fall_completely(self, next_block, playing_field, player):from tetris import update_graphicsfall= Truewhile fall:for block_tile in self.tiles:if block_tile.y >= playing_field_height+off_set_y-tile_length:fall = False  break #check already existed tilesfor block_tile in self.tiles:y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and block_tile.y+tile_length == tile.y and block_tile.x == tile.x: fall = False   breaky += tile_lengthif not fall:breakfor tile in self.tiles:tile.y += tile_lengthupdate_graphics(self, next_block, playing_field, player)clock.get_rawtime()clock.tick(50)class Player:def __init__(self, start_time):self.start_time = start_timeself.time_since_start = 0self.score = 0 

tetris.py文件:

#import libraries
import pygame
from util import *def update_graphics(block, next_block, playing_field, player):#Sets black background and textDISPLAY_SCREEN.blit(background_img, (0, 0))pygame.draw.rect(DISPLAY_SCREEN , black, (off_set_x, off_set_y, playing_field_width, playing_field_height) )font = pygame.font.SysFont("comicsansms", 48)rendered_text = font.render("Tetris", 1, orange)DISPLAY_SCREEN.blit(rendered_text, (width/2-80, 10))#Displays Current score and timeplayer.time_since_start = pygame.time.get_ticks() - player.start_timefont = pygame.font.SysFont("comicsansms", 20)rendered_text_time =  font.render("Time: " + str(player.time_since_start), 1, orange)DISPLAY_SCREEN.blit(rendered_text_time, (playing_field_width+tile_length*2, playing_field_height-80))  rendered_text_score = font.render("Score: " + str(player.score), 1, orange)DISPLAY_SCREEN.blit(rendered_text_score, (playing_field_width+tile_length*2, playing_field_height-50))#Draw the small screen for the next blockdraw_small_screen(next_block)#Set tilesy = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:tile.draw_tile()y += tile_length#Blocks while fallingfor tile in block.tiles:if tile.y >= off_set_y:tile.draw_tile()#Sets borderspygame.draw.line(DISPLAY_SCREEN , blue, (off_set_x-2, off_set_y-3), (playing_field_width+off_set_x+1, off_set_y-3), 4) # horizontal line toppygame.draw.line(DISPLAY_SCREEN , blue, (off_set_x-2, off_set_y+playing_field_height+1), (playing_field_width+off_set_x+1, off_set_y+playing_field_height+1), 4) # horizontal line bottompygame.draw.line(DISPLAY_SCREEN , blue, (off_set_x-3, off_set_y-3), (off_set_x-3, off_set_y+playing_field_height+1), 4) # vertical line leftpygame.draw.line(DISPLAY_SCREEN , blue, (playing_field_width+off_set_x+1, off_set_y-3), (playing_field_width+off_set_x+1, off_set_y+playing_field_height+1), 4) # vertical line right#Sets Gridcurrent_y_horizontal_lines = off_set_ycurrent_x_vertical_lines = off_set_xfor i in range(19): current_y_horizontal_lines += 33pygame.draw.line(DISPLAY_SCREEN , white, (off_set_x, current_y_horizontal_lines), (playing_field_width+off_set_x-1, current_y_horizontal_lines)) # horizontal line topfor j in range(9): current_x_vertical_lines += 33        pygame.draw.line(DISPLAY_SCREEN , white, (current_x_vertical_lines-1, off_set_y), (current_x_vertical_lines-1, playing_field_height+off_set_y)) # horizontal line toppygame.display.update()def draw_small_screen(next_block):#Sets backgroundpygame.draw.rect(DISPLAY_SCREEN , black, (playing_field_width+tile_length*2, height/2-20, 6*tile_length, 6*tile_length) )#Sets borderspygame.draw.line(DISPLAY_SCREEN , blue, (playing_field_width+tile_length*2-2, height/2-20-2), ((6*tile_length)+(playing_field_width+tile_length*2), (height/2-20-2)), 3) # horizontal line toppygame.draw.line(DISPLAY_SCREEN , blue, (playing_field_width+tile_length*2-2, height/2-20+(6*tile_length)), ((6*tile_length)+(playing_field_width+tile_length*2), height/2-20+(6*tile_length)), 3) # horizontal line bottompygame.draw.line(DISPLAY_SCREEN , blue, (playing_field_width+tile_length*2-2, height/2-20-2), (playing_field_width+tile_length*2-2, height/2-20+(6*tile_length)), 3) # vertical line leftpygame.draw.line(DISPLAY_SCREEN , blue, ((6*tile_length)+(playing_field_width+tile_length*2), height/2-20-2), ((6*tile_length)+(playing_field_width+tile_length*2), height/2-20+(6*tile_length)), 3) # vertical line right#Sets textfont = pygame.font.SysFont("comicsansms", 30)rendered_text = font.render("Next Block", 1, orange)DISPLAY_SCREEN.blit(rendered_text, (playing_field_width+tile_length*2,  height/2-70))#Displays next blocktemp_block = Block(next_block.shape, next_block.color)  temp_block.tiles = [Tile(playing_field_width+tile_length*2+2*tile_length, height/2-20+4*tile_length, next_block.color), Tile(0, 0, next_block.color), Tile(0, 0, next_block.color), Tile(0, 0, next_block.color)]temp_block.complete_block()for tile in temp_block.tiles:tile.draw_tile()def is_game_over(playing_field, player): y = off_set_yfor i in range(20):for tile in playing_field.tiles["row"+str(i+1)][y]:if not tile.empty and tile.y <= off_set_y: temp_y = off_set_yfor j in range(20):for tile in playing_field.tiles["row"+str(j+1)][temp_y]:tile.draw_tile()temp_y += tile_lengthfont = pygame.font.SysFont("comicsansms", 48)rendered_text = font.render("GAME OVER", 1, white)DISPLAY_SCREEN.blit(rendered_text, (off_set_x+20, playing_field_height/2))pygame.display.update()time.sleep(2)   introduction(player)y += tile_lengthdef start_game():    global best_scoreglobal longest_timerand_index = random.randint(0, 6)block = Block(shapes[rand_index], block_colors[rand_index])next_rand_index = random.randint(0, 6)next_block = Block(shapes[next_rand_index], block_colors[next_rand_index]) playing_field = PlayingField()start_time = pygame.time.get_ticks()player = Player(start_time)while True:update_graphics(block, next_block, playing_field, player)(block, next_block, is_new) = block.get_new_block(next_block, playing_field, player)if is_new:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()pygame.event.clear()manage_events(block, next_block, playing_field, player)update_graphics(block, next_block, playing_field, player)block.block_is_falling(next_block, playing_field, player)update_graphics(block, next_block, playing_field, player)playing_field.destory_full_row(player)update_graphics(block, next_block, playing_field, player)if player.score > best_score:best_score = player.scoreif player.time_since_start > longest_time:longest_time = player.time_since_startis_game_over(playing_field, player)update_graphics(block, next_block, playing_field, player)pygame.display.update()clock.tick(60)def manage_events(block, next_block, playing_field, player):for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:#move the block to the leftblock.move_left(playing_field)elif event.key == pygame.K_RIGHT:#move the block to the rightblock.move_right(playing_field)elif event.key == pygame.K_UP:# rotate blockblock.rotate(next_block, playing_field, player)if event.key == pygame.K_SPACE:# let the block fall completelyblock.fall_completely(next_block, playing_field, player)if event.key == pygame.K_DOWN:# let the block fall down fasterblock.block_is_falling(next_block, playing_field, player, "faster")update_graphics(block, next_block, playing_field, player)def introduction(player = None):button_width = 300button_height = 90#start_x_button = width/2-button_width/2play_button = Button(blue, orange, -400, height/2, button_width, button_height, 32, black, white, "PLAY")instructions_button = Button(blue, orange, width+150, height/2+button_height+10, button_width,button_height, 32, black, white, "INSTRUCTIONS")quit_button = Button(blue, orange, -400, height/2+button_height*2+20, button_width,button_height, 32, black, white, "QUIT")font = pygame.font.SysFont("comicsansms", 48)rendered_text = font.render("Tetris", 1, black)rendered_text_y = height#To draw the Tetris text in an animated waywhile rendered_text_y > 10: DISPLAY_SCREEN.blit(background_img, (0, 0))for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()rendered_text_y -= 1.5DISPLAY_SCREEN.blit(rendered_text, (width/2-80, rendered_text_y))pygame.display.update()#To draw the score and time texts in an animated wayif player:font_small = pygame.font.SysFont("comicsansms", 30)rendered_current_score = font_small.render("Current Score: " + str(player.score), 1, orange)rendered_best_score = font_small.render("Best Score: " + str(best_score), 1, orange)rendered_current_time = font_small.render("Current Time: " + str(player.time_since_start), 1, orange)rendered_longest_time = font_small.render("Longest Time: " + str(longest_time), 1, orange)rendered_current_score_y = heightrendered_best_score_y = height+40rendered_current_time_y = height+80rendered_longest_time_y = height+120while rendered_current_score_y > 150: DISPLAY_SCREEN.blit(background_img, (0, 0))DISPLAY_SCREEN.blit(rendered_text, (width/2-80, rendered_text_y))for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()rendered_current_score_y -= 1.5rendered_best_score_y -= 1.5rendered_current_time_y -= 1.5rendered_longest_time_y -= 1.5DISPLAY_SCREEN.blit(rendered_current_score, (off_set_x, rendered_current_score_y))DISPLAY_SCREEN.blit(rendered_best_score, (off_set_x+45, rendered_best_score_y))DISPLAY_SCREEN.blit(rendered_current_time, (off_set_x+15, rendered_current_time_y))DISPLAY_SCREEN.blit(rendered_longest_time, (off_set_x+15, rendered_longest_time_y))pygame.display.update()#To draw the buttons in an animated waywhile play_button.x < width/2-button_width/2 or instructions_button.x > width/2-button_width/2:DISPLAY_SCREEN.blit(background_img, (0, 0))DISPLAY_SCREEN.blit(rendered_text, (width/2-80, rendered_text_y))if player:DISPLAY_SCREEN.blit(rendered_current_score, (off_set_x, rendered_current_score_y))DISPLAY_SCREEN.blit(rendered_best_score, (off_set_x+45, rendered_best_score_y))DISPLAY_SCREEN.blit(rendered_current_time, (off_set_x+15, rendered_current_time_y))DISPLAY_SCREEN.blit(rendered_longest_time, (off_set_x+15, rendered_longest_time_y))for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if play_button.x < width/2-button_width/2:play_button.x += 3quit_button.x += 3if instructions_button.x > width/2-button_width/2 :    instructions_button.x -= 3play_button.blit(DISPLAY_SCREEN)instructions_button.blit(DISPLAY_SCREEN)quit_button.blit(DISPLAY_SCREEN)pygame.display.update()run = Truewhile run:DISPLAY_SCREEN.blit(background_img, (0, 0))DISPLAY_SCREEN.blit(rendered_text, (width/2-80, rendered_text_y))if player:DISPLAY_SCREEN.blit(rendered_current_score, (off_set_x, rendered_current_score_y))DISPLAY_SCREEN.blit(rendered_best_score, (off_set_x+45, rendered_best_score_y))DISPLAY_SCREEN.blit(rendered_current_time, (off_set_x+15, rendered_current_time_y))DISPLAY_SCREEN.blit(rendered_longest_time, (off_set_x+15, rendered_longest_time_y))# Get the position of the mousemouse_position = pygame.mouse.get_pos() for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.MOUSEBUTTONDOWN:if play_button.is_clicked(mouse_position, event):start_game()run = Falseelif instructions_button.is_clicked(mouse_position, event):instructions(player)run = Falseelif quit_button.is_clicked(mouse_position, event):pygame.quit()sys.exit()if play_button.is_hovered_over(mouse_position):play_button.blit_hovered_over(DISPLAY_SCREEN)else:play_button.blit(DISPLAY_SCREEN, gray)if instructions_button.is_hovered_over(mouse_position):instructions_button.blit_hovered_over(DISPLAY_SCREEN)else:instructions_button.blit(DISPLAY_SCREEN, gray)if quit_button.is_hovered_over(mouse_position):quit_button.blit_hovered_over(DISPLAY_SCREEN)else:quit_button.blit(DISPLAY_SCREEN, gray)clock.tick(60)pygame.display.update()def instructions(player = None):button_width = 150button_height = 60play_button = Button(blue, orange, width-150-10, height-80, button_width, button_height, 32, black, white, "PLAY >>")back_button = Button(blue, orange, 10, height-80, button_width, button_height, 32, black, white, "<< BACK")run = Truewhile run:DISPLAY_SCREEN.blit(instructions_img, (0, 0))font = pygame.font.SysFont("comicsansms", 48)rendered_text = font.render("Tetris", 1, orange)DISPLAY_SCREEN.blit(rendered_text, (width/2-80, 10))# Get the position of the mousemouse_position = pygame.mouse.get_pos() for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.MOUSEBUTTONDOWN:if play_button.is_clicked(mouse_position, event):start_game()run = Falseelif back_button.is_clicked(mouse_position, event):introduction(player)run = Falseinstructions_label = "Instructions" font = pygame.font.SysFont("comicsansms", 40)rendered_text = font.render(instructions_label, 1, orange)DISPLAY_SCREEN.blit(rendered_text, (width/2 - rendered_text.get_width()/2, 100))instructions1 = "   Move Right:                      right arrow >"  instructions2 = "   Move   Left:                     left    arrow <" instructions3 = "          Rotate:                      up      arrow ^" instructions4 = "   Soft  Drop:                      down   arrow" instructions5 = "   Hard  Drop:                      space"font = pygame.font.SysFont("comicsansms", 20)rendered_text1 = font.render(instructions1, 1, orange)rendered_text2 = font.render(instructions2, 1, orange)rendered_text3 = font.render(instructions3, 1, orange)rendered_text4 = font.render(instructions4, 1, orange)rendered_text5 = font.render(instructions5, 1, orange)DISPLAY_SCREEN.blit(rendered_text1, (20, 200))DISPLAY_SCREEN.blit(rendered_text2, (20, 240))DISPLAY_SCREEN.blit(rendered_text3, (20, 280))DISPLAY_SCREEN.blit(rendered_text4, (20, 320))DISPLAY_SCREEN.blit(rendered_text5, (20, 360))if play_button.is_hovered_over(mouse_position):play_button.blit_hovered_over(DISPLAY_SCREEN)else:play_button.blit(DISPLAY_SCREEN, gray)if back_button.is_hovered_over(mouse_position):back_button.blit_hovered_over(DISPLAY_SCREEN)else:back_button.blit(DISPLAY_SCREEN, gray)clock.tick(60)pygame.display.update()if __name__ == "__main__":introduction()

Python俄羅斯方塊Tetris源文件本站下載:
https://download.csdn.net/download/mufenglaoshi/88612722

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/210322.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/210322.shtml
英文地址,請注明出處:http://en.pswp.cn/news/210322.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

wireshark過濾包小技巧

1、過濾包含某個字符串的數據包&#xff1a; 或者&#xff1a; 2、過濾包含某一連續十六進制的數據包&#xff1a; 或者&#xff1a; 3、過濾精確到位數位置 或者&#xff1a;

關于使用EB tresos出現無法激活的情況解決

EB安裝完成時需要激活才能使用的&#xff0c;不然都無法建立工程。 我在安裝eb studio時就是在激活方面有問題導致無法使用&#xff0c;下面講解出現了什么問題以及我如何去解除的。 1.出現的錯誤提示&#xff1f; ERROR&#xff1a;flexActAPPActivationSend按照在官網中&…

低代碼:輕松構建應用程序的新時代

在當今數字化時代&#xff0c;應用程序對于日常企業業務的開展&#xff0c;已經成為一種剛需。然而&#xff0c;應用程序開發的過程往往耗時耗力&#xff0c;對于企業來講&#xff0c;是一筆不小的成本開支。低代碼問世以來&#xff0c;一直在嘗試為業務人員賦能&#xff0c;讓…

扁平按鈕樣式

上圖 代碼&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>扁平按鈕</title><style>body {margin: 0;padding: 0;height: 100vh;display: flex;justify-content: center;ali…

Web漏洞-XSS繞過和pikachu靶場4個場景(三)

★★實戰前置聲明★★ 文章中涉及的程序(方法)可能帶有攻擊性&#xff0c;僅供安全研究與學習之用&#xff0c;讀者將其信息做其他用途&#xff0c;由用戶承擔全部法律及連帶責任&#xff0c;文章作者不承擔任何法律及連帶責任。 1、XSS漏洞挖掘與繞過 1.1、XSS漏洞挖掘 數據…

排序算法---冒泡排序

1. 原理 對數組進行遍歷&#xff0c;每次對相鄰的兩個元素進行比較&#xff0c;如果大的在前面&#xff0c;則交換兩個元素的位置&#xff0c;完成一趟遍歷后&#xff0c;數組中最大的數值到了數組的末尾。再對前面n-1個數值進行相同的遍歷。一共完成n-1趟遍歷就實現了排序。 1…

代碼隨想錄 63. 不同路徑 II

題目 一個機器人位于一個 m x n 網格的左上角 &#xff08;起始點在下圖中標記為 “Start” &#xff09;。 機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角&#xff08;在下圖中標記為 “Finish”&#xff09;。 現在考慮網格中有障礙物。那么從左上角到右下…

UI界面程序鼠標右鍵彈出菜單的一些事

1.概述 在做客戶端UI程序時&#xff0c;鼠標右鍵彈出菜單這種操作非常常見&#xff0c;一般在鼠標右鍵按下或者鼠標右鍵抬起事件中響應操作&#xff0c;顯示菜單即可&#xff0c;但是有時涉及到鼠標的移動&#xff0c;就是鼠標按下右鍵且移動時&#xff0c;則不需要彈出菜單&a…

104. 二叉樹的最大深度(Java)

目錄 解法&#xff1a; 官方解答&#xff1a; 方法一&#xff1a;深度優先搜索 方法二&#xff1a;廣度優先搜索 思路與算法 復雜度分析 時間復雜度&#xff1a; 空間復雜度&#xff1a; 給定一個二叉樹 root &#xff0c;返回其最大深度。 二叉樹的 最大深度 是指從根…

【密碼學引論】數字簽名

第八章 數字簽名 1、數字簽名體制包括兩個方面&#xff1a;施加簽名、驗證簽名 SIG(M,Kd)S VER(S,Ke)bool&#xff08;真、假&#xff09; 2、數字簽名和信息加密的區別&#xff08;從密碼學五個組成部分來回答 3、安全性要求&#xff1a;先簽名后加密&#xff1b;針對哈希函…

如何入門網絡安全_網絡安全自學

由于我之前寫了不少網絡安全技術相關的故事文章&#xff0c;不少讀者朋友知道我是從事網絡安全相關的工作&#xff0c;于是經常有人在微信里問我&#xff1a; 我剛入門網絡安全&#xff0c;該怎么學&#xff1f;要學哪些東西&#xff1f;有哪些方向&#xff1f;怎么選&#xff…

算法:合并兩個有序數組(雙指針)

時間復雜度 O(m n)&#xff0c;空間復雜度 O(1) /*** param {number[]} nums1* param {number} m* param {number[]} nums2* param {number} n* return {void} Do not return anything, modify nums1 in-place instead.*/ var merge function(nums1,m,nums2,n) {let p1 m-1…

harmonyOS學習筆記之@Styles裝飾器與@Extend裝飾器

Styles裝飾器 定義組件重用樣式 自定義樣式函數使用裝飾器 可以定義在組件內或全局,內部優先級>外部,內部不需要function,外部需要function 定義在組件內的styles可以通過this訪問組件內部的常量和狀態變量,可以在styles里通過事件來改變狀態變量 弊端:只支持通用屬性和通用…

深度模型訓練時CPU或GPU的使用model.to(device)

一、使用device控制使用CPU還是GPU device torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 單GPU或者CPU.先判斷機器上是否存在GPU&#xff0c;沒有則使用CPU訓練 model model.to(device) data data.to(device)#或者在確定有GPU的…

解決 Cannot read properties of undefined (reading ‘getUserMedia‘) 報錯

[TOC](解決 Cannot read properties of undefined (reading ‘getUserMedia’) 報錯) 0. 背景 使用瀏覽器輸入語音時&#xff0c;瀏覽器的控制臺里面有下面錯誤信息。 Cannot read properties of undefined (reading getUserMedia)1. 解決方法 在瀏覽器中訪問 chrome://fla…

半導體材料

半導體材料 電子元器件百科 文章目錄 半導體材料前言一、半導體材料是什么二、半導體材料的類別三、半導體材料的應用實例四、半導體材料的作用原理總結前言 半導體材料具有獨特的電學性質,使其在電子器件和集成電路中有廣泛的應用。通過控制半導體材料中載流子的濃度和運動方…

數字化浪潮下,你的企業數字化轉型了嗎?

企業數字化轉型面臨的挑戰 技術轉型挑戰&#xff1a;數字化轉型涉及到各種新技術、新軟件和新硬件&#xff0c;需要企業有一定的技術實力和專業知識&#xff0c;并且需要不斷學習和適應變化。對于傳統企業來說&#xff0c;可能面臨技術門檻高、技術更新快等問題。組織結構轉型…

如何用flex布局設計登錄頁?

使用 Flex 布局設計登錄頁是一種簡單而靈活的方式&#xff0c;讓頁面在不同屏幕大小下都能有良好的布局。以下是一個簡單的例子&#xff0c;演示如何使用 Flex 布局設計登錄頁&#xff1a; HTML 結構&#xff1a; <!DOCTYPE html> <html lang"en"> <…

從Android源碼中生成系統簽名文件

從Android源碼中生成系統簽名文件 文章目錄 從Android源碼中生成系統簽名文件1、在linux中打開編譯android源碼目錄。2、cd到簽名文件位置3、生成 platform.pem文件4、生成 platform.p12 文件5、生成 最終的 platform.jks系統簽名文件6、把platform.jks 放到Studio 項目app 根目…

word中,文本框如何跨頁?

我們經常使用word編輯一些文檔&#xff0c;文檔中往往會有一些比較大的文本框&#xff0c;需要跨多頁&#xff0c;我們可以使用本文章中的方法&#xff0c;將文本框連接在一起&#xff0c;是的內容自動跨頁。 在文字中插入兩個文本框如下圖&#xff1a; 將內容放到第一個文本框…