Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 18

2048

PYTHON
GAME
NO.13 Nitiya Triraj
NO.14 Pasinyapa Boon Boonthavornsakul
What is 2048
✘ 2048 คือเกม ปั ด
บวกเลข ทำยังไง
Rule of 2048
✘ เริ่มเกม มีแต่ cell ที่มีค่า 2 เกิดขึน
้ แบบสุ่ม
ก็ได้ให้ได้ 2048 ใน board
✘ user สามารถ เคลื่อนไหว cell ทัง้ หมด
พร้อมๆกันไปได้ 4 ทิศทาง
(up/down/left/right)
✘ กฎการชนและการเกิดใหม่ของ cell
✘ เมื่อมีการเคลื่อนไหวใดๆ 1 ครัง้ จะมี cell
เกิดใหม่เกิดขึน้ แบบสุ่ม ( cell ค่า 2 90%
และ cell ค่า 4 อีก 10%)
✘ เมื่อ user สามารถสร้าง cell ที่มีค่า 2048
ได้ ก็เป็ นอันจบเกมส์ 2
CODE
Write game’s code by python
Should have Python version 3+
PyGame
board
class Board:
def __init__(self):
self.board = [ [0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0] ]
self.score = 0

4

random
startRow = random.choice([x for x in range(3)]) #random btw 0-3
startColumn = random.choice([x for x in range(3)])
self.board[startRow][startColumn] = 2

5
def toString(self):
for i in self.board:
print(i)

6
Movement

7
Movement

8
def createRandCell(self):
complete = False
while not complete:
startRow = random.choice([x for x in
range(3)])
startColumn = random.choice([x for x in
range(3)])
#random ใหม่หากตำแหน่งนัน ้ มีค่าอยู่แล้ว(ไม่
ว่าง)
if self.board[startRow][startColumn] != 0:
continue
self.board[startRow][startColumn] =
random.choice([2,2,2,2,2,2,2,2,2,4]) #10% of
respawning 4
complete = True
9
def isWin(self):
for i in self.board:
if 2048 in i:
return True
return False

10
GUI
11
Big concept
นำ board ที่เป็น 2D list ใน class board ามาใชเ้ ป็นตน

แบบและครอบดว้ ย GUI

12
class Game:
def __init__(self):
pygame.init()
pygame.display.set_caption("2048 Game by NITIYA & PASINYAPA")
self.score = "Score : "
self.board = Board()
self.gameDisplay = pygame.display.set_mode((800,600))
self.font = pygame.font.SysFont("monospace", 28)
self.clock = pygame.time.Clock()
self.over = False
self.start()
pygame.quit()
quit()
13
14
def drawCell(self):
for i in range(len(self.board.board)):
for j in range(len(self.board.board)):
myimage = pygame.image.load("assets/" +
str(self.board.board[i][j]) + ".jpeg")
imageRect = myimage.get_rect()
imageRect.x = j * imageRect.width + CELL_WIDTH
imageRect.y = i * imageRect.height + CELL_HEIGHT
self.gameDisplay.blit(myimage, imageRect)

15
Maps

our office

16
รั บ event keyboard
def checkEvent(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
self.board.down()

if event.key == pygame.K_UP:
self.board.up()

if event.key == pygame.K_LEFT:
self.board.left()

if event.key == pygame.K_RIGHT:
self.board.right()

17
display
def displayResult(self):
font = pygame.font.SysFont("monospace", 40)
pygame.draw.rect(self.gameDisplay, (0, 0, 150), (270, 150, 300, 170))
label = font.render("You Win!!!", 1, (255, 255, 255))
self.gameDisplay.blit(label, (350, 220))

run
Game()

18

You might also like