How to draw cover on each tile in memory in pygame

2024/11/16 19:48:01

I am a beginner in pygame and I am not a English native speaker.

My assignment is coding a game called 'Memory'. This game contains 8 pairs pictures and an cover exists on each pictures. This week, our assignment is draw covers and if you click an cover, this cover will disappear. However, although I draw pictures successfully. I still cannot draw covers properly. Actually, I don't know the approaches that to draw an cover and to click an cover and make it disappear. I searched a lot however, maybe because I am not a native speaker, I cannot really understand how it works. Therefore, I hope someone could help me here. I will provide my code and pictures below. Thanks everyone!

# This is version 1 for 'Memory'.
# This version contains complete tile grid, but not the score. 
# All 8 pairs of two tiles should be exposed when the game starts. 
# Each time the game is played, the tiles must be in random locations in the grid. 
# Player actions must be ignored.import pygame, sys, time, random 
from pygame.locals import *
pygame.init()# User-defined Classclass Tile:bgColor=pygame.Color('black')BorderWidth= 3def __init__(self, x, y, image, surface):self.x = xself.y = yself.surface = surfaceself.image= imagedef DrawTile(self):self.surface.blit( self.image , (self.x, self.y))class Memory:boardWidthSize=4boardHeightSize=4 def __init__(self, surface):self.surface = surfaceself.board = []self.cover = []self.board2= []def createImages(self):#load images from file  self.cover=[]self.imageNames = ['image1.bmp','image2.bmp','image3.bmp','image4.bmp','image5.bmp','image6.bmp','image7.bmp','image8.bmp','image1.bmp','image2.bmp','image3.bmp','image4.bmp','image5.bmp','image6.bmp','image7.bmp','image8.bmp']self.images=[]for name in self.imageNames :pic = pygame.image.load(name)self.images.append(pic) random.shuffle(self.images)self.cover.append(pygame.image.load('image0.bmp'))def createTile(self):board =[]board2=[]#loop through the loaded images and create tile objectsfor rowIndex in range(0,Memory.boardWidthSize):row = []row2=[]for columnIndex in range(0,Memory.boardHeightSize):width = 100x = columnIndex*widthheight = 100y = rowIndex*heighttile = Tile(x, y, self.images[rowIndex*4+columnIndex], self.surface)cover= Tile(x, y, self.cover, self.surface)row.append(tile)row2.append(cover)self.board.append(row)self.board2.append(row2)def GetScore(self):position=(400,0)FontSize=50FontColor=pygame.Color('White')String='Score : 'font=pygame.font.SysFont(None, FontSize, True)surface1=font.render(str(pygame.time.get_ticks()/1000), True, FontColor,0)self.surface.blit(surface1,position)    def draw(self):for row in self.board:for tile in row:tile.DrawTile()def update(self):if False:return Trueelse:self.createTile()return Falsedef main():surfaceSize = (500, 400) windowTitle = 'Memory'# No frame delay since no moving objectsgameOver = False# Create the windowsurface = pygame.display.set_mode(surfaceSize, 0, 0)pygame.display.set_caption(windowTitle)memory = Memory(surface)memory.createImages()memory.createTile()pygame.display.update()while True:for event in pygame.event.get():if event.type == QUIT:pygame.quit()sys.exit()memory.draw()memory.GetScore()gameOver = memory.update()pygame.display.update()main()

I upload these pictures in my Google Drive:

https://drive.google.com/folderview?id=0Bx-bEVazt-TWUnRSZlJVRmhfQm8&usp=sharing

Answer

Example with drawing cover and handle click (and hide card after 2000ms)

#!/usr/bin/env python
# -*- coding: utf-8 -*-import pygameclass Tile:def __init__(self, x, y, image, cover):self.image = imageself.cover = coverself.rect = pygame.Rect(x, y, 60, 60)self.covered = Trueself.time_to_cover = Nonedef draw(self, screen):# draw cover or imageif self.covered:screen.blit(self.cover, self.rect)else:screen.blit(self.image, self.rect)def update(self):# hide card (after 2000ms)if not self.covered and pygame.time.get_ticks() >= self.time_to_cover:self.covered = Truedef handle_event(self, event):# check left button clickif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:# check position if self.rect.collidepoint(event.pos):self.covered = not self.coveredif not self.covered:# if uncovered then set +2000ms to coverself.time_to_cover = pygame.time.get_ticks() + 2000#----------------------------------------------------------------------# initpygame.init()screen = pygame.display.set_mode((320,320))# create imagesimg = pygame.surface.Surface((60, 60))
img.fill((255,0,0))cov = pygame.surface.Surface((60, 60))
cov.fill((0,255,0))# create tilestiles = []
for y in range(5):for x in range(5):tiles.append( Tile(x*65, y*65, img, cov) )# mainloopclock = pygame.time.Clock()
running = Truewhile running:# eventsfor event in pygame.event.get():if event.type == pygame.QUIT:running = Falsefor x in tiles:x.handle_event(event)# updatesfor x in tiles:x.update()# drawsfor x in tiles:x.draw(screen)pygame.display.flip()# clockclock.tick(25)pygame.quit()   
https://en.xdnf.cn/q/119158.html

Related Q&A

Compare 2 Excel files and output an Excel file with differences

Assume for simplicity that the data files look like this, sorted on ID:ID | Data1 | Data2 | Data3 | Data4 199 | Tim | 55 | work | $55 345 | Joe | 45 | work | $34 356 | Sam |…

Problem to show data dynamically table in python flask

I want to show a table in the html using python flask framework. I have two array. One for column heading and another for data record. The length of the column heading and data record are dynamic. I ca…

RuntimeError: generator raised StopIteration

I am in a course and try to find my problem. I cant understand why if I enter something other than 9 digits, the if should raise the StopIteration and then I want it to go to except and print it out. W…

split list elements into sub-elements in pandas dataframe

I have a dataframe as:-Filtered_data[defence possessed russia china,factors driving china modernise] [force bolster pentagon,strike capabilities pentagon congress detailing china] [missiles warheads, d…

Image does not display on Pyqt [duplicate]

This question already has an answer here:Why Icon and images are not shown when I execute Python QT5 code?(1 answer)Closed 2 years ago.I am using Pyqt5, python3.9, and windows 11. I am trying to add a…

Expand the following dictionary into following list

how to generate the following list from the following dictionary d = {2: 4, 3: 1, 5: 3}f = [2**1,2**2, 2**3, 2**4, 3**1, 5**1, 5**2, 5**3, 2**1 * 3, 2**2 * 3, 2**3 * 3, 2**4 * 3, 5**1 * 3, 5**2 * 3, 5*…

how can I improve the accuracy rate of the below trained model using CNN

I have trained a model using python detect the colors of the gemstone and have built a CNN.Herewith Iam attaching the code of mine.(Referred https://www.kaggle.com) import os import matplotlib.pyplot a…

Classes and methods, with lists in Python

I have two classes, called "Pussa" and "Cat". The Pussa has an int atribute idPussa, and the Cat class has two atributes, a list of "Pussa" and an int catNum. Every class …

polars dataframe TypeError: must be real number, not str

so bascially i changed panda.frame to polars.frame for better speed in yolov5 but when i run the code, it works fine till some point (i dont exactly know when error occurs) and it gives me TypeError: m…

Get a string in Shell/Python using sys.argv

Im beginning with bash and Im executing a script :$ ./readtext.sh ./InputFiles/applications.txt Here is my readtext.sh code :#!/bin/bash filename="$1" counter=1 while IFS=: true; doline=read …