python&pygame Snake source code

caidan_youxi.py

import sys

import pygame
from PyQt5.QtWidgets import QApplication, QMainWindow

import login

if __name__ == '__main__':
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load('C:/Users/ShiWe/Desktop/Computer Software Technology Internship/tanchishe/bgm.mp3') # Load songs
    pygame.mixer.music.play() # Play
    app = QApplication(sys.argv)
    win = QMainWindow()
    loginUi = login.Ui_MainWindow()
    loginUi.setupUi(win)
    win.show()
    sys.exit(app.exec_())

youxi.py

f = open("speed.txt", mode='r')
speed = f.read()
f.close()
score = 0

import pygame as py
import random


class point:
    def __init__(self, row=0, col=0):
        self.row = row
        self.col = col

    def copy(self):
        return Point(self.row, self.col)


# Define the W (width) H (height) of the display window
W = 800
H = 800
snakes = [] # Define snake body list

flag=False#Whether to pause

def ge_food():
    while True:
        pos = Point(random.randint(0, ROW - 1), random.randint(0, COL - 1))
        is_collide = False
        if pos.row == head.row and pos.col == head.col: # coincide with the snake head
            is_collide = True
        # Collision with snake body
        for snake in snakes:
            if (snake.row == pos.row and snake.col == pos.col):
                is_collide = True
                break
        if not is_collide:
            return pos


ROW = 20 # number of rows
COL = 20 # number of columns
size = (W, H)
py.init() #Initialization interface
window = py.display.set_mode(size)
py.display.set_caption("Snake Battle")
bak_color = (255, 255, 255)
# Define snake head
head = Point(row=int(ROW / 2), col=int(COL / 2))
head_color = (0, 128, 128)
# define food
food = ge_food()
food_color = (255, 255, 0)

snake_color = (128, 128, 128)
direct = 'left'


def rect(point, color):
    cell_width = W/COL
    cell_height = H/ROW
    left = point.col * cell_width
    top = point.row * cell_height
    py.draw.rect(
        window, color,
        (left, top, cell_width, cell_height)
    )


image = py.image.load("huiworf.jpg")
new = py.transform.scale(image, (40, 40))
window.blit(new, (0, 0))

image = py.image.load("lan.jpg")
new1 = py.transform.scale(image, (40, 40))
window.blit(new1, (0, 0))

image = py.image.load("lan1.jpg")
new2 = py.transform.scale(image, (40, 40))
window.blit(new2, (0, 0))


def rect1(point):
    cell_width = W/COL
    cell_height = H/ROW
    left = point.col * cell_width
    top = point.row * cell_height
    #py.draw.rect(
    # window, color,
    # (left, top, cell_width, cell_height)
    # )
    window.blit(
        new,
        (left, top)
    )


def rect2(point):
    cell_width = W/COL
    cell_height = H/ROW
    left = point.col * cell_width
    top = point.row * cell_height
    #py.draw.rect(
    # window, color,
    # (left, top, cell_width, cell_height)
    # )
    window.blit(
        new1,
        (left, top)
    )


def rect3(point):
    cell_width = W/COL
    cell_height = H/ROW
    left = point.col * cell_width
    top = point.row * cell_height
    #py.draw.rect(
    # window, color,
    # (left, top, cell_width, cell_height)
    # )
    window.blit(
        new2,
        (left, top)
    )


showWindow = True
clock = py.time.Clock() # Clock control
while showWindow:
    # Handle events
    for event in py.event.get():
        if event.type == py.QUIT:
            showWindow = False
        if event.type == py.KEYDOWN:
            if event.key == py.K_UP:
                if direct == 'left' or direct == 'right':
                    direct = "top"
            elif event.key == py.K_DOWN:
                if direct == 'left' or direct == 'right':
                    direct = "down"
            elif event.key == py.K_LEFT:
                if direct == 'top' or direct == 'down':
                    direct = 'left'
            elif event.key == py.K_RIGHT:
                if direct == 'top' or direct == 'down':
                    direct = 'right'
        if event.type == py.KEYDOWN:
            if event.key == py.K_r:
                head = Point(row=int(ROW / 2), col=int(COL / 2))
                snakes=[]
                score = 0


            if event.key == py.K_q:
                flag=True
                while flag:
                    for event0 in py.event.get():
                        if event0.type == py.KEYDOWN:
                            if event0.key == py.K_s:

                                flag=False
                            if event.type == py.QUIT:
                                showWindow = False
                                break


    # Determine whether the snake has eaten something
    eat=False
    if head.row == food.row and head.col == food.col: # The snake eats food
        eat=True
    if eat: # When food is eaten, new food will be produced
        food = ge_food()
        score = score + 1
    # Insert the snake head into the snakes list
    snakes.insert(0, head.copy())
    # Delete the last element
    if not eat:
        snakes.pop()
    # Move snake head
    if direct == 'left':
        head.col -= 1 # Note that direct = 'left' and head.col-=1 cannot be written together because the snake head has to keep moving.
    elif direct == 'right':
        head.col + = 1
    elif direct == 'top':
        head.row -= 1
    else:
        head.row + = 1
    # Determine whether the snake is dead
    dead = False
    # Determine whether the snake hit the wall
    if head.col < 0 or head.row < 0 or head.row >= ROW or head.col >= COL:

        dead = True
    # Determine whether the snake has hit the snake body
    for snake in snakes:
        if snake.row == head.row and snake.col == head.col:
            dead = True
            break
    if dead:
        with open(file=r"Paihang.txt", mode="r", encoding="utf-8") as fb:
            bt = fb.readlines()
        diyi=int(bt[0].strip('\\
'))
        dier=int(bt[1].strip('\\
'))
        disan=int(bt[2].strip('\\
'))
        if score>diyi:
            disan=dier
            dier=diyi
            diyi=score
            with open(file=r"Paihang.txt", mode="w", encoding="utf-8") as fb:
                fb.write(str(diyi) + '\\
' + str(dier) + '\\
' + str(disan))
            break
        if score > dier:
            disan = dier
            dier = score
            with open(file=r"Paihang.txt", mode="w", encoding="utf-8") as fb:
                fb.write(str(diyi) + '\\
' + str(dier) + '\\
' + str(disan))
            break

        if score>disan:
            disan = score
            with open(file=r"Paihang.txt", mode="w", encoding="utf-8") as fb:
                fb.write(str(diyi) + '\\
' + str(dier) + '\\
' + str(disan))
            break

        with open(file=r"Paihang.txt", mode="w", encoding="utf-8") as fb:
            fb.write(str(diyi) + '\\
' + str(dier) + '\\
' + str(disan))
        showWindow = False
    # Page rendering
    py.draw.rect(window, bak_color, (0, 0, W, H))
    # It should be noted here that the food and snake heads should be drawn after drawing the background, because the black background color will cover everything.

    image = py.image.load("caoyuan.jpg")
    new0 = py.transform.scale(image, (800, 800))
    window.blit(new0, (0, 0))

    # draw snake head
    rect1(head)
    # draw snake body
    for snake in snakes:
        rect3(snake)
    #drawfood
    rect2(food)

    font = py.font.Font("HYShangWeiShouShuW.ttf", 30)
    text=font.render("score" + str(score) + '\t' + "q: Pause s: Start r: Restart",True,(0,0,0))
    window.blit(text,(0,0))



    py.display.flip() # Update the entire Surface object to be displayed to the screen
    clock.tick(int(speed)) # Set the frame rate, which can be used to control the speed of the snake head movement


test.py

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

import loginPaihang

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = QMainWindow()
    loginUi = loginPaihang.Ui_MainWindow()
    loginUi.setupUi(win)
    win.show()
    sys.exit(app.exec_())

login.py

# -*- coding: utf-8 -*-
import os

# Form implementation generated from reading ui file 'login.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt import MainWindow


class Ui_MainWindow(object):
    a=2

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1000, 1000)

        MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(100, 40, 800, 800))
        self.label.setStyleSheet("border-image: url(:/images/images/caoyuan.jpg);\\
"
"border-top-left-radius:5px;\\
"
"border-bottom-left-radius:5px;\\
"
"border-top-right-radius:5px;\\
"
"border-bottom-right-radius:5px;")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(440, 150, 171, 61))
        font = QtGui.QFont()
        font.setFamily("Bahnschrift SemiBold Condensed")
        font.setPointSize(27)
        font.setBold(False)
        font.setItalic(True)
        font.setUnderline(True)
        font.setWeight(50)
        font.setStrikeOut(True)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("color: rgb(85, 85, 127);")
        self.label_2.setObjectName("label_2")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(540, 310, 101, 71))
        font = QtGui.QFont()
        font.setPointSize(18)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.comboBox.setFont(font)
        self.comboBox.setStyleSheet("background-color: rgba(255, 255, 255, 80);\\
"
"")
        self.comboBox.setFrame(False)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(330, 310, 171, 71))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(420, 470, 181, 51))
        font = QtGui.QFont()
        font.setPointSize(18)
        font.setBold(False)
        font.setItalic(True)
        font.setWeight(50)
        self.pushButton.setFont(font)
        self.pushButton.setStyleSheet("#pushButton{\\
"
"background-color: rgb(255, 255, 255,80);\\
"
"color:rgb(0,0,0);\\
"
"border:3px solid rgb(255,255,255,80);\\
"
"border-radius:7px;\\
"
"}\\
"
"#pushButton:hover{\\
"
"background-color: rgb(0, 0, 0,80);\\
"
"color:rgb(255,255,255);\\
"
"}\\
"
"#pushButton:pressed{\\
"
"padding-top:5px;\\
"
"padding-left:5px\\
"
"}\\
"
"\\
"
"")
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(420, 560, 181, 51))
        font = QtGui.QFont()
        font.setPointSize(18)
        font.setItalic(True)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setStyleSheet("#pushButton_2{\\
"
"background-color: rgb(255, 255, 255,80);\\
"
"color:rgb(0,0,0);\\
"
"border:3px solid rgb(255,255,255,80);\\
"
"border-radius:7px;\\
"
"}\\
"
"#pushButton_2:hover{\\
"
"background-color: rgb(0, 0, 0,80);\\
"
"color:rgb(255,255,255);\\
"
"}\\
"
"#pushButton_2:pressed{\\
"
"padding-top:5px;\\
"
"padding-left:5px\\
"
"}\\
"
"\\
"
"")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(870, 40, 31, 31))
        self.pushButton_3.setStyleSheet("border-image: url(:/icons/icons/close.png);\\
"
"background-color: rgba(255, 255, 255, 0);")
        self.pushButton_3.setText("")
        self.pushButton_3.setObjectName("pushButton_3")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.pushButton_3.clicked.connect(MainWindow.close) # type: ignore
        self.pushButton_3.clicked.connect(self.Speed)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label_2.setText(_translate("MainWindow", "Wolf catching sheep"))
        self.comboBox.setItemText(0, _translate("MainWindow", "Simple"))
        self.comboBox.setItemText(1, _translate("MainWindow", "medium"))
        self.comboBox.setItemText(2, _translate("MainWindow", "difficulty"))
        self.label_3.setText(_translate("MainWindow", "Difficulty selection:"))
        self.pushButton.setText(_translate("MainWindow", "Start Game"))
        self.pushButton_2.setText(_translate("MainWindow", "Rankboard"))

        self.comboBox.currentIndexChanged[str].connect(self.nandu)
        self.pushButton.clicked.connect(self.Kaishi)
        self.pushButton_2.clicked.connect(self.Paihang)

    def nandu(self, i):
        self.a=2
        if i == "simple":
            self.a = 2
        elif i == "medium":
            self.a = 6
        elif i == "difficulty":
            self.a = 8
        else:
            self.a = 2
        f = open("speed.txt", mode='w')
        f.writelines(str(self.a))
        f.close()



    def Kaishi(self):
        os.system("youxi.py")

    def Paihang(self):
        os.system("test.py")

    def Speed(self):
        f = open("speed.txt", mode='w')
        f.writelines(str(2))
        f.close()




import resource_rc

loginPaihang.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'loginPaihang.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1000, 1000)

        MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(100, 40, 800, 800))
        self.label.setStyleSheet("border-image: url(:/images/images/caoyuan.jpg);\\
"
"border-top-left-radius:5px;\\
"
"border-bottom-left-radius:5px;\\
"
"border-top-right-radius:5px;\\
"
"border-bottom-right-radius:5px;")
        self.label.setText("")
        self.label.setObjectName("label")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(870, 40, 31, 31))
        self.pushButton_3.setStyleSheet("border-image: url(:/icons/icons/close.png);\\
"
"background-color: rgba(255, 255, 255, 0);")
        self.pushButton_3.setText("")
        self.pushButton_3.setObjectName("pushButton_3")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(161, 181, 200, 100))
        font = QtGui.QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(160, 280, 100, 100))
        font = QtGui.QFont()
        font.setPointSize(27)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("")
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(160, 380, 100, 100))
        font = QtGui.QFont()
        font.setPointSize(27)
        self.label_4.setFont(font)
        self.label_4.setStyleSheet("")
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(160, 480, 100, 100))
        font = QtGui.QFont()
        font.setPointSize(27)
        self.label_5.setFont(font)
        self.label_5.setStyleSheet("")
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(260, 280, 300, 100))
        font = QtGui.QFont()
        font.setPointSize(27)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(260, 380, 300, 100))
        font = QtGui.QFont()
        font.setPointSize(27)
        self.label_7.setFont(font)
        self.label_7.setObjectName("label_7")
        self.label_8 = QtWidgets.QLabel(self.centralwidget)
        self.label_8.setGeometry(QtCore.QRect(260, 480, 300, 100))
        font = QtGui.QFont()
        font.setPointSize(27)
        self.label_8.setFont(font)
        self.label_8.setObjectName("label_8")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.pushButton_3.clicked.connect(MainWindow.close) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label_2.setText(_translate("MainWindow", "ranking list"))
        self.label_3.setText(_translate("MainWindow", "1."))
        self.label_4.setText(_translate("MainWindow", "2."))
        self.label_5.setText(_translate("MainWindow", "3."))

        with open(file=r"Paihang.txt", mode="r", encoding="utf-8") as fb:
            bt = fb.readlines()
        diyi=bt[0].strip('\\
')
        dier=bt[1].strip('\\
')
        disan=bt[2].strip('\\
')

        self.label_6.setText(_translate("MainWindow", str(diyi)))
        self.label_7.setText(_translate("MainWindow", str(dier)))
        self.label_8.setText(_translate("MainWindow", str(disan)))
import resource_rc

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeHomepageOverview 374849 people are learning the system