20213310 wuzenghui's Experiment 4 of python program design python comprehensive practice

Course: Python Programming

Class: 2133
20213310 wuzenghui's Experiment 4 of python program design python comprehensive practice
Name: wuzenghui

Student No.: 20213310

Experiment teacher: Mr. wangzhiqiang

Test date: May 22, 2022

Compulsory / elective course: Public Elective Course

1. experiment content
   Python comprehensive application: crawler, data processing, visualization, machine learning, neural network, game, network security, etc. Write a dodge game and run it using Huawei cloud services (either ECS or mindspire).

  1. Experimental process and results
    preparation in advance
    After thinking for a long time, I found that the content of python's big assignment was very difficult, so I chose a game that I often contact and may be easy to use for programming, so I finally chose to write a dodge game.

Experimental process
At the beginning, I had great difficulties. I had been looking for teaching videos and related blog materials on the Internet. I also asked my classmates to help me learn how to run Huawei cloud services.

Game programming code

import sys
import random
from math import *

pygame.init()#Initialization settings

width = 400
height = 500
display = pygame.display.set_mode((width, height))#Initializes the window for display and sets the window size
pygame.display.set_caption("Simple Dodge Ball Game")#Set window title
clock = pygame.time.Clock()#Create a Clock object to operate the time

background = (255, 255, 255)#Background color is white
playerColor = (50, 50, 50)#Select the color corresponding to (50, 50, 50)

red = (203, 67, 53)#Color setting
yellow = (241, 196, 15)
blue = (46, 134, 193)
green = (34, 153, 84)
purple = (136, 78, 160)
orange = (214, 137, 16)

colors = [red, yellow, blue, green, purple, orange]#Create colors list

score = 0 #Initial score is 0


class Ball: #class: class
    def __init__(self, radius, speed):
       #Initial value setting, no practical significance
        self.x = 0
        self.y = 0
        self.r = radius
        self.color = 0
        self.speed = speed
        self.angle = 0

    def createBall(self):
        self.x = width / 2 - self.r #x coordinate setting
        self.y = height / 2 - self.r #y coordinate setting
        self.color = random.choice(colors) #Randomly select colors from the created colors list
        self.angle = random.randint(-180, 180) #Random generation of integers in the range of [-180180]

    def move(self):
        #Every time the ball moves, it has a new coordinate
        self.x += self.speed * cos(radians(self.angle))
        self.y += self.speed * sin(radians(self.angle))
       #Judge whether the ball hits the wall, and reverse the movement when it hits the wall
        if self.x < self.r or self.x + self.r > width:
            self.angle = 180 - self.angle
        if self.y < self.r or self.y + self.r > height:
            self.angle *= -1

    def draw(self):
        pygame.draw.ellipse(display, self.color, (self.x - self.r, self.y - self.r, self.r * 2, self.r * 2))#Draw a rectangle and limit the required circle to the set rectangle (understood as drawing a circle)

    def collision(self, radius):
        pos = pygame.mouse.get_pos()#Get the position of the mouse cursor

        dist = ((pos[0] - self.x) ** 2 + (pos[1] - self.y) ** 2) ** 0.5 #Calculate distance by formula

        if dist <= self.r + radius:#This represents a collision (the distance is less than or equal to the sum of the radii of the two objects), and the game ends after the collision
            gameOver()


class Target: #Set another class
    def __init__(self): #Initialization settings
        self.x = 0
        self.y = 0
        self.w = 20
        self.h = self.w

    def generateNewCoord(self):
        self.x = random.randint(self.w, width - self.w)#Define the (x,y) of the function
        self.y = random.randint(self.h, height - self.h)

    def draw(self):
        color = random.choice(colors)#Random color selection

        pygame.draw.rect(display, color, (self.x, self.y, self.w, self.h)) #Draw square


def gameOver():
    loop = True #Judge whether the cycle is still in progress

    font = pygame.font.SysFont("Agency FB", 100) #Font settings
    text = font.render("Game Over!", True, (0, 0, 0)) #Pop up "Game Over" in black font

    while loop:
        for event in pygame.event.get():
            # Get game window status
            # Image movement KEYDOWN keyboard press event
            # Corresponding keys through key attribute
            if event.type == pygame.QUIT:
                close()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    close()
                if event.key == pygame.K_r:
                    gameLoop()

        display.fill(background)#Background fill

        display.blit(text, (20, height / 2 - 100))#Position setting
        displayScore() #Show scores

        pygame.display.update() #Update display interface
        clock.tick() #timing


def checkCollision(target, d, objTarget): #Check for collisions
    pos = pygame.mouse.get_pos() #Mouse position
    dist = ((pos[0] - target[0] - objTarget.w) ** 2 + (pos[1] - target[1] - objTarget.h) ** 2) ** 0.5 #Calculate distance

    if dist <= d + objTarget.w: #When the distance is less than or equal to the sum of their radii, the collision is considered to have occurred
        return True
    return False


def drawPlayerPointer(pos, r):
    pygame.draw.ellipse(display, playerColor, (pos[0] - r, pos[1] - r, 2 * r, 2 * r))#Draw a circle


def close():
    pygame.quit()#Game stop
    sys.exit() #quit


def displayScore():
    font = pygame.font.SysFont("Arial", 30)#Set font
    scoreText = font.render("Score: " + str(score), True, (0, 0, 0)) #scoring
    display.blit(scoreText, (10, 10)) #Show score


def gameLoop():
    global score #Set score as global variable
    score = 0 #Initial value

    loop = True #Cycle in progress

    pRadius = 10 #Set radius

    balls = [] #List setting

    for i in range(1):
        newBall = Ball(pRadius + 2, 5) #Set the radius and speed of the new ball
        newBall.createBall() #Generate new ball
        balls.append(newBall) #Each time a new ball is generated, it is added to the balls list

    target = Target() #Run the previously defined function. The previous def is just the definition. Now run it
    target.generateNewCoord()

    while loop:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                close()
                #Image movement KEYDOWN keyboard press event
                #Corresponding keys through key attribute
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    close()
                if event.key == pygame.K_r:
                    gameLoop()

        display.fill(background) #Background fill

        for i in range(len(balls)): #All the balls make them move
            balls[i].move()

        for i in range(len(balls)):
            balls[i].draw() #Draw these balls

        for i in range(len(balls)):
            balls[i].collision(pRadius) #Detect collisions

        playerPos = pygame.mouse.get_pos()
        drawPlayerPointer((playerPos[0], playerPos[1]), pRadius)

        collide = checkCollision((target.x, target.y), pRadius, target)

        if collide:
            score += 1 #When the ball collides with the square piece, score plus one point
            target.generateNewCoord()
        elif score == 2 and len(balls) == 1: #Two collisions but only one ball in the interface
            newBall = Ball(pRadius + 2, 5) #Generate new ball
            newBall.createBall()#The following three lines are to run the previous def function
            balls.append(newBall)
            target.generateNewCoord()
        elif score == 5 and len(balls) == 2: #Five times but there are only two balls in the interface
            newBall = Ball(pRadius + 2, 6)  #A new ball is produced and the ball moves faster
            newBall.createBall()
            balls.append(newBall)
            target.generateNewCoord()
        elif score == 10 and len(balls) == 3: #It is similar to the above, which means that when the collision occurs ten times, a new ball should be added to the interface
            newBall = Ball(pRadius + 2, 7)
            newBall.createBall()
            balls.append(newBall)
            target.generateNewCoord()
        elif score == 15 and len(balls) == 4:
            newBall = Ball(pRadius + 2, 8)
            newBall.createBall()
            balls.append(newBall)
            target.generateNewCoord()
        elif score == 20 and len(balls) == 5:
            newBall = Ball(pRadius + 2, 9)
            newBall.createBall()
            balls.append(newBall)
            target.generateNewCoord()

        target.draw() #draw
        displayScore() #Show scores

        pygame.display.update() #Interface update
        clock.tick(60) #timing


gameLoop() #Execute the game



3. screenshot of operation results
vscode run

Huawei ECS running

4. problems encountered in the experiment and Solutions
Problem 1: the online reference code to your own vscode cannot run
Solution 1: the address and path of the running file should be consistent with that in the reference code.
Problem 2: it is difficult to write code. There are many sentences that you don't understand, and errors are often reported
Solution 2: keep searching for information and asking students;

5. experimental experience and classroom summary
As a whole, this big assignment is very difficult. Most of them rely on online search for relevant materials and teaching videos to write code step by step and then make relevant comments. If you want to write a complete code and understand it autonomously, you may need to continue your efforts. Volume 2 of freshman's year is a challenge as well as an exercise to be exposed to the two new courses of python and c language at the same time this semester. I know more about learning programming. I need to be patient and persistent. I need to learn more by myself in combination with online materials. I also need to often play code to exercise my hand feeling. In this way, I can learn more smoothly and go to a higher level.
Finally, talk about the class summary. Mr. wangzhiqiang is really gentle. In every class, he takes us to type code line by line instead of reading ppt roughly, and pays more attention to practice. However, as an elective course, many students do not have a deep understanding of Python. Most of them are beginners who are curious about and love python. Therefore, it is suggested to slow down slightly, talk about some basic programming sentences, or send the code typed in class to wechat group for review. I was very happy to take Python as an elective course this semester. I learned some real things. The sense of achievement in facing difficulties is irreplaceable. I never thought I would have the perseverance to understand and write a small game, but this big assignment was done. Thanks to python, thanks to Mr. wangzhiqiang, I hope the teacher will be better and better, and everything goes well!

Posted by jcubie on Mon, 30 May 2022 21:34:32 +0530