Use graphics. py to implement 2048 games

Source: Internet
Author: User
This article will share with you the source code for implementing 2048 mini games using Python. it is not implemented using QT. we recommend it to you. if you need it, refer to it. 1. during the Chinese New Year, I downloaded 2048 for a few days on my mobile phone. I decided to use py to write it. at the beginning, I wanted to use QT to implement it. I found that the dependency was a little high. We can see that graphics. py is a tkinter-based package, and uses model. py (2048 logical part) encapsulated by a friend of CSDN)
2. you may not be able to write poorly because it is a matter of practice.

First look at the demo image

Attached source code:

2048 main process

The code is as follows:


#-*-Coding: UTF-8 -*-
# Python3.3.5
From graphics import *
From tkinter. messagebox import askquestion
From tkinter. messagebox import showinfo
Import time, random, model, configparser
Import GUI_2048 as g
Class Application ():
'''
Initialize the application
'''
Def _ init _ (self ):
Self. matrix = model. init ()
Self. win = g. init ()
Self. create_r_2048 (self. win)
Self. show_matrix (self. matrix)
Self. win. master. bind (" ", Self. bind_key)
While 1:
Update ()
'''
Create 16 squares, best scores, and current scores on the grid
'''
Def create_r_2048 (self, win ):
P = Point (1, 10,190)
N = 4
Self. rt = [0 for row in range (n * n)]
For I in range (n ):
For a in range (n ):
_ P = Point (p. x + 60 * I, p. y + 60 *)
Self. rt [I + 4 * a] = g. rectangle_2048 (win, _ p)
# Best Score
Self. zjcj = g. _ text (win, Point (135, 60 + 30), Point (135 + 115, 60 + 30 + 30), self. getMaxScore ())
# Current score
Self. dqjf = g. _ text (win, Point (135,120 + 30), Point (135 + 115,120 + 30 + 30), '0 ')
'''
Get the best score from the configuration file
'''
Def getMaxScore (self ):
Config = configparser. ConfigParser ()
Config. read ('config. ini ')
MaxScore = config. get ("Score", "maxScore ")
Return maxScore
'''
Write the best score to the configuration file
'''
Def setMaxScore (self, score ):
Config = configparser. ConfigParser ()
Config. optionxform = str
Config. read ('config. ini ')
Config. set ("Score", "maxScore", str (score ))
Config. write (open ("config. ini", "w "))
'''
Initialize the data and interface and call it after the game ends.
'''
Def my_init (self ):
MaxScore = self. getMaxScore ()
If int (maxScore) <model. getScore ():
Self. setMaxScore (model. getScore ())
Self. zjcj. setText (model. getScore ())
Matrix = model. init ()
Self. dqjf. setText (model. getScore ())
Return matrix
'''
Bind keyboard event capture to top, bottom, left, and Q keys
'''
Def bind_key (self, event ):
'''
Key event
'''
If model. is_over (self. matrix ):
If askquestion ("game over", "game over! \ NDo you want to init it? ") = 'Yes ':
Self. matrix = self. my_init ()
Self. show_matrix (self. matrix)
Return
Else:
Self. win. close ()
Else:
If event. keysym. lower () = "q ":
Self. win. close ()
Elif event. keysym = "Left ":
Self. matrix = model. move_left (self. matrix)
Elif event. keysym = "Right ":
Self. matrix = model. move_right (self. matrix)
Elif event. keysym = "Up ":
Self. matrix = model. move_up (self. matrix)
Elif event. keysym = "Down ":
Self. matrix = model. move_down (self. matrix)
If event. keysym in ["q", "Left", "Right", "Up", "Down"]:
Try:
Self. matrix = model. insert (self. matrix)
Self. dqjf. setText (model. getScore ())
Self. show_matrix (self. matrix)
Except t:
Pass
If model. is_win (self. matrix ):
If askquestion ("WIN", "You win the game! \ NDo you want to init it? ") = 'Yes ':
Self. matrix = self. my_init ()
Self. show_matrix (self. matrix)
Return
Else:
Self. win. close ()
'''
Obtain the result data from a two-dimensional array and display it in a 16-square box.
'''
Def show_matrix (self, matrix ):
For I in range (16 ):
Num = matrix [I // 4] [I % 4]
Print (num)
If num = 0:
Num =''
Self. rectangle_2048 (I, num)
'''
Change the color and number of 16 squares
'''
Def rectangle_2048 (self, I, num ):
C = color_rgb (200,190,180)
If num = 2:
C = color_rgb (240,230,220)
Elif num = 4:
C = color_rgb (240,220,200)
Elif num = 8:
C = color_rgb (240,180,120)
Elif num = 16:
C = color_rgb (240,140, 90)
Elif num = 32:
C = color_rgb (240,120, 90)
Elif num = 64:
C = color_rgb (240, 90, 60)
Elif num = 128:
C = color_rgb (240, 90, 50)
Elif num = 256:
C = color_rgb (240,200, 70)
Elif num = 512:
C = color_rgb (240,200, 70)
Elif num = 1024:
C = color_rgb (0,130, 0)
Elif num = 2048:
C = color_rgb (0,130, 0)
'''
Set color and number in cycles
'''
Self. rt [I] [0]. setFill (c)
Self. rt [I] [1]. setText (num)
# Main
Application ()


2048gui

The code is as follows:


#-*-Coding: UTF-8 -*-
# Python3.3.5
From graphics import *
# Initialize and build the 2048 interface
Def init ():
Win = GraphWin ("2048", 260,450)
Win. master. geometry ('+ 400 + 150') # screen position
C = color_rgb (206,194,180)
Win. setBackground (c)
Hint (win)
_ Title (win)
_ Grid (win)
MaxScore (win)
CurScore (win)
Return win
#2048 square meters
Def rectangle_2048 (win, p1 = Point (10, 10), txt = '', c = color_rgb (206,194,180 )):
P2 = Point (p1.x + 60, p1.y + 60)
R = _ rectangle (win, p1, p2, c)
T = _ text (win, p1, p2, txt)
Return r, t
# Listing
Def hint (win, p1 = Point (10, 10 )):
P2 = Point (p1.x + 240, p1.y + 40)
C = color_rgb (187,173,164)
_ Rectangle (win, p1, p2, c)
T = _ text (win, p1, p2, 'Hero challenge 2048 ~ ')
T. setTextColor (color_rgb (238,231,221 ))
Return t
# Title logo
Def _ title (win, p1 = Point (10, 60 )):
P2 = Point (p1.x + 120, p1.y + 120)
C = color_rgb (228,184, 0)
_ Rectangle (win, p1, p2, c)
T = Text (Point (p2.x + p1.x)/2, (p2.y + p1.y)/2), '123 ')
T. setSize (35)
T. setStyle ('bold ')
T. setTextColor ('white ')
T. draw (win)
# Draw a square
Def _ rectangle (win, p1, p2, c ):
R = Rectangle (p1, p2)
R. setFill (c)
R. setOutline (color_rgb (198,186,174 ))
R. draw (win)
Return r
# Write text
Def _ text (win, p1, p2, txt ):
T = Text (Point (p2.x + p1.x)/2, (p2.y + p1.y)/2), txt)
T. draw (win)
Return t
# Grid
Def _ grid (win, p1 = Point (10,190 )):
# Above
P_u_1 = Point (p1.x + 60, p1.y)
P_u_2 = Point (p1.x + 120, p1.y)
P_u_3 = Point (p1.x + 180, p1.y)
P_u_4 = Point (p1.x + 240, p1.y)
# Left side
P_l_1 = Point (p1.x, p1.y + 60)
P_l_2 = Point (p1.x, p1.y + 120)
P_l_3 = Point (p1.x, p1.y + 180)
P_l_4 = Point (p1.x, p1.y + 240)
# Right side
P_r_1 = Point (p1.x + 240, p1.y + 60)
P_r_2 = Point (p1.x + 240, p1.y + 120)
P_r_3 = Point (p1.x + 240, p1.y + 180)
P_r_4 = Point (p1.x + 240, p1.y + 240)
# Below
P_d_1 = Point (p1.x + 60, p1.y + 240)
P_d_2 = Point (p1.x + 120, p1.y + 240)
P_d_3 = Point (p1.x + 180, p1.y + 240)
P_d_4 = Point (p1.x + 240, p1.y + 240)
C = color_rgb (198,186,174)
# Draw a horizontal line
L_W_1 = Line (p1, p_u_4)
L_W_2 = Line (p_l_1, p_r_1)
L_W_3 = Line (p_l_2, p_r_2)
L_W_4 = Line (p_l_3, p_r_3)
L_W_5 = Line (p_l_4, p_r_4)
L_W_1.setFill (c)
L_W_2.setFill (c)
Rochelle w_3.setfill (c)
L_W_4.setFill (c)
L_W_5.setFill (c)
L_W_1.draw (win)
Rochelle w_2.draw (win)
Rochelle w_3.draw (win)
L_W_4.draw (win)
Rochelle w_5.draw (win)
# Draw a vertical line
L_H_1 = Line (p1, p_l_4)
L_h2 = Line (p_u_1, p_d_1)
L_H_3 = Line (p_u_2, p_d_2)
L_H_4 = Line (p_u_3, p_d_3)
L_H_5 = Line (p_u_4, p_d_4)
L_H_1.setFill (c)
L_H_2.setFill (c)
L_H_3.setFill (c)
L_H_4.setFill (c)
L_H_5.setFill (c)
L_H_1.draw (win)
L_H_2.draw (win)
L_H_3.draw (win)
L_H_4.draw (win)
L_H_5.draw (win)
# Best Score
Def maxScore (win, p1 = Point (135, 60 )):
P2 = Point (p1.x + 115, p1.y + 30)
C = color_rgb (187,173,164)
_ Rectangle (win, p1, p2, c)
_ Text (win, p1, p2, 'Best score :')
# Current score
Def curScore (win, p1 = Point (135,120 )):
P2 = Point (p1.x + 115, p1.y + 30)
C = color_rgb (187,173,164)
_ Rectangle (win, p1, p2, c)
_ Text (win, p1, p2, 'Current score :')


The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.