当前位置:网站首页>Make 2048 games with pyGame
Make 2048 games with pyGame
2022-07-16 08:05:00 【Harazekong】
I haven't written for a long time , I haven't learned much about computers during the summer vacation , But I insisted on reciting the word Hongbao book for more than a month , I read the basic course of Tang Shen . I really didn't expect that I could recite it with perseverance 150 Multi page words , I also finished writing a front and back calligraphy, which I have never insisted on before , Maybe I've grown up and become sensible ,hhh. I also practiced section 3 . I took the exam for the third time the day after tomorrow , I hope I can pass the exam this time .
After dinner, I have nothing to do , Prepare to return to the past and write a small article . Now let's share my python One of the two final assignments ——Pygame Developed 2048
This 2048 The main part of the project is that I am be based on Python Of PyGame Library implementation of 2048 Little games Looking for , I added music , The main menu , Interface , Reopen this close , Go back to the previous step , Record the highest score
The complete code of the game is in the third part , If you don't want to see the explanation, you can directly pull to Part3
One 、 Game effect display
1. Run the program , Welcome screen appears . Click the left mouse button , The main menu interface appears .

2. Click the respectively “ Introduction to play ” and “ Game skills ”, Enter the corresponding interface .

3. Click on “ Start the game ” Button , Enter the game . Manipulate up, down, left, right and constantly merge boxes to improve scores .

4. When you take the wrong steps , Click the space . You can go back to the previous step .

5. When the game fails , Click on “New Game” Button to play a new game .

6. When the game can't go on or it doesn't work well , The system automatically determines failure . You can also click NewGame Play another game .

7. There is a scoreboard in the upper right corner , It can record the player's highest score .
Two 、 Detailed introduction of function module development
Next, I will explain the functions of each part from seven parts , design idea . Maybe a little more , It's normal not to understand , Think more, run more, experience more . After all, it's not easy to understand the big homework that others spent two weeks writing . I was going to write the title 2048 I didn't rush to write first , I went online for a week first 2048^ ^. It's still of great help to the gangsters like me .
1. Welcome interface and main menu
This part is purely for adding up the number of lines of code , When I finished writing it for the first time, only 300 Row or so , Who knows that the teacher specially said the yard size in class at night? At least 500+, At that time, I fainted directly ! Let's write a simple 2048 Well , It's not like brother Qi Rui who writes about advanced super Mary and Lianliankan , The rest of that 200 How can I get together , And it's all finished , Is it not that heaven is going to kill me ? Later, I thought hard , Add a main menu , I made a game to explain that I deliberately typed many lines of Chinese characters to make up the number , Add a function of playing music , Ha ha ha , Tact as I , But I was criticized miserably by Uncle Jing ,/(ㄒoㄒ)/~~
def game_view_page0():# Game welcome interface , Here an animation function is realized : Two rows of different sizes and colors “2048 Little games ” Rotate around the center of the screen
FPS = 5
BLACK = (0, 0, 0)
BROWN = (187, 173, 160)
WHITE = (255, 255, 255)
BGCOLOR = BROWN
titleFont = pygame.font.Font(r'C:\Windows\Fonts\simkai.ttf', 100)
titleSurf1 = titleFont.render('2048 Little games ', True, BLACK)
titleSurf2 = titleFont.render('2048 Little games ', True, WHITE)
degrees1 = 0
degrees2 = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN or event.type == KEYUP:
return
screen.fill(BGCOLOR)
rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
rotatedRect1 = rotatedSurf1.get_rect()
rotatedRect1.center = (screen_width / 2, screen_height / 2 - 50)
screen.blit(rotatedSurf1, rotatedRect1)
rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
rotatedRect2 = rotatedSurf2.get_rect()
rotatedRect2.center = (screen_width / 2, screen_height / 2 - 50)
screen.blit(rotatedSurf2, rotatedRect2)
screen.blit(write(" Click the left mouse button to enter the game ", height=30, color=(255, 255, 255)),
(left_of_screen + 60, left_of_screen // 2 + 450))
pygame.display.update()
FPSCLOCK.tick(10)
degrees1 += 3
degrees2 += 5
It's all some Pygame Basic operation ,game_view_page0() Function is used to draw a starting welcome interface , There are two lines of text rotating with the center of the window as the axis in the interface “2048”, Click the left mouse button to enter the main menu .
2. Introduction to playing methods and high score skills
Same as 1 part , To round up the number of lines = =
def game_start_page():# Game start screen
# Load background image
screen.blit(background, (0, 0))
# Create several customized buttons
button4 = Button((left_of_screen + 110, 150), b4, 200, 80)
button5 = Button((left_of_screen + 110, 270), b5, 200, 80)
button6 = Button((left_of_screen + 110, 390), b6, 200, 80)
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if button4.isOver() == True:# If you press yes button4, Start the game
return
elif button5.isOver() == True:# If you press yes button5, That is, introduction to game playing
game_introduce()
screen.blit(background, (0, 0))
button4 = Button((left_of_screen + 110, 150), b4, 200, 80)
button5 = Button((left_of_screen + 110, 270), b5, 200, 80)
button6 = Button((left_of_screen + 110, 390), b6, 200, 80)
elif button6.isOver() == True:# If you press yes button6, Introduction to game skills
game_skill()
screen.blit(background, (0, 0))
button4 = Button((left_of_screen + 110, 150), b4, 200, 80)
button5 = Button((left_of_screen + 110, 270), b5, 200, 80)
button6 = Button((left_of_screen + 110, 390), b6, 200, 80)
screen.blit(write("2048", height=100, color=(119, 110, 101)),
(left_of_screen + 110, left_of_screen // 2))
pygame.display.update()game_start_page() Function is used to draw a game main menu , Players can choose their next steps in the main menu .
In the welcome interface, you first need to set the font size and text content of the rotating text on the home page of the game , Then take the center point of the text , Set the text placement , refresh frequency FPS Set to 10 The fluency meets the requirements . Put it on while True The welcome interface can be drawn in the dead loop .
The main menu contains three custom button components that can lead to different interfaces Button,Button Medium is_Over() Function can determine whether the user has clicked on the button with the mouse ;Button Loading with different pictures .
class Button(object):# This class is a customized button class , Use various buttons that appear in the game
def __init__(self, position, fileName, sizex, sizey):# Initialize the button , Including loading pictures , initial position , Button size
self.imageUp = pygame.image.load(fileName).convert_alpha()
self.position = position
self.imageUp = pygame.transform.scale(self.imageUp, (sizex, sizey))
screen.blit(self.imageUp, self.position)
def isOver(self):# Determine whether the mouse is placed on the button
point_x, point_y = pygame.mouse.get_pos()
x, y = self.position
w, h = self.imageUp.get_size()
in_x = x < point_x < x + w
in_y = y < point_y < y + h
return in_x and in_y
def render(self):# Decide whether to restart the game
global score
w, h = self.imageUp.get_size()
x, y = self.position
if self.isOver() == True:
score = 0
draw_box(0)
init_board()Screenshot of picture folder :

game_introduce() Used to display the game introduction interface .
game_skill() It is used to display the game skill introduction interface .
Set the text and position to be loaded , And then call screen.blit Function loads them onto the screen .
3. Moving and merging of squares ( Key points )
In fact, this part of me is also online copy Of , The logic of this part is relatively strong , It is the principle part of box merging and moving .
combinate() Function is used to perform the merge operation of the same block .
up() Function is used to correspond to the user pressing “ On ” Post key , Corresponding to the operation of merging blocks up .
down() Function is used to press “ Next ” Post key , Corresponding to the operation of merging blocks downward .
left() Used to correspond to the user pressing in the game “ Left ” Post key , Corresponding to the operation of merging boxes to the left .
right() Used to correspond to the user pressing in the game “ Right ” Post key , Corresponding to the operation of merging squares to the right .
combinate() Design idea of merging operation :
To perform a merge of the same squares in a row , First, put the numbers in this line into a new list from left to right ans in :
(1) When ans When there are two numbers in , Add them directly and merge them . Return the added new line .score Add the corresponding score .
(2) When ans When there are three numbers in , Let's first judge ans[0] and ans[1] Whether it is equal or not , Merge the two equally ; Otherwise, judgment and[1] and ans[2]. There are two possible combinations . And then score Add the corresponding score .
(3) When ans The same is true when there are four numbers in , You need to determine ans[0] and ans[1],ans[1] and ans[2],ans[2] and ans[3], There are three possible combinations .
When merging to the left, it goes from top to bottom line by line combinate() operation ; When merging to the right, reverse the left and right order of each line ; When merging upward, it is carried out from left to right in one column combinate() operation ; When merging downward, reverse the order from up to down .
I feel that I have said so much ,= = In fact, you just need to draw with a piece of paper , There are three situations , It doesn't seem too difficult ?
def combinate(L):# The function of this function is to merge the blocks , It is the key and difficult point of this procedure
global score
ans = [0, 0, 0, 0]
num = []
for i in L:
if i != 0:# Put all the numbers in this line on the list num In the middle
num.append(i)
length = len(num)
if length == 4:# There are 4 A digital
if num[0] == num[1]:#case1
ans[0] = num[0] + num[1]
score += ans[0]
if num[2] == num[3]:
ans[1] = num[2] + num[3]
score += ans[1]
else:
ans[1] = num[2]
ans[2] = num[3]
elif num[1] == num[2]:#case2
ans[0] = num[0]
ans[1] = num[1] + num[2]
ans[2] = num[3]
score += ans[1]
elif num[2] == num[3]:#case3
ans[0] = num[0]
ans[1] = num[1]
ans[2] = num[2] + num[3]
score += ans[2]
else:#case4 There are no figures that can be merged
for i in range(length):
ans[i] = num[i]
elif length == 3:# There are 3 A digital
if num[0] == num[1]:#case 1
ans[0] = num[0] + num[1]
ans[1] = num[2]
score += ans[0]
elif num[1] == num[2]:#case 2
ans[0] = num[0]
ans[1] = num[1] + num[2]
score += ans[1]
else:#case 3 There are no figures that can be merged
for i in range(length):
ans[i] = num[i]
elif length == 2:# There are 2 A digital
if num[0] == num[1]:#case 1
ans[0] = num[0] + num[1]
score += ans[0]
else:#case 2 There are no figures that can be merged
for i in range(length):
ans[i] = num[i]
elif length == 1:
ans[0] = num[0]
else:
pass
return ans
def left():# The user presses the left key to move
for i in range(4):
temp = combinate(board[i])
for j in range(4):
board[i][j] = temp[j]
def right():# The user presses the right button to move
for i in range(4):
temp = combinate(board[i][::-1])
for j in range(4):
board[i][3 - j] = temp[j]
def up():# The user presses the up key to move
for i in range(4):
to_comb = []
for j in range(4):
to_comb.append(board[j][i])
temp = combinate(to_comb)
for k in range(4):
board[k][i] = temp[k]
def down():# The user presses the next key to move
for i in range(4):
to_comb = []
for j in range(4):
to_comb.append(board[3 - j][i])
temp = combinate(to_comb)
for k in range(4):
board[3 - k][i] = temp[k]4.“ restart ” function
When the user clicks the restart button , Reload a game .
Set up a Button Class accepts user clicks , adopt self.is_Over() Function to determine whether the current mouse position and button position of the user overlap . When the user clicks the button , call self.render() function , Yes score fraction ,board Initialize the game panel .
5. Record the score and the highest score
Record the highest score of this machine and display it on high score It's about .
use txt The highest score of the file storage machine , Judge whether the current score is higher than the highest score when each set fails ,with open Open file in overwrite write mode , Write the score to txt Keep the file . Read the highest score in the reading mode every time , call screen.blit Displayed in the high score Partial Department .
6.“ Go back to the previous step " function
When the user goes wrong, he can click the space bar to return to the previous step .
Set up a tmpScore And list b Store the score of the previous step and the game situation . Press the space bar and assign the state of the previous step to the current state , Refresh the interface to realize the function of fallback .
7. Lose and win
Judge whether the user's game fails or wins .
Loop through the binary list board Medium element . When the list board There are no spaces in , That is, no 0 Element time , This game failed ; When the list board Numbers appear in 2048 when , This game is successful . Print the information to the screen and give corresponding prompts to the user .
def win():# Judge whether the current victory
for i in range(4):
for j in range(4):
if board[i][j] == 2048:# Yes 2048, It must be victory
return True
return False
def is_over():# Determine whether the current failure
for i in range(4):
for j in range(4):
if board[i][j] == 0:# Yes 0, There is also blank space , Certainly not a failure
return False
for i in range(4):
for j in range(3):
if board[i][j] == board[i][j + 1]:# There are the same letters on the left and right , Can also merge , Certainly not a failure
return False
for i in range(3):
for j in range(4):
if board[i][j] == board[i + 1][j]:# There are the same letters above and below , Can also merge , Certainly not a failure
return False
return True# failed 3、 ... and 、 Complete program code
# Some libraries used in this program
import os
import random
import pygame
from sys import exit
from copy import deepcopy
from pygame.locals import *
pygame.init()
FPS = 5
b4 = "button4.jpg"
b5 = "button5.jpg"
b6 = "button6.jpg"
folder = r'C:\Users\longlong\Music'
musics = [folder + '\\' + music for music in os.listdir(folder)
if music.endswith('.mp3')]
total = len(musics)
pygame.mixer.init()
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
box_size = 100 # Each little square
box_gap = 5 # The spacing between each small square and each small square
top_of_screen = 100 # The distance from the grid to the top of the window
bottom_of_screen = 20 # The distance from the grid to the bottom of the window
left_of_screen = 50 # The distance from the grid to the left end of the window
screen_width = 520 # The width of the game interface
screen_height = 600 # The height of the game interface
screen = pygame.display.set_mode((screen_width, screen_height), 0, 32) # Initializes a window or screen to be displayed
pygame.display.set_caption("My2048") # Set game window title
background = pygame.image.load('background3.jpg').convert() # Set the game background
high_score_name = "high_score.txt"
score = 0 # score
tmpScore = 0
high_score = 0
def play_music():# The function of this function is to play music
if not pygame.mixer.music.get_busy():
nextMusic = random.choice(musics)
pygame.mixer.music.load(nextMusic)
pygame.mixer.music.play(1)
else:
time.sleep(1)
class Button(object):# This class is a customized button class , Use various buttons that appear in the game
def __init__(self, position, fileName, sizex, sizey):# Initialize the button , Including loading pictures , initial position , Button size
self.imageUp = pygame.image.load(fileName).convert_alpha()
self.position = position
self.imageUp = pygame.transform.scale(self.imageUp, (sizex, sizey))
screen.blit(self.imageUp, self.position)
def isOver(self):# Determine whether the mouse is placed on the button
point_x, point_y = pygame.mouse.get_pos()
x, y = self.position
w, h = self.imageUp.get_size()
in_x = x < point_x < x + w
in_y = y < point_y < y + h
return in_x and in_y
def render(self):# Decide whether to restart the game
global score
w, h = self.imageUp.get_size()
x, y = self.position
if self.isOver() == True:
score = 0
draw_box(0)
init_board()
class Box:
def __init__(self, topleft, text, color):
self.topleft = topleft
self.text = text
self.color = color
def render(self, surface):
x, y = self.topleft
pygame.draw.rect(surface, self.color, (x, y, box_size, box_size), 0)
text_height = 35
font_obj = pygame.font.SysFont("arial", text_height)
text_surface = font_obj.render(self.text, True, (0, 0, 0))
text_rect = text_surface.get_rect()
text_rect.center = (x + 50, y + 50)
surface.blit(text_surface, text_rect)
def load_data():# Read local txt The highest score of this machine in the file
with open(high_score_name, "r") as f:
high = int(f.read())
return high
def draw_box(type):# Draw the game board interface , Use one 4x4 List representation of
global board
if type == 0:
board = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
colors = {# All kinds of different RGB Color mixing , Exactly according to the original 2048 Copy
0: (205, 193, 180),
2: (238, 228, 218),
4: (237, 224, 200),
8: (242, 177, 121),
16: (245, 149, 99),
32: (246, 124, 95),
64: (246, 94, 59),
128: (237, 207, 114),
256: (237, 204, 98),
512: (237, 200, 80),
1024: (237, 197, 63),
2048: (225, 187, 0)
}
x, y = left_of_screen, top_of_screen
size = 425
pygame.draw.rect(screen, (187, 173, 160), (x, y, size, size))
x, y = x + box_gap, y + box_gap
for i in range(4):
for j in range(4):
idx = board[i][j]
if idx == 0:
text = ""
else:
text = str(idx)
if idx > 2048:
idx = 2048
color = colors[idx]
box = Box((x, y), text, color)
box.render(screen)
x += box_size + box_gap
x = left_of_screen + box_gap
y += top_of_screen + box_gap
def set_random_number():# The function of this function is to move the number after each step 0 Randomly generate a 2 or 4
num = []
for i in range(4):
for j in range(4):
if board[i][j] == 0:
num.append((i, j))
m = random.choice(num)
num.remove(m)
value = random.uniform(0, 1)
if value < 0.1:# produce 4 The probability of
value = 4
else:
value = 2
board[m[0]][m[1]] = value
def init_board():# Initialize the chessboard at the beginning of the game : Randomly generate two 2/4
for i in range(2):
set_random_number()
def combinate(L):# The function of this function is to merge the blocks , It is the key and difficult point of this procedure
global score
ans = [0, 0, 0, 0]
num = []
for i in L:
if i != 0:# Put all the numbers in this line on the list num In the middle
num.append(i)
length = len(num)
if length == 4:# There are 4 A digital
if num[0] == num[1]:#case1
ans[0] = num[0] + num[1]
score += ans[0]
if num[2] == num[3]:
ans[1] = num[2] + num[3]
score += ans[1]
else:
ans[1] = num[2]
ans[2] = num[3]
elif num[1] == num[2]:#case2
ans[0] = num[0]
ans[1] = num[1] + num[2]
ans[2] = num[3]
score += ans[1]
elif num[2] == num[3]:#case3
ans[0] = num[0]
ans[1] = num[1]
ans[2] = num[2] + num[3]
score += ans[2]
else:#case4 There are no figures that can be merged
for i in range(length):
ans[i] = num[i]
elif length == 3:# There are 3 A digital
if num[0] == num[1]:#case 1
ans[0] = num[0] + num[1]
ans[1] = num[2]
score += ans[0]
elif num[1] == num[2]:#case 2
ans[0] = num[0]
ans[1] = num[1] + num[2]
score += ans[1]
else:#case 3 There are no figures that can be merged
for i in range(length):
ans[i] = num[i]
elif length == 2:# There are 2 A digital
if num[0] == num[1]:#case 1
ans[0] = num[0] + num[1]
score += ans[0]
else:#case 2 There are no figures that can be merged
for i in range(length):
ans[i] = num[i]
elif length == 1:
ans[0] = num[0]
else:
pass
return ans
def left():# The user presses the left key to move
for i in range(4):
temp = combinate(board[i])
for j in range(4):
board[i][j] = temp[j]
def right():# The user presses the right button to move
for i in range(4):
temp = combinate(board[i][::-1])
for j in range(4):
board[i][3 - j] = temp[j]
def up():# The user presses the up key to move
for i in range(4):
to_comb = []
for j in range(4):
to_comb.append(board[j][i])
temp = combinate(to_comb)
for k in range(4):
board[k][i] = temp[k]
def down():# The user presses the next key to move
for i in range(4):
to_comb = []
for j in range(4):
to_comb.append(board[3 - j][i])
temp = combinate(to_comb)
for k in range(4):
board[3 - k][i] = temp[k]
def write(msg="Winning!!!", color=(255, 255, 0), height=14):# Print fonts on the screen
path = 'C:/Windows/Fonts/simhei.ttf'
myfont = pygame.font.SysFont("simsunnsimsun", height)
mytext = myfont.render(msg, True, color)
mytext = mytext.convert_alpha()
return mytext
def win():# Judge whether the current victory
for i in range(4):
for j in range(4):
if board[i][j] == 2048:# Yes 2048, It must be victory
return True
return False
def is_over():# Determine whether the current failure
for i in range(4):
for j in range(4):
if board[i][j] == 0:# Yes 0, There is also blank space , Certainly not a failure
return False
for i in range(4):
for j in range(3):
if board[i][j] == board[i][j + 1]:# There are the same letters on the left and right , Can also merge , Certainly not a failure
return False
for i in range(3):
for j in range(4):
if board[i][j] == board[i + 1][j]:# There are the same letters above and below , Can also merge , Certainly not a failure
return False
return True# failed
def game_skill():# Introduction to game skills
button_back = Button((left_of_screen + 140, 480), "button_back.jpg", 130, 50)
screen.blit(background, (0, 0))
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if button_back.isOver() == True:
return
pygame.display.update()
rect = pygame.draw.rect(screen, (251, 248, 241), (10, 10, 500, 580))
screen.blit(write("1、 Simply put, try not to go up .", height=30, color=(119, 110, 101)), (30, 165))
screen.blit(write(" Just slide , Try to use three from the bottom left ", height=30, color=(119, 110, 101)), (30, 195))
screen.blit(write(" Key game , Let the big box sink at the bottom as much as possible ", height=30, color=(119, 110, 101)), (30, 225))
screen.blit(write("2、 After the number gets bigger and bigger , Larger numbers should ", height=30, color=(119, 110, 101)), (30, 255))
screen.blit(write(" Lean against this one in turn . Let the numbers in a row order ", height=30, color=(119, 110, 101)), (30, 285))
screen.blit(write(" Next to each other . Don't always rush to clean the desktop .", height=30, color=(119, 110, 101)), (30, 315))
screen.blit(write("3、 Because try not to slide up , So big ", height=30, color=(119, 110, 101)), (30, 345))
screen.blit(write(" The number must be at the bottom . Then don't try to be fast .", height=30, color=(119, 110, 101)), (30, 375))
screen.blit(write("4、 When the game doesn't go on ,NewGame", height=30, color=(119, 110, 101)), (30, 405))
screen.blit(write(" Click start again , Wish you have a good time. .", height=30, color=(119, 110, 101)), (30, 435))
button_back = Button((left_of_screen + 140, 480), "button_back.jpg", 130, 50)
screen.blit(write("2048", height=100, color=(119, 110, 101)),
(left_of_screen + 110, left_of_screen // 2))
def game_introduce():# How to play the game
button_back = Button((left_of_screen + 140, 480), "button_back.jpg", 130, 50)
screen.blit(background, (0, 0))
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if button_back.isOver() == True:
return
pygame.display.update()
rect = pygame.draw.rect(screen, (251, 248, 241), (10, 10, 500, 580))
screen.blit(write(" The rules of the game are simple ", height=30, color=(119, 110, 101)), (135, 165))
screen.blit(write(" You need to control all the squares ", height=30, color=(119, 110, 101)), (135, 195))
screen.blit(write(" Move in the same direction ", height=30, color=(119, 110, 101)), (135, 225))
screen.blit(write(" Two identical number squares ", height=30, color=(119, 110, 101)), (135, 255))
screen.blit(write(" Meet after bumping together ", height=30, color=(119, 110, 101)), (135, 285))
screen.blit(write(" And become their addition ", height=30, color=(119, 110, 101)), (135, 315))
screen.blit(write(" Then a new one will appear ", height=30, color=(119, 110, 101)), (135, 345))
screen.blit(write("2 or 4 When you get it together ", height=30, color=(119, 110, 101)), (135, 375))
screen.blit(write("2048 Game is victory ", height=30, color=(119, 110, 101)), (135, 405))
button_back = Button((left_of_screen + 140, 480), "button_back.jpg", 130, 50)
screen.blit(write("2048", height=100, color=(119, 110, 101)),
(left_of_screen + 110, left_of_screen // 2))
def game_view_page0():# Game welcome interface , Here an animation function is realized : Two rows of different sizes and colors “2048 Little games ” Rotate around the center of the screen
FPS = 5
BLACK = (0, 0, 0)
BROWN = (187, 173, 160)
WHITE = (255, 255, 255)
BGCOLOR = BROWN
titleFont = pygame.font.Font(r'C:\Windows\Fonts\simkai.ttf', 100)
titleSurf1 = titleFont.render('2048 Little games ', True, BLACK)
titleSurf2 = titleFont.render('2048 Little games ', True, WHITE)
degrees1 = 0
degrees2 = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN or event.type == KEYUP:
return
screen.fill(BGCOLOR)
rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
rotatedRect1 = rotatedSurf1.get_rect()
rotatedRect1.center = (screen_width / 2, screen_height / 2 - 50)
screen.blit(rotatedSurf1, rotatedRect1)
rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
rotatedRect2 = rotatedSurf2.get_rect()
rotatedRect2.center = (screen_width / 2, screen_height / 2 - 50)
screen.blit(rotatedSurf2, rotatedRect2)
screen.blit(write(" Click the left mouse button to enter the game ", height=30, color=(255, 255, 255)),
(left_of_screen + 60, left_of_screen // 2 + 450))
pygame.display.update()
FPSCLOCK.tick(10)
degrees1 += 3
degrees2 += 5
def game_start_page():# Game start screen
# Load background image
screen.blit(background, (0, 0))
# Create several customized buttons
button4 = Button((left_of_screen + 110, 150), b4, 200, 80)
button5 = Button((left_of_screen + 110, 270), b5, 200, 80)
button6 = Button((left_of_screen + 110, 390), b6, 200, 80)
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if button4.isOver() == True:# If you press yes button4, Start the game
return
elif button5.isOver() == True:# If you press yes button5, That is, introduction to game playing
game_introduce()
screen.blit(background, (0, 0))
button4 = Button((left_of_screen + 110, 150), b4, 200, 80)
button5 = Button((left_of_screen + 110, 270), b5, 200, 80)
button6 = Button((left_of_screen + 110, 390), b6, 200, 80)
elif button6.isOver() == True:# If you press yes button6, Introduction to game skills
game_skill()
screen.blit(background, (0, 0))
button4 = Button((left_of_screen + 110, 150), b4, 200, 80)
button5 = Button((left_of_screen + 110, 270), b5, 200, 80)
button6 = Button((left_of_screen + 110, 390), b6, 200, 80)
screen.blit(write("2048", height=100, color=(119, 110, 101)),
(left_of_screen + 110, left_of_screen // 2))
pygame.display.update()
def main():
# play_music() Commented out , Playing concerts causes games to get too laggy
global FPSCLOCK, score, high_score, tmpScore, board
flag = False
flag2 = False
FPSCLOCK = pygame.time.Clock()
game_view_page0()# Game welcome interface
game_start_page()# Game main menu interface
b = [[0, 0, 0, 0],#b It is used to record the checkerboard status of each step before the user moves , Can be used to implement “ Go back to the previous step ” function
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
screen.blit(background, (0, 0))
init_board()
newboard = deepcopy(board)
gameover = is_over()
draw_box(1)
button = Button((left_of_screen + 210, left_of_screen // 2 + 5), "button3.jpg", 100, 60)
screen.blit(write("2048", height=60, color=(119, 110, 101)),
(left_of_screen, left_of_screen // 2))
high_score = load_data()
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):# If the user presses ESC, sign out
pygame.quit()
exit()
elif not gameover:# If the current game has not failed ( There are spaces on the chessboard , The digital 0)
if win() == True:# If you win now ( Spell out the numbers 2048)
screen.blit(write("You win!", height=40, color=(119, 110, 101)),# Print on the screen “You win!”
(left_of_screen + 160, screen_height // 2 - 30))
elif event.type == KEYUP and event.key == K_UP:# User presses the up key
tmpScore = score
flag = False
up()
elif event.type == KEYUP and event.key == K_DOWN:# User presses the down key
tmpScore = score
flag = False
down()
elif event.type == KEYUP and event.key == K_LEFT:# User presses the left key
tmpScore = score
flag = False
left()
elif event.type == KEYUP and event.key == K_RIGHT:# User presses the right key
tmpScore = score
flag = False
right()
elif event.type == pygame.MOUSEBUTTONDOWN:# The user clicked the mouse , That is, the user presses the restart button
button.render()# Restart a game
flag = False# Initialize the values
flag2 = True
elif event.type == KEYUP and event.key == K_SPACE:# User presses the space Going back to the previous step
if flag == False:
board = deepcopy(b)
score = tmpScore
flag = True
if newboard != board:
b = deepcopy(newboard)
if flag == False and flag2 == False:
set_random_number()
flag2 = False
newboard = deepcopy(board)
draw_box(1)
gameover = is_over()
else:# Otherwise, it will be judged that the user's game fails
screen.blit(write("Game over!", height=40, color=(119, 110, 101)),# Print failure information
(left_of_screen + 140, screen_height // 2 - 40))
if score > high_score:# If the user's score is higher than the highest score of the machine
screen.blit(write("New record!", height=40, color=(119, 110, 101)),# Prompt the user to refresh the record
(left_of_screen + 140, screen_height // 2 + 10))
high_score = score
with open(high_score_name, "w") as f:
f.write(str(high_score))# Use the new score to cover the original highest score
if event.type == pygame.MOUSEBUTTONDOWN:# The user clicked the mouse , That is, the user presses the restart button
gameover = False
score = 0
tmpScore = 0# Initialize the values
button.render()# Restart a game
flag2 = True
pygame.display.update()
rect1 = pygame.draw.rect(screen, (187, 173, 160),
(left_of_screen + 120, left_of_screen // 2 + 5, 80, 60))
rect2 = pygame.draw.rect(screen, (187, 173, 160),
(left_of_screen + 320, left_of_screen // 2 + 5, 105, 60))
screen.blit(write("score:", height=28, color=(255, 255, 255)),
(left_of_screen + 125, left_of_screen // 2 + 5))
screen.blit(write("best:", height=30, color=(255, 255, 255)),
(left_of_screen + 340, left_of_screen // 2 + 5))
text1 = write(str(score), height=30, color=(255, 255, 255))
text2 = write(str(high_score), height=30, color=(255, 255, 255))
text_rect = text1.get_rect()
text_rect2 = text2.get_rect()
text_rect.center = (left_of_screen + 160, left_of_screen // 2 + 50)
text_rect2.center = (left_of_screen + 370, left_of_screen // 2 + 50)
screen.blit(text1, text_rect)
screen.blit(text2, text_rect2)
if __name__ == "__main__":
main()
Copying source code directly is not possible , Missing local files such as image materials . I put all these things in my GitHub On , Students who need it can download .
Remember to give me a by the way star~OvO
Another little blogger has an article C Push box made of language , Interested students can go to see . By the end C What can language do ? Let's make a suitcase first ~( There are pictures )
That's all, thanks for watching~
边栏推荐
猜你喜欢
随机推荐
Win11 is not compatible with VM -- VMware Workstation solution. On March 31, 2022, the pro test was successfully solved
TFIDF sklearn code call
prism对话服务
Rasa session data store redistrackerstore connection Sentinel
小白能看懂等Tacotron 中文语音合成实践
Day 11 of leetcode question brushing
认识kubenetes的核心组件之一kubelet
Reptile Youdao translation
Nodejs uses Multe to upload files and store them on the server
2021-07-02
Header file ctype H (detailed)
YoloV1~YoloV4
rasa会话数据存储 RedisTrackerStore 连接哨兵
win11不兼容vm--VMware Workstation解决办法。2022年3月31日,亲测成功解决
WordPress Chinese website code download
常用的正则表达式
I2C protocol
Basic use of gzip and PM2 management tools for project launch
Day 4 of leetcode question brushing
C excel net core reading xlsm









