# Externe Bibliotheken import sys import pygame from pygame.locals import * # Afmetingen van de mainscreen SQUARESIZE = 50 DISPLAYWIDTH = 12 * SQUARESIZE DISPLAYHEIGHT = 14 * SQUARESIZE # Afmetingen van het speelbord COLUMN_COUNT = 8 ROW_COUNT = 8 XMARGIN = int((DISPLAYWIDTH - (COLUMN_COUNT * SQUARESIZE)) / 2) YMARGIN = DISPLAYHEIGHT - XMARGIN - (COLUMN_COUNT * SQUARESIZE) # Loop- en Animatiesnelheid FRAMESPEED = 60 ANIMATIONSPEED = 25 # integer from 1 to 100, higher is faster animation # Standaard kleurenpalet white = (255, 255, 255) red = (255, 0, 0) black = (0, 0, 0) darkgreen = (0, 155, 0) lightgreen = (0, 255, 0) brightblue = (0, 50, 255) darkblue = (0, 0, 155) brown = (174, 94, 0) def main(): # Globale variabelen: kunnen aangeroepen worden in andere functies global DISPLAY, BACKGROUND, BOARDIMG, BOARDIMG_Rect, CLOCK, smalltxt, medtxt, bigtxt, into # Initialisatie van pygame en mainscreen pygame.init() CLOCK = pygame.time.Clock() DISPLAY = pygame.display.set_mode((DISPLAYWIDTH, DISPLAYHEIGHT)) pygame.display.set_caption('Reversi') DISPLAY.fill(white) smalltxt = pygame.font.Font('freesansbold.ttf', 16) medtxt = pygame.font.Font('freesansbold.ttf', 22) bigtxt = pygame.font.Font('freesansbold.ttf', 40) BACKGROUND = pygame.image.load('reversibg.jpg') BACKGROUND = pygame.transform.smoothscale(BACKGROUND, ((DISPLAYWIDTH, DISPLAYHEIGHT))) BACKGROUND_Rect = BACKGROUND.get_rect() DISPLAY.blit(BACKGROUND, BACKGROUND_Rect) BOARDIMG = pygame.image.load('reversi.png') BOARDIMG = pygame.transform.smoothscale(BOARDIMG, (COLUMN_COUNT * SQUARESIZE, ROW_COUNT * SQUARESIZE)) BOARDIMG_Rect = BOARDIMG.get_rect() BOARDIMG_Rect.topleft = (XMARGIN, YMARGIN) global intro intro = True # Start het spel runIntro() pygame.quit() quit() def runIntro(): while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() # Als er weggeklikt wordt, stopt intro # if event.type == MOUSEBUTTONUP: largeText = pygame.font.SysFont("comicsansms",115) text_Surf = bigtxt.render("REVERSI", True, darkblue, darkgreen) textRect = text_Surf.get_rect() textRect.center = ((DISPLAYWIDTH/2),(DISPLAYHEIGHT/4)) DISPLAY.blit(text_Surf, textRect) button("Player VS Player",DISPLAYWIDTH / 3,450,100,50, darkgreen,lightgreen) button("Player VS Computer",DISPLAYWIDTH - DISPLAYWIDTH / 3,450,100,50, darkgreen,lightgreen) button("Start Game",DISPLAYWIDTH / 2,300,100,50, darkgreen,lightgreen, runGame) pygame.display.update() CLOCK.tick(FRAMESPEED) # if game_mode == 'playerVSplayer': # Pick color player1 # Pick name player 1 # Pick color player2 # Pick name player 2 # if game_mode == 'playerVScomputer': # Pick color player1 # Pick name player1 # Pick difficulty def runGame(): global intro intro = False DISPLAY.blit(BOARDIMG, BOARDIMG_Rect) # Maak en teken het speelbord mainBoard = create_board() start_board(mainBoard) drawBoard(mainBoard) # Beginspeler en Speler Referenties turn = 0 player1_tile, player2_tile = 1, 2 game_mode = 'playerVSplayer' # game_mode = 'playerVScomputer' # De Game Loop game = True while game: if game_mode == 'playerVSplayer': if turn % 2 == 0: player = (player1_tile, player2_tile) else: player = (player2_tile, player1_tile) # Controle of er mogelijke zetten zijn if getValidMoves(mainBoard, player[0]) == []: break # Loop totdat er een legale zet wordt gemaakt door speler 1 board_xy = None while board_xy == None: # Controleer alle events die plaatsvinden for event in pygame.event.get(): # "Quit Event" behandeling if event.type == pygame.QUIT: pygame.quit() quit() # "Click Event" behandeling if event.type == MOUSEBUTTONUP: # Opslaan van "Click Event" coordinaten pixel_x, pixel_y = event.pos # "Click Event" buiten het speelbord # "Click Event" op het speelbord: coordinaten omzetten in axis van speelbord board_xy = PixelToBoard(pixel_x, pixel_y) # Reset wanneer "Click Event" ongeldige zet probeert if board_xy != None and not ValidMove(mainBoard, player[0], board_xy[0], board_xy[1]): board_xy = None # DRAW INFO # DRAW BUTTONS # Mainscreen updaten: FRAMESPEED keer / seconde drawBoard(mainBoard) drawInfo(mainBoard, turn) CLOCK.tick(FRAMESPEED) pygame.display.update() # Teken zet op het Speelbord en wissel van Speler draw_move(mainBoard, player[0], board_xy[0], board_xy[1], True) if getValidMoves(mainBoard, player[1]) != []: turn += 1 if game_mode == 'playerVScomputer': pass # ENDGAME if getScore(mainBoard)[1] > getScore(mainBoard)[2]: string = "Player 1 wins!" else: string = "Player 2 Wins!" string += " Final score: Player 1: {} Tiles. Player 2: {} Tiles.".format(getScore(mainBoard)[1], getScore(mainBoard)[2]) print(string) def create_board(): # Maak Speelbord board = [] for i in range(COLUMN_COUNT): board.append([0] * ROW_COUNT) return board def start_board(board): # Reset Speelbord (startpositie) for x in range(COLUMN_COUNT): for y in range(ROW_COUNT): board[x][y] = 0 board[3][3] = 1 board[3][4] = 2 board[4][3] = 2 board[4][4] = 1 def drawBoard(board): # Teken de Tokens op het Speelbord for x in range(COLUMN_COUNT): for y in range(ROW_COUNT): middlex, middley = BoardToPixel(x, y) if board[x][y] == 1 or board[x][y] == 2: if board[x][y] == 1: tileColor = white else: tileColor = black pygame.draw.circle(DISPLAY, tileColor, (middlex, middley), int(SQUARESIZE / 2) - 4) def drawInfo(board, turn): if turn % 2 == 0: player = 'white' else: player = 'black' score = getScore(board) score_Surf = bigtxt.render("Player 1 Score: {} Player 2 Score: {}".format(score[1], score[2]), True, darkblue, darkgreen) scoreRect = score_Surf.get_rect() scoreRect.center = (DISPLAYWIDTH / 2, YMARGIN / 2) DISPLAY.blit(score_Surf, scoreRect) turn_Surf = bigtxt.render("Turn: " + str(turn) + " ({})".format(player), True, black, darkgreen) turnRect = turn_Surf.get_rect() turnRect.center = (DISPLAYWIDTH / 2, DISPLAYHEIGHT - (DISPLAYHEIGHT - YMARGIN - SQUARESIZE * ROW_COUNT) / 2) DISPLAY.blit(turn_Surf, turnRect) def BoardToPixel(x, y): # Zet Speelbord Coordinaten om in Pixels van Mainscreen return XMARGIN + x * SQUARESIZE + int(SQUARESIZE / 2), YMARGIN + y * SQUARESIZE + int(SQUARESIZE / 2) def PixelToBoard(pixel_x, pixel_y): # Zet Pixels van Mainscreen om in Coordinaten van Speelbord for x in range(COLUMN_COUNT): for y in range(ROW_COUNT): if pixel_x > x * SQUARESIZE + XMARGIN and \ pixel_x < (x + 1) * SQUARESIZE + XMARGIN and \ pixel_y > y * SQUARESIZE + YMARGIN and \ pixel_y < (y + 1) * SQUARESIZE + YMARGIN: return (x, y) return None def isOnBoard(x, y): # Controleert of de Coordinaten op het bord liggen return COLUMN_COUNT > x >= 0 and ROW_COUNT > y >= 0 def ValidMove(board, playerTile, column, row): # Controleert of Zet legaal is en toont welke Tokens geflipt moeten worden # Als er geen tokens geflipt moeten worden, is zet niet legaal: return Flase # Als de coordinaten niet op het bord liggen of het vakje is niet leeg, is zet niet legaal if not isOnBoard(row, column) or board[column][row] != 0: return False # Vult slechts ter controle het gekozen vakje met een Token board[column][row] = playerTile if playerTile == 1: other = 2 else: other = 1 # Controleert welke Tokens omgedraaid zouden moeten worden tilesToFlip = [] # Controle in alle 8 richtingen for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]: x, y = column, row x += xdirection y += ydirection # Doorgaan als vakje naast nieuwe Token van Tegenstander is if isOnBoard(x, y) and board[x][y] == other: x += xdirection y += ydirection if not isOnBoard(x, y): continue while board[x][y] == other: x += xdirection y += ydirection if not isOnBoard(x, y): break # Break uit While Loop, doorgaan met For Loop if not isOnBoard(x, y): continue # Als eigen kleur wordt bereikt in een van de richtingen moeten er Tokens geflipt worden # Volg zelfde lijn in tegengestelde richting en Append alle vakjes naar tilesToFlip if board[x][y] == playerTile: while True: x -= xdirection y -= ydirection if x == column and y == row: break tilesToFlip.append([x, y]) # Originele vakje wordt weer leeg gemaakt om dubbele handeling te voorkomen board[column][row] = 0 # Als er geen Tokens geflipt moeten worden is de zet niet legaal: return False if tilesToFlip == []: return False # Return Lijst met vakjes die geflipt moeten worden return tilesToFlip def getValidMoves(board, playerTile): # Return Lijst met alle legale Zetten # Maak lege Lijst validMoves = [] # Append Lijst met legale Zetten for x in range(COLUMN_COUNT): for y in range(ROW_COUNT): if ValidMove(board, playerTile, x, y) != False: validMoves.append((x, y)) return validMoves def draw_move(board, playerTile, column, row, realMove=False): # Tekent de zetten, indien legaal tilesToFlip = ValidMove(board, playerTile, column, row) if tilesToFlip == False: return False board[column][row] = playerTile # Flip alle Tokens tussen nieuwe Token en eigen Token for x, y in tilesToFlip: board[x][y] = playerTile return True def getScore(board): tiles1 = 0 tiles2 = 0 for x in range(COLUMN_COUNT): for y in range(ROW_COUNT): if board[x][y] == 1: tiles1 += 1 if board[x][y] == 2: tiles2 += 1 return {1: tiles1, 2: tiles2} def button(msg,x,y,w,h,ic,ac,action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() print(click) if x+w > mouse[0] > x and y+h > mouse[1] > y: pygame.draw.rect(DISPLAY, ac,(x,y,w,h)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(DISPLAY, ic,(x,y,w,h)) smalltext = pygame.font.SysFont("comicsansms",20) text_Surf = smalltext.render(msg, True, black) textRect = text_Surf.get_rect() textRect.center = ( (x+(w/2)), (y+(h/2)) ) DISPLAY.blit(text_Surf, textRect) # def button(msg,x,y,w,h,ic,ac,action=None): # mouse = pygame.mouse.get_pos() # click = pygame.mouse.get_pressed() # print(mouse[0]) # print(mouse[1]) # print (x-0,5 * w), (x + 0.5 * w), (y - 0.5 * h), (y + 0.5 * h) # if (x - 0.5 * w) > mouse[0] > (x + 0.5 * w) and (y - 0.5 * h) > mouse[1] > (y + 0.5 * h): # box = pygame.image.load('blue_button.jpg') # box = pygame.transform.smoothscale(box, (w, h)) # box_Rect = box.get_rect() # box_Rect.center = (x, y) # if click[0] == 1 and action!= None: # action() # else: # box = pygame.image.load('blue_button.jpg') # box = pygame.transform.smoothscale(box, (w, h)) # box_Rect = box.get_rect() # box_Rect.center = (x, y) # smalltext = pygame.font.SysFont("comicsansms",20) # text_Surf = smalltext.render(msg, True, black) # textRect = text_Surf.get_rect() # textRect.center = ( x, y )#( (x+(w/2)), (y+(h/2)) ) # DISPLAY.blit(box, box_Rect) # DISPLAY.blit(text_Surf, textRect) main() pygame.quit() quit()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question